1 //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Pass to verify generated machine code. The following is checked:
12 // Operand counts: All explicit operands must be present.
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
26 #include "LiveRangeCalc.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SetOperations.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/EHPersonalities.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
39 #include "llvm/CodeGen/LiveInterval.h"
40 #include "llvm/CodeGen/LiveIntervals.h"
41 #include "llvm/CodeGen/LiveStacks.h"
42 #include "llvm/CodeGen/LiveVariables.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBundle.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/PseudoSourceValue.h"
53 #include "llvm/CodeGen/SlotIndexes.h"
54 #include "llvm/CodeGen/StackMaps.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetOpcodes.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/MC/LaneBitmask.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCInstrDesc.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/MC/MCTargetOptions.h"
68 #include "llvm/Pass.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/LowLevelTypeImpl.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetMachine.h"
87 struct MachineVerifier
{
88 MachineVerifier(Pass
*pass
, const char *b
) : PASS(pass
), Banner(b
) {}
90 unsigned verify(MachineFunction
&MF
);
94 const MachineFunction
*MF
;
95 const TargetMachine
*TM
;
96 const TargetInstrInfo
*TII
;
97 const TargetRegisterInfo
*TRI
;
98 const MachineRegisterInfo
*MRI
;
100 unsigned foundErrors
;
102 // Avoid querying the MachineFunctionProperties for each operand.
103 bool isFunctionRegBankSelected
;
104 bool isFunctionSelected
;
106 using RegVector
= SmallVector
<unsigned, 16>;
107 using RegMaskVector
= SmallVector
<const uint32_t *, 4>;
108 using RegSet
= DenseSet
<unsigned>;
109 using RegMap
= DenseMap
<unsigned, const MachineInstr
*>;
110 using BlockSet
= SmallPtrSet
<const MachineBasicBlock
*, 8>;
112 const MachineInstr
*FirstTerminator
;
113 BlockSet FunctionBlocks
;
115 BitVector regsReserved
;
117 RegVector regsDefined
, regsDead
, regsKilled
;
118 RegMaskVector regMasks
;
122 // Add Reg and any sub-registers to RV
123 void addRegWithSubRegs(RegVector
&RV
, unsigned Reg
) {
125 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
126 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid(); ++SubRegs
)
127 RV
.push_back(*SubRegs
);
131 // Is this MBB reachable from the MF entry point?
132 bool reachable
= false;
134 // Vregs that must be live in because they are used without being
135 // defined. Map value is the user.
138 // Regs killed in MBB. They may be defined again, and will then be in both
139 // regsKilled and regsLiveOut.
142 // Regs defined in MBB and live out. Note that vregs passing through may
143 // be live out without being mentioned here.
146 // Vregs that pass through MBB untouched. This set is disjoint from
147 // regsKilled and regsLiveOut.
150 // Vregs that must pass through MBB because they are needed by a successor
151 // block. This set is disjoint from regsLiveOut.
152 RegSet vregsRequired
;
154 // Set versions of block's predecessor and successor lists.
155 BlockSet Preds
, Succs
;
159 // Add register to vregsPassed if it belongs there. Return true if
161 bool addPassed(unsigned Reg
) {
162 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
164 if (regsKilled
.count(Reg
) || regsLiveOut
.count(Reg
))
166 return vregsPassed
.insert(Reg
).second
;
169 // Same for a full set.
170 bool addPassed(const RegSet
&RS
) {
171 bool changed
= false;
172 for (RegSet::const_iterator I
= RS
.begin(), E
= RS
.end(); I
!= E
; ++I
)
178 // Add register to vregsRequired if it belongs there. Return true if
180 bool addRequired(unsigned Reg
) {
181 if (!TargetRegisterInfo::isVirtualRegister(Reg
))
183 if (regsLiveOut
.count(Reg
))
185 return vregsRequired
.insert(Reg
).second
;
188 // Same for a full set.
189 bool addRequired(const RegSet
&RS
) {
190 bool changed
= false;
191 for (RegSet::const_iterator I
= RS
.begin(), E
= RS
.end(); I
!= E
; ++I
)
197 // Same for a full map.
198 bool addRequired(const RegMap
&RM
) {
199 bool changed
= false;
200 for (RegMap::const_iterator I
= RM
.begin(), E
= RM
.end(); I
!= E
; ++I
)
201 if (addRequired(I
->first
))
206 // Live-out registers are either in regsLiveOut or vregsPassed.
207 bool isLiveOut(unsigned Reg
) const {
208 return regsLiveOut
.count(Reg
) || vregsPassed
.count(Reg
);
212 // Extra register info per MBB.
213 DenseMap
<const MachineBasicBlock
*, BBInfo
> MBBInfoMap
;
215 bool isReserved(unsigned Reg
) {
216 return Reg
< regsReserved
.size() && regsReserved
.test(Reg
);
219 bool isAllocatable(unsigned Reg
) const {
220 return Reg
< TRI
->getNumRegs() && TRI
->isInAllocatableClass(Reg
) &&
221 !regsReserved
.test(Reg
);
224 // Analysis information if available
225 LiveVariables
*LiveVars
;
226 LiveIntervals
*LiveInts
;
227 LiveStacks
*LiveStks
;
228 SlotIndexes
*Indexes
;
230 void visitMachineFunctionBefore();
231 void visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
);
232 void visitMachineBundleBefore(const MachineInstr
*MI
);
233 void visitMachineInstrBefore(const MachineInstr
*MI
);
234 void visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
);
235 void visitMachineInstrAfter(const MachineInstr
*MI
);
236 void visitMachineBundleAfter(const MachineInstr
*MI
);
237 void visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
);
238 void visitMachineFunctionAfter();
240 void report(const char *msg
, const MachineFunction
*MF
);
241 void report(const char *msg
, const MachineBasicBlock
*MBB
);
242 void report(const char *msg
, const MachineInstr
*MI
);
243 void report(const char *msg
, const MachineOperand
*MO
, unsigned MONum
,
244 LLT MOVRegType
= LLT
{});
246 void report_context(const LiveInterval
&LI
) const;
247 void report_context(const LiveRange
&LR
, unsigned VRegUnit
,
248 LaneBitmask LaneMask
) const;
249 void report_context(const LiveRange::Segment
&S
) const;
250 void report_context(const VNInfo
&VNI
) const;
251 void report_context(SlotIndex Pos
) const;
252 void report_context_liverange(const LiveRange
&LR
) const;
253 void report_context_lanemask(LaneBitmask LaneMask
) const;
254 void report_context_vreg(unsigned VReg
) const;
255 void report_context_vreg_regunit(unsigned VRegOrUnit
) const;
257 void verifyInlineAsm(const MachineInstr
*MI
);
259 void checkLiveness(const MachineOperand
*MO
, unsigned MONum
);
260 void checkLivenessAtUse(const MachineOperand
*MO
, unsigned MONum
,
261 SlotIndex UseIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
262 LaneBitmask LaneMask
= LaneBitmask::getNone());
263 void checkLivenessAtDef(const MachineOperand
*MO
, unsigned MONum
,
264 SlotIndex DefIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
265 LaneBitmask LaneMask
= LaneBitmask::getNone());
267 void markReachable(const MachineBasicBlock
*MBB
);
268 void calcRegsPassed();
269 void checkPHIOps(const MachineBasicBlock
&MBB
);
271 void calcRegsRequired();
272 void verifyLiveVariables();
273 void verifyLiveIntervals();
274 void verifyLiveInterval(const LiveInterval
&);
275 void verifyLiveRangeValue(const LiveRange
&, const VNInfo
*, unsigned,
277 void verifyLiveRangeSegment(const LiveRange
&,
278 const LiveRange::const_iterator I
, unsigned,
280 void verifyLiveRange(const LiveRange
&, unsigned,
281 LaneBitmask LaneMask
= LaneBitmask::getNone());
283 void verifyStackFrame();
285 void verifySlotIndexes() const;
286 void verifyProperties(const MachineFunction
&MF
);
289 struct MachineVerifierPass
: public MachineFunctionPass
{
290 static char ID
; // Pass ID, replacement for typeid
292 const std::string Banner
;
294 MachineVerifierPass(std::string banner
= std::string())
295 : MachineFunctionPass(ID
), Banner(std::move(banner
)) {
296 initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
299 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
300 AU
.setPreservesAll();
301 MachineFunctionPass::getAnalysisUsage(AU
);
304 bool runOnMachineFunction(MachineFunction
&MF
) override
{
305 unsigned FoundErrors
= MachineVerifier(this, Banner
.c_str()).verify(MF
);
307 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
312 } // end anonymous namespace
314 char MachineVerifierPass::ID
= 0;
316 INITIALIZE_PASS(MachineVerifierPass
, "machineverifier",
317 "Verify generated machine code", false, false)
319 FunctionPass
*llvm::createMachineVerifierPass(const std::string
&Banner
) {
320 return new MachineVerifierPass(Banner
);
323 bool MachineFunction::verify(Pass
*p
, const char *Banner
, bool AbortOnErrors
)
325 MachineFunction
&MF
= const_cast<MachineFunction
&>(*this);
326 unsigned FoundErrors
= MachineVerifier(p
, Banner
).verify(MF
);
327 if (AbortOnErrors
&& FoundErrors
)
328 report_fatal_error("Found "+Twine(FoundErrors
)+" machine code errors.");
329 return FoundErrors
== 0;
332 void MachineVerifier::verifySlotIndexes() const {
333 if (Indexes
== nullptr)
336 // Ensure the IdxMBB list is sorted by slot indexes.
338 for (SlotIndexes::MBBIndexIterator I
= Indexes
->MBBIndexBegin(),
339 E
= Indexes
->MBBIndexEnd(); I
!= E
; ++I
) {
340 assert(!Last
.isValid() || I
->first
> Last
);
345 void MachineVerifier::verifyProperties(const MachineFunction
&MF
) {
346 // If a pass has introduced virtual registers without clearing the
347 // NoVRegs property (or set it without allocating the vregs)
348 // then report an error.
349 if (MF
.getProperties().hasProperty(
350 MachineFunctionProperties::Property::NoVRegs
) &&
351 MRI
->getNumVirtRegs())
352 report("Function has NoVRegs property but there are VReg operands", &MF
);
355 unsigned MachineVerifier::verify(MachineFunction
&MF
) {
359 TM
= &MF
.getTarget();
360 TII
= MF
.getSubtarget().getInstrInfo();
361 TRI
= MF
.getSubtarget().getRegisterInfo();
362 MRI
= &MF
.getRegInfo();
364 const bool isFunctionFailedISel
= MF
.getProperties().hasProperty(
365 MachineFunctionProperties::Property::FailedISel
);
366 isFunctionRegBankSelected
=
367 !isFunctionFailedISel
&&
368 MF
.getProperties().hasProperty(
369 MachineFunctionProperties::Property::RegBankSelected
);
370 isFunctionSelected
= !isFunctionFailedISel
&&
371 MF
.getProperties().hasProperty(
372 MachineFunctionProperties::Property::Selected
);
378 LiveInts
= PASS
->getAnalysisIfAvailable
<LiveIntervals
>();
379 // We don't want to verify LiveVariables if LiveIntervals is available.
381 LiveVars
= PASS
->getAnalysisIfAvailable
<LiveVariables
>();
382 LiveStks
= PASS
->getAnalysisIfAvailable
<LiveStacks
>();
383 Indexes
= PASS
->getAnalysisIfAvailable
<SlotIndexes
>();
388 verifyProperties(MF
);
390 visitMachineFunctionBefore();
391 for (MachineFunction::const_iterator MFI
= MF
.begin(), MFE
= MF
.end();
393 visitMachineBasicBlockBefore(&*MFI
);
394 // Keep track of the current bundle header.
395 const MachineInstr
*CurBundle
= nullptr;
396 // Do we expect the next instruction to be part of the same bundle?
397 bool InBundle
= false;
399 for (MachineBasicBlock::const_instr_iterator MBBI
= MFI
->instr_begin(),
400 MBBE
= MFI
->instr_end(); MBBI
!= MBBE
; ++MBBI
) {
401 if (MBBI
->getParent() != &*MFI
) {
402 report("Bad instruction parent pointer", &*MFI
);
403 errs() << "Instruction: " << *MBBI
;
407 // Check for consistent bundle flags.
408 if (InBundle
&& !MBBI
->isBundledWithPred())
409 report("Missing BundledPred flag, "
410 "BundledSucc was set on predecessor",
412 if (!InBundle
&& MBBI
->isBundledWithPred())
413 report("BundledPred flag is set, "
414 "but BundledSucc not set on predecessor",
417 // Is this a bundle header?
418 if (!MBBI
->isInsideBundle()) {
420 visitMachineBundleAfter(CurBundle
);
422 visitMachineBundleBefore(CurBundle
);
423 } else if (!CurBundle
)
424 report("No bundle header", &*MBBI
);
425 visitMachineInstrBefore(&*MBBI
);
426 for (unsigned I
= 0, E
= MBBI
->getNumOperands(); I
!= E
; ++I
) {
427 const MachineInstr
&MI
= *MBBI
;
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
);
435 visitMachineOperand(&Op
, I
);
438 visitMachineInstrAfter(&*MBBI
);
440 // Was this the last bundled instruction?
441 InBundle
= MBBI
->isBundledWithSucc();
444 visitMachineBundleAfter(CurBundle
);
446 report("BundledSucc flag set on last instruction in block", &MFI
->back());
447 visitMachineBasicBlockAfter(&*MFI
);
449 visitMachineFunctionAfter();
462 void MachineVerifier::report(const char *msg
, const MachineFunction
*MF
) {
465 if (!foundErrors
++) {
467 errs() << "# " << Banner
<< '\n';
468 if (LiveInts
!= nullptr)
469 LiveInts
->print(errs());
471 MF
->print(errs(), Indexes
);
473 errs() << "*** Bad machine code: " << msg
<< " ***\n"
474 << "- function: " << MF
->getName() << "\n";
477 void MachineVerifier::report(const char *msg
, const MachineBasicBlock
*MBB
) {
479 report(msg
, MBB
->getParent());
480 errs() << "- basic block: " << printMBBReference(*MBB
) << ' '
481 << MBB
->getName() << " (" << (const void *)MBB
<< ')';
483 errs() << " [" << Indexes
->getMBBStartIdx(MBB
)
484 << ';' << Indexes
->getMBBEndIdx(MBB
) << ')';
488 void MachineVerifier::report(const char *msg
, const MachineInstr
*MI
) {
490 report(msg
, MI
->getParent());
491 errs() << "- instruction: ";
492 if (Indexes
&& Indexes
->hasIndex(*MI
))
493 errs() << Indexes
->getInstructionIndex(*MI
) << '\t';
494 MI
->print(errs(), /*SkipOpers=*/true);
497 void MachineVerifier::report(const char *msg
, const MachineOperand
*MO
,
498 unsigned MONum
, LLT MOVRegType
) {
500 report(msg
, MO
->getParent());
501 errs() << "- operand " << MONum
<< ": ";
502 MO
->print(errs(), MOVRegType
, TRI
);
506 void MachineVerifier::report_context(SlotIndex Pos
) const {
507 errs() << "- at: " << Pos
<< '\n';
510 void MachineVerifier::report_context(const LiveInterval
&LI
) const {
511 errs() << "- interval: " << LI
<< '\n';
514 void MachineVerifier::report_context(const LiveRange
&LR
, unsigned VRegUnit
,
515 LaneBitmask LaneMask
) const {
516 report_context_liverange(LR
);
517 report_context_vreg_regunit(VRegUnit
);
519 report_context_lanemask(LaneMask
);
522 void MachineVerifier::report_context(const LiveRange::Segment
&S
) const {
523 errs() << "- segment: " << S
<< '\n';
526 void MachineVerifier::report_context(const VNInfo
&VNI
) const {
527 errs() << "- ValNo: " << VNI
.id
<< " (def " << VNI
.def
<< ")\n";
530 void MachineVerifier::report_context_liverange(const LiveRange
&LR
) const {
531 errs() << "- liverange: " << LR
<< '\n';
534 void MachineVerifier::report_context_vreg(unsigned VReg
) const {
535 errs() << "- v. register: " << printReg(VReg
, TRI
) << '\n';
538 void MachineVerifier::report_context_vreg_regunit(unsigned VRegOrUnit
) const {
539 if (TargetRegisterInfo::isVirtualRegister(VRegOrUnit
)) {
540 report_context_vreg(VRegOrUnit
);
542 errs() << "- regunit: " << printRegUnit(VRegOrUnit
, TRI
) << '\n';
546 void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask
) const {
547 errs() << "- lanemask: " << PrintLaneMask(LaneMask
) << '\n';
550 void MachineVerifier::markReachable(const MachineBasicBlock
*MBB
) {
551 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
552 if (!MInfo
.reachable
) {
553 MInfo
.reachable
= true;
554 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
->succ_begin(),
555 SuE
= MBB
->succ_end(); SuI
!= SuE
; ++SuI
)
560 void MachineVerifier::visitMachineFunctionBefore() {
561 lastIndex
= SlotIndex();
562 regsReserved
= MRI
->reservedRegsFrozen() ? MRI
->getReservedRegs()
563 : TRI
->getReservedRegs(*MF
);
566 markReachable(&MF
->front());
568 // Build a set of the basic blocks in the function.
569 FunctionBlocks
.clear();
570 for (const auto &MBB
: *MF
) {
571 FunctionBlocks
.insert(&MBB
);
572 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
574 MInfo
.Preds
.insert(MBB
.pred_begin(), MBB
.pred_end());
575 if (MInfo
.Preds
.size() != MBB
.pred_size())
576 report("MBB has duplicate entries in its predecessor list.", &MBB
);
578 MInfo
.Succs
.insert(MBB
.succ_begin(), MBB
.succ_end());
579 if (MInfo
.Succs
.size() != MBB
.succ_size())
580 report("MBB has duplicate entries in its successor list.", &MBB
);
583 // Check that the register use lists are sane.
584 MRI
->verifyUseLists();
590 // Does iterator point to a and b as the first two elements?
591 static bool matchPair(MachineBasicBlock::const_succ_iterator i
,
592 const MachineBasicBlock
*a
, const MachineBasicBlock
*b
) {
601 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock
*MBB
) {
602 FirstTerminator
= nullptr;
604 if (!MF
->getProperties().hasProperty(
605 MachineFunctionProperties::Property::NoPHIs
) && MRI
->tracksLiveness()) {
606 // If this block has allocatable physical registers live-in, check that
607 // it is an entry block or landing pad.
608 for (const auto &LI
: MBB
->liveins()) {
609 if (isAllocatable(LI
.PhysReg
) && !MBB
->isEHPad() &&
610 MBB
->getIterator() != MBB
->getParent()->begin()) {
611 report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB
);
616 // Count the number of landing pad successors.
617 SmallPtrSet
<MachineBasicBlock
*, 4> LandingPadSuccs
;
618 for (MachineBasicBlock::const_succ_iterator I
= MBB
->succ_begin(),
619 E
= MBB
->succ_end(); I
!= E
; ++I
) {
621 LandingPadSuccs
.insert(*I
);
622 if (!FunctionBlocks
.count(*I
))
623 report("MBB has successor that isn't part of the function.", MBB
);
624 if (!MBBInfoMap
[*I
].Preds
.count(MBB
)) {
625 report("Inconsistent CFG", MBB
);
626 errs() << "MBB is not in the predecessor list of the successor "
627 << printMBBReference(*(*I
)) << ".\n";
631 // Check the predecessor list.
632 for (MachineBasicBlock::const_pred_iterator I
= MBB
->pred_begin(),
633 E
= MBB
->pred_end(); I
!= E
; ++I
) {
634 if (!FunctionBlocks
.count(*I
))
635 report("MBB has predecessor that isn't part of the function.", MBB
);
636 if (!MBBInfoMap
[*I
].Succs
.count(MBB
)) {
637 report("Inconsistent CFG", MBB
);
638 errs() << "MBB is not in the successor list of the predecessor "
639 << printMBBReference(*(*I
)) << ".\n";
643 const MCAsmInfo
*AsmInfo
= TM
->getMCAsmInfo();
644 const BasicBlock
*BB
= MBB
->getBasicBlock();
645 const Function
&F
= MF
->getFunction();
646 if (LandingPadSuccs
.size() > 1 &&
648 AsmInfo
->getExceptionHandlingType() == ExceptionHandling::SjLj
&&
649 BB
&& isa
<SwitchInst
>(BB
->getTerminator())) &&
650 !isScopedEHPersonality(classifyEHPersonality(F
.getPersonalityFn())))
651 report("MBB has more than one landing pad successor", MBB
);
653 // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
654 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
655 SmallVector
<MachineOperand
, 4> Cond
;
656 if (!TII
->analyzeBranch(*const_cast<MachineBasicBlock
*>(MBB
), TBB
, FBB
,
658 // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
659 // check whether its answers match up with reality.
661 // Block falls through to its successor.
662 MachineFunction::const_iterator MBBI
= MBB
->getIterator();
664 if (MBBI
== MF
->end()) {
665 // It's possible that the block legitimately ends with a noreturn
666 // call or an unreachable, in which case it won't actually fall
667 // out the bottom of the function.
668 } else if (MBB
->succ_size() == LandingPadSuccs
.size()) {
669 // It's possible that the block legitimately ends with a noreturn
670 // call or an unreachable, in which case it won't actuall fall
672 } else if (MBB
->succ_size() != 1+LandingPadSuccs
.size()) {
673 report("MBB exits via unconditional fall-through but doesn't have "
674 "exactly one CFG successor!", MBB
);
675 } else if (!MBB
->isSuccessor(&*MBBI
)) {
676 report("MBB exits via unconditional fall-through but its successor "
677 "differs from its CFG successor!", MBB
);
679 if (!MBB
->empty() && MBB
->back().isBarrier() &&
680 !TII
->isPredicated(MBB
->back())) {
681 report("MBB exits via unconditional fall-through but ends with a "
682 "barrier instruction!", MBB
);
685 report("MBB exits via unconditional fall-through but has a condition!",
688 } else if (TBB
&& !FBB
&& Cond
.empty()) {
689 // Block unconditionally branches somewhere.
690 // If the block has exactly one successor, that happens to be a
691 // landingpad, accept it as valid control flow.
692 if (MBB
->succ_size() != 1+LandingPadSuccs
.size() &&
693 (MBB
->succ_size() != 1 || LandingPadSuccs
.size() != 1 ||
694 *MBB
->succ_begin() != *LandingPadSuccs
.begin())) {
695 report("MBB exits via unconditional branch but doesn't have "
696 "exactly one CFG successor!", MBB
);
697 } else if (!MBB
->isSuccessor(TBB
)) {
698 report("MBB exits via unconditional branch but the CFG "
699 "successor doesn't match the actual successor!", MBB
);
702 report("MBB exits via unconditional branch but doesn't contain "
703 "any instructions!", MBB
);
704 } else if (!MBB
->back().isBarrier()) {
705 report("MBB exits via unconditional branch but doesn't end with a "
706 "barrier instruction!", MBB
);
707 } else if (!MBB
->back().isTerminator()) {
708 report("MBB exits via unconditional branch but the branch isn't a "
709 "terminator instruction!", MBB
);
711 } else if (TBB
&& !FBB
&& !Cond
.empty()) {
712 // Block conditionally branches somewhere, otherwise falls through.
713 MachineFunction::const_iterator MBBI
= MBB
->getIterator();
715 if (MBBI
== MF
->end()) {
716 report("MBB conditionally falls through out of function!", MBB
);
717 } else if (MBB
->succ_size() == 1) {
718 // A conditional branch with only one successor is weird, but allowed.
720 report("MBB exits via conditional branch/fall-through but only has "
721 "one CFG successor!", MBB
);
722 else if (TBB
!= *MBB
->succ_begin())
723 report("MBB exits via conditional branch/fall-through but the CFG "
724 "successor don't match the actual successor!", MBB
);
725 } else if (MBB
->succ_size() != 2) {
726 report("MBB exits via conditional branch/fall-through but doesn't have "
727 "exactly two CFG successors!", MBB
);
728 } else if (!matchPair(MBB
->succ_begin(), TBB
, &*MBBI
)) {
729 report("MBB exits via conditional branch/fall-through but the CFG "
730 "successors don't match the actual successors!", MBB
);
733 report("MBB exits via conditional branch/fall-through but doesn't "
734 "contain any instructions!", MBB
);
735 } else if (MBB
->back().isBarrier()) {
736 report("MBB exits via conditional branch/fall-through but ends with a "
737 "barrier instruction!", MBB
);
738 } else if (!MBB
->back().isTerminator()) {
739 report("MBB exits via conditional branch/fall-through but the branch "
740 "isn't a terminator instruction!", MBB
);
742 } else if (TBB
&& FBB
) {
743 // Block conditionally branches somewhere, otherwise branches
745 if (MBB
->succ_size() == 1) {
746 // A conditional branch with only one successor is weird, but allowed.
748 report("MBB exits via conditional branch/branch through but only has "
749 "one CFG successor!", MBB
);
750 else if (TBB
!= *MBB
->succ_begin())
751 report("MBB exits via conditional branch/branch through but the CFG "
752 "successor don't match the actual successor!", MBB
);
753 } else if (MBB
->succ_size() != 2) {
754 report("MBB exits via conditional branch/branch but doesn't have "
755 "exactly two CFG successors!", MBB
);
756 } else if (!matchPair(MBB
->succ_begin(), TBB
, FBB
)) {
757 report("MBB exits via conditional branch/branch but the CFG "
758 "successors don't match the actual successors!", MBB
);
761 report("MBB exits via conditional branch/branch but doesn't "
762 "contain any instructions!", MBB
);
763 } else if (!MBB
->back().isBarrier()) {
764 report("MBB exits via conditional branch/branch but doesn't end with a "
765 "barrier instruction!", MBB
);
766 } else if (!MBB
->back().isTerminator()) {
767 report("MBB exits via conditional branch/branch but the branch "
768 "isn't a terminator instruction!", MBB
);
771 report("MBB exits via conditinal branch/branch but there's no "
775 report("AnalyzeBranch returned invalid data!", MBB
);
780 if (MRI
->tracksLiveness()) {
781 for (const auto &LI
: MBB
->liveins()) {
782 if (!TargetRegisterInfo::isPhysicalRegister(LI
.PhysReg
)) {
783 report("MBB live-in list contains non-physical register", MBB
);
786 for (MCSubRegIterator
SubRegs(LI
.PhysReg
, TRI
, /*IncludeSelf=*/true);
787 SubRegs
.isValid(); ++SubRegs
)
788 regsLive
.insert(*SubRegs
);
792 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
793 BitVector PR
= MFI
.getPristineRegs(*MF
);
794 for (unsigned I
: PR
.set_bits()) {
795 for (MCSubRegIterator
SubRegs(I
, TRI
, /*IncludeSelf=*/true);
796 SubRegs
.isValid(); ++SubRegs
)
797 regsLive
.insert(*SubRegs
);
804 lastIndex
= Indexes
->getMBBStartIdx(MBB
);
807 // This function gets called for all bundle headers, including normal
808 // stand-alone unbundled instructions.
809 void MachineVerifier::visitMachineBundleBefore(const MachineInstr
*MI
) {
810 if (Indexes
&& Indexes
->hasIndex(*MI
)) {
811 SlotIndex idx
= Indexes
->getInstructionIndex(*MI
);
812 if (!(idx
> lastIndex
)) {
813 report("Instruction index out of order", MI
);
814 errs() << "Last instruction was at " << lastIndex
<< '\n';
819 // Ensure non-terminators don't follow terminators.
820 // Ignore predicated terminators formed by if conversion.
821 // FIXME: If conversion shouldn't need to violate this rule.
822 if (MI
->isTerminator() && !TII
->isPredicated(*MI
)) {
823 if (!FirstTerminator
)
824 FirstTerminator
= MI
;
825 } else if (FirstTerminator
) {
826 report("Non-terminator instruction after the first terminator", MI
);
827 errs() << "First terminator was:\t" << *FirstTerminator
;
831 // The operands on an INLINEASM instruction must follow a template.
832 // Verify that the flag operands make sense.
833 void MachineVerifier::verifyInlineAsm(const MachineInstr
*MI
) {
834 // The first two operands on INLINEASM are the asm string and global flags.
835 if (MI
->getNumOperands() < 2) {
836 report("Too few operands on inline asm", MI
);
839 if (!MI
->getOperand(0).isSymbol())
840 report("Asm string must be an external symbol", MI
);
841 if (!MI
->getOperand(1).isImm())
842 report("Asm flags must be an immediate", MI
);
843 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
844 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
845 // and Extra_IsConvergent = 32.
846 if (!isUInt
<6>(MI
->getOperand(1).getImm()))
847 report("Unknown asm flags", &MI
->getOperand(1), 1);
849 static_assert(InlineAsm::MIOp_FirstOperand
== 2, "Asm format changed");
851 unsigned OpNo
= InlineAsm::MIOp_FirstOperand
;
853 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; OpNo
+= NumOps
) {
854 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
855 // There may be implicit ops after the fixed operands.
858 NumOps
= 1 + InlineAsm::getNumOperandRegisters(MO
.getImm());
861 if (OpNo
> MI
->getNumOperands())
862 report("Missing operands in last group", MI
);
864 // An optional MDNode follows the groups.
865 if (OpNo
< MI
->getNumOperands() && MI
->getOperand(OpNo
).isMetadata())
868 // All trailing operands must be implicit registers.
869 for (unsigned e
= MI
->getNumOperands(); OpNo
< e
; ++OpNo
) {
870 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
871 if (!MO
.isReg() || !MO
.isImplicit())
872 report("Expected implicit register after groups", &MO
, OpNo
);
876 void MachineVerifier::visitMachineInstrBefore(const MachineInstr
*MI
) {
877 const MCInstrDesc
&MCID
= MI
->getDesc();
878 if (MI
->getNumOperands() < MCID
.getNumOperands()) {
879 report("Too few operands", MI
);
880 errs() << MCID
.getNumOperands() << " operands expected, but "
881 << MI
->getNumOperands() << " given.\n";
884 if (MI
->isPHI() && MF
->getProperties().hasProperty(
885 MachineFunctionProperties::Property::NoPHIs
))
886 report("Found PHI instruction with NoPHIs property set", MI
);
888 // Check the tied operands.
889 if (MI
->isInlineAsm())
892 // Check the MachineMemOperands for basic consistency.
893 for (MachineInstr::mmo_iterator I
= MI
->memoperands_begin(),
894 E
= MI
->memoperands_end();
896 if ((*I
)->isLoad() && !MI
->mayLoad())
897 report("Missing mayLoad flag", MI
);
898 if ((*I
)->isStore() && !MI
->mayStore())
899 report("Missing mayStore flag", MI
);
902 // Debug values must not have a slot index.
903 // Other instructions must have one, unless they are inside a bundle.
905 bool mapped
= !LiveInts
->isNotInMIMap(*MI
);
906 if (MI
->isDebugInstr()) {
908 report("Debug instruction has a slot index", MI
);
909 } else if (MI
->isInsideBundle()) {
911 report("Instruction inside bundle has a slot index", MI
);
914 report("Missing slot index", MI
);
918 if (isPreISelGenericOpcode(MCID
.getOpcode())) {
919 if (isFunctionSelected
)
920 report("Unexpected generic instruction in a Selected function", MI
);
923 SmallVector
<LLT
, 4> Types
;
924 for (unsigned I
= 0; I
< MCID
.getNumOperands(); ++I
) {
925 if (!MCID
.OpInfo
[I
].isGenericType())
927 // Generic instructions specify type equality constraints between some of
928 // their operands. Make sure these are consistent.
929 size_t TypeIdx
= MCID
.OpInfo
[I
].getGenericTypeIndex();
930 Types
.resize(std::max(TypeIdx
+ 1, Types
.size()));
932 const MachineOperand
*MO
= &MI
->getOperand(I
);
933 LLT OpTy
= MRI
->getType(MO
->getReg());
934 // Don't report a type mismatch if there is no actual mismatch, only a
935 // type missing, to reduce noise:
936 if (OpTy
.isValid()) {
937 // Only the first valid type for a type index will be printed: don't
938 // overwrite it later so it's always clear which type was expected:
939 if (!Types
[TypeIdx
].isValid())
940 Types
[TypeIdx
] = OpTy
;
941 else if (Types
[TypeIdx
] != OpTy
)
942 report("Type mismatch in generic instruction", MO
, I
, OpTy
);
944 // Generic instructions must have types attached to their operands.
945 report("Generic instruction is missing a virtual register type", MO
, I
);
949 // Generic opcodes must not have physical register operands.
950 for (unsigned I
= 0; I
< MI
->getNumOperands(); ++I
) {
951 const MachineOperand
*MO
= &MI
->getOperand(I
);
952 if (MO
->isReg() && TargetRegisterInfo::isPhysicalRegister(MO
->getReg()))
953 report("Generic instruction cannot have physical register", MO
, I
);
958 if (!TII
->verifyInstruction(*MI
, ErrorInfo
))
959 report(ErrorInfo
.data(), MI
);
961 // Verify properties of various specific instruction types
962 switch(MI
->getOpcode()) {
965 case TargetOpcode::G_LOAD
:
966 case TargetOpcode::G_STORE
:
967 // Generic loads and stores must have a single MachineMemOperand
968 // describing that access.
969 if (!MI
->hasOneMemOperand())
970 report("Generic instruction accessing memory must have one mem operand",
973 case TargetOpcode::G_PHI
: {
974 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
975 if (!DstTy
.isValid() ||
976 !std::all_of(MI
->operands_begin() + 1, MI
->operands_end(),
977 [this, &DstTy
](const MachineOperand
&MO
) {
980 LLT Ty
= MRI
->getType(MO
.getReg());
981 if (!Ty
.isValid() || (Ty
!= DstTy
))
985 report("Generic Instruction G_PHI has operands with incompatible/missing "
990 case TargetOpcode::G_SEXT
:
991 case TargetOpcode::G_ZEXT
:
992 case TargetOpcode::G_ANYEXT
:
993 case TargetOpcode::G_TRUNC
:
994 case TargetOpcode::G_FPEXT
:
995 case TargetOpcode::G_FPTRUNC
: {
996 // Number of operands and presense of types is already checked (and
997 // reported in case of any issues), so no need to report them again. As
998 // we're trying to report as many issues as possible at once, however, the
999 // instructions aren't guaranteed to have the right number of operands or
1000 // types attached to them at this point
1001 assert(MCID
.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1002 if (MI
->getNumOperands() < MCID
.getNumOperands())
1004 LLT DstTy
= MRI
->getType(MI
->getOperand(0).getReg());
1005 LLT SrcTy
= MRI
->getType(MI
->getOperand(1).getReg());
1006 if (!DstTy
.isValid() || !SrcTy
.isValid())
1009 LLT DstElTy
= DstTy
.isVector() ? DstTy
.getElementType() : DstTy
;
1010 LLT SrcElTy
= SrcTy
.isVector() ? SrcTy
.getElementType() : SrcTy
;
1011 if (DstElTy
.isPointer() || SrcElTy
.isPointer())
1012 report("Generic extend/truncate can not operate on pointers", MI
);
1014 if (DstTy
.isVector() != SrcTy
.isVector()) {
1015 report("Generic extend/truncate must be all-vector or all-scalar", MI
);
1016 // Generally we try to report as many issues as possible at once, but in
1017 // this case it's not clear what should we be comparing the size of the
1018 // scalar with: the size of the whole vector or its lane. Instead of
1019 // making an arbitrary choice and emitting not so helpful message, let's
1020 // avoid the extra noise and stop here.
1023 if (DstTy
.isVector() && DstTy
.getNumElements() != SrcTy
.getNumElements())
1024 report("Generic vector extend/truncate must preserve number of lanes",
1026 unsigned DstSize
= DstElTy
.getSizeInBits();
1027 unsigned SrcSize
= SrcElTy
.getSizeInBits();
1028 switch (MI
->getOpcode()) {
1030 if (DstSize
<= SrcSize
)
1031 report("Generic extend has destination type no larger than source", MI
);
1033 case TargetOpcode::G_TRUNC
:
1034 case TargetOpcode::G_FPTRUNC
:
1035 if (DstSize
>= SrcSize
)
1036 report("Generic truncate has destination type no smaller than source",
1042 case TargetOpcode::COPY
: {
1045 const MachineOperand
&DstOp
= MI
->getOperand(0);
1046 const MachineOperand
&SrcOp
= MI
->getOperand(1);
1047 LLT DstTy
= MRI
->getType(DstOp
.getReg());
1048 LLT SrcTy
= MRI
->getType(SrcOp
.getReg());
1049 if (SrcTy
.isValid() && DstTy
.isValid()) {
1050 // If both types are valid, check that the types are the same.
1051 if (SrcTy
!= DstTy
) {
1052 report("Copy Instruction is illegal with mismatching types", MI
);
1053 errs() << "Def = " << DstTy
<< ", Src = " << SrcTy
<< "\n";
1056 if (SrcTy
.isValid() || DstTy
.isValid()) {
1057 // If one of them have valid types, let's just check they have the same
1059 unsigned SrcSize
= TRI
->getRegSizeInBits(SrcOp
.getReg(), *MRI
);
1060 unsigned DstSize
= TRI
->getRegSizeInBits(DstOp
.getReg(), *MRI
);
1061 assert(SrcSize
&& "Expecting size here");
1062 assert(DstSize
&& "Expecting size here");
1063 if (SrcSize
!= DstSize
)
1064 if (!DstOp
.getSubReg() && !SrcOp
.getSubReg()) {
1065 report("Copy Instruction is illegal with mismatching sizes", MI
);
1066 errs() << "Def Size = " << DstSize
<< ", Src Size = " << SrcSize
1072 case TargetOpcode::STATEPOINT
:
1073 if (!MI
->getOperand(StatepointOpers::IDPos
).isImm() ||
1074 !MI
->getOperand(StatepointOpers::NBytesPos
).isImm() ||
1075 !MI
->getOperand(StatepointOpers::NCallArgsPos
).isImm())
1076 report("meta operands to STATEPOINT not constant!", MI
);
1079 auto VerifyStackMapConstant
= [&](unsigned Offset
) {
1080 if (!MI
->getOperand(Offset
).isImm() ||
1081 MI
->getOperand(Offset
).getImm() != StackMaps::ConstantOp
||
1082 !MI
->getOperand(Offset
+ 1).isImm())
1083 report("stack map constant to STATEPOINT not well formed!", MI
);
1085 const unsigned VarStart
= StatepointOpers(MI
).getVarIdx();
1086 VerifyStackMapConstant(VarStart
+ StatepointOpers::CCOffset
);
1087 VerifyStackMapConstant(VarStart
+ StatepointOpers::FlagsOffset
);
1088 VerifyStackMapConstant(VarStart
+ StatepointOpers::NumDeoptOperandsOffset
);
1090 // TODO: verify we have properly encoded deopt arguments
1095 MachineVerifier::visitMachineOperand(const MachineOperand
*MO
, unsigned MONum
) {
1096 const MachineInstr
*MI
= MO
->getParent();
1097 const MCInstrDesc
&MCID
= MI
->getDesc();
1098 unsigned NumDefs
= MCID
.getNumDefs();
1099 if (MCID
.getOpcode() == TargetOpcode::PATCHPOINT
)
1100 NumDefs
= (MONum
== 0 && MO
->isReg()) ? NumDefs
: 0;
1102 // The first MCID.NumDefs operands must be explicit register defines
1103 if (MONum
< NumDefs
) {
1104 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1106 report("Explicit definition must be a register", MO
, MONum
);
1107 else if (!MO
->isDef() && !MCOI
.isOptionalDef())
1108 report("Explicit definition marked as use", MO
, MONum
);
1109 else if (MO
->isImplicit())
1110 report("Explicit definition marked as implicit", MO
, MONum
);
1111 } else if (MONum
< MCID
.getNumOperands()) {
1112 const MCOperandInfo
&MCOI
= MCID
.OpInfo
[MONum
];
1113 // Don't check if it's the last operand in a variadic instruction. See,
1114 // e.g., LDM_RET in the arm back end.
1116 !(MI
->isVariadic() && MONum
== MCID
.getNumOperands()-1)) {
1117 if (MO
->isDef() && !MCOI
.isOptionalDef())
1118 report("Explicit operand marked as def", MO
, MONum
);
1119 if (MO
->isImplicit())
1120 report("Explicit operand marked as implicit", MO
, MONum
);
1123 int TiedTo
= MCID
.getOperandConstraint(MONum
, MCOI::TIED_TO
);
1126 report("Tied use must be a register", MO
, MONum
);
1127 else if (!MO
->isTied())
1128 report("Operand should be tied", MO
, MONum
);
1129 else if (unsigned(TiedTo
) != MI
->findTiedOperandIdx(MONum
))
1130 report("Tied def doesn't match MCInstrDesc", MO
, MONum
);
1131 else if (TargetRegisterInfo::isPhysicalRegister(MO
->getReg())) {
1132 const MachineOperand
&MOTied
= MI
->getOperand(TiedTo
);
1133 if (!MOTied
.isReg())
1134 report("Tied counterpart must be a register", &MOTied
, TiedTo
);
1135 else if (TargetRegisterInfo::isPhysicalRegister(MOTied
.getReg()) &&
1136 MO
->getReg() != MOTied
.getReg())
1137 report("Tied physical registers must match.", &MOTied
, TiedTo
);
1139 } else if (MO
->isReg() && MO
->isTied())
1140 report("Explicit operand should not be tied", MO
, MONum
);
1142 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
1143 if (MO
->isReg() && !MO
->isImplicit() && !MI
->isVariadic() && MO
->getReg())
1144 report("Extra explicit operand on non-variadic instruction", MO
, MONum
);
1147 switch (MO
->getType()) {
1148 case MachineOperand::MO_Register
: {
1149 const unsigned Reg
= MO
->getReg();
1152 if (MRI
->tracksLiveness() && !MI
->isDebugValue())
1153 checkLiveness(MO
, MONum
);
1155 // Verify the consistency of tied operands.
1157 unsigned OtherIdx
= MI
->findTiedOperandIdx(MONum
);
1158 const MachineOperand
&OtherMO
= MI
->getOperand(OtherIdx
);
1159 if (!OtherMO
.isReg())
1160 report("Must be tied to a register", MO
, MONum
);
1161 if (!OtherMO
.isTied())
1162 report("Missing tie flags on tied operand", MO
, MONum
);
1163 if (MI
->findTiedOperandIdx(OtherIdx
) != MONum
)
1164 report("Inconsistent tie links", MO
, MONum
);
1165 if (MONum
< MCID
.getNumDefs()) {
1166 if (OtherIdx
< MCID
.getNumOperands()) {
1167 if (-1 == MCID
.getOperandConstraint(OtherIdx
, MCOI::TIED_TO
))
1168 report("Explicit def tied to explicit use without tie constraint",
1171 if (!OtherMO
.isImplicit())
1172 report("Explicit def should be tied to implicit use", MO
, MONum
);
1177 // Verify two-address constraints after leaving SSA form.
1179 if (!MRI
->isSSA() && MO
->isUse() &&
1180 MI
->isRegTiedToDefOperand(MONum
, &DefIdx
) &&
1181 Reg
!= MI
->getOperand(DefIdx
).getReg())
1182 report("Two-address instruction operands must be identical", MO
, MONum
);
1184 // Check register classes.
1185 unsigned SubIdx
= MO
->getSubReg();
1187 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1189 report("Illegal subregister index for physical register", MO
, MONum
);
1192 if (MONum
< MCID
.getNumOperands()) {
1193 if (const TargetRegisterClass
*DRC
=
1194 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1195 if (!DRC
->contains(Reg
)) {
1196 report("Illegal physical register for instruction", MO
, MONum
);
1197 errs() << printReg(Reg
, TRI
) << " is not a "
1198 << TRI
->getRegClassName(DRC
) << " register.\n";
1202 if (MO
->isRenamable()) {
1203 if (MRI
->isReserved(Reg
)) {
1204 report("isRenamable set on reserved register", MO
, MONum
);
1208 if (MI
->isDebugValue() && MO
->isUse() && !MO
->isDebug()) {
1209 report("Use-reg is not IsDebug in a DBG_VALUE", MO
, MONum
);
1213 // Virtual register.
1214 const TargetRegisterClass
*RC
= MRI
->getRegClassOrNull(Reg
);
1216 // This is a generic virtual register.
1218 // If we're post-Select, we can't have gvregs anymore.
1219 if (isFunctionSelected
) {
1220 report("Generic virtual register invalid in a Selected function",
1225 // The gvreg must have a type and it must not have a SubIdx.
1226 LLT Ty
= MRI
->getType(Reg
);
1227 if (!Ty
.isValid()) {
1228 report("Generic virtual register must have a valid type", MO
,
1233 const RegisterBank
*RegBank
= MRI
->getRegBankOrNull(Reg
);
1235 // If we're post-RegBankSelect, the gvreg must have a bank.
1236 if (!RegBank
&& isFunctionRegBankSelected
) {
1237 report("Generic virtual register must have a bank in a "
1238 "RegBankSelected function",
1243 // Make sure the register fits into its register bank if any.
1244 if (RegBank
&& Ty
.isValid() &&
1245 RegBank
->getSize() < Ty
.getSizeInBits()) {
1246 report("Register bank is too small for virtual register", MO
,
1248 errs() << "Register bank " << RegBank
->getName() << " too small("
1249 << RegBank
->getSize() << ") to fit " << Ty
.getSizeInBits()
1254 report("Generic virtual register does not subregister index", MO
,
1259 // If this is a target specific instruction and this operand
1260 // has register class constraint, the virtual register must
1262 if (!isPreISelGenericOpcode(MCID
.getOpcode()) &&
1263 MONum
< MCID
.getNumOperands() &&
1264 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1265 report("Virtual register does not match instruction constraint", MO
,
1267 errs() << "Expect register class "
1268 << TRI
->getRegClassName(
1269 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
))
1270 << " but got nothing\n";
1277 const TargetRegisterClass
*SRC
=
1278 TRI
->getSubClassWithSubReg(RC
, SubIdx
);
1280 report("Invalid subregister index for virtual register", MO
, MONum
);
1281 errs() << "Register class " << TRI
->getRegClassName(RC
)
1282 << " does not support subreg index " << SubIdx
<< "\n";
1286 report("Invalid register class for subregister index", MO
, MONum
);
1287 errs() << "Register class " << TRI
->getRegClassName(RC
)
1288 << " does not fully support subreg index " << SubIdx
<< "\n";
1292 if (MONum
< MCID
.getNumOperands()) {
1293 if (const TargetRegisterClass
*DRC
=
1294 TII
->getRegClass(MCID
, MONum
, TRI
, *MF
)) {
1296 const TargetRegisterClass
*SuperRC
=
1297 TRI
->getLargestLegalSuperClass(RC
, *MF
);
1299 report("No largest legal super class exists.", MO
, MONum
);
1302 DRC
= TRI
->getMatchingSuperRegClass(SuperRC
, DRC
, SubIdx
);
1304 report("No matching super-reg register class.", MO
, MONum
);
1308 if (!RC
->hasSuperClassEq(DRC
)) {
1309 report("Illegal virtual register for instruction", MO
, MONum
);
1310 errs() << "Expected a " << TRI
->getRegClassName(DRC
)
1311 << " register, but got a " << TRI
->getRegClassName(RC
)
1320 case MachineOperand::MO_RegisterMask
:
1321 regMasks
.push_back(MO
->getRegMask());
1324 case MachineOperand::MO_MachineBasicBlock
:
1325 if (MI
->isPHI() && !MO
->getMBB()->isSuccessor(MI
->getParent()))
1326 report("PHI operand is not in the CFG", MO
, MONum
);
1329 case MachineOperand::MO_FrameIndex
:
1330 if (LiveStks
&& LiveStks
->hasInterval(MO
->getIndex()) &&
1331 LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1332 int FI
= MO
->getIndex();
1333 LiveInterval
&LI
= LiveStks
->getInterval(FI
);
1334 SlotIndex Idx
= LiveInts
->getInstructionIndex(*MI
);
1336 bool stores
= MI
->mayStore();
1337 bool loads
= MI
->mayLoad();
1338 // For a memory-to-memory move, we need to check if the frame
1339 // index is used for storing or loading, by inspecting the
1341 if (stores
&& loads
) {
1342 for (auto *MMO
: MI
->memoperands()) {
1343 const PseudoSourceValue
*PSV
= MMO
->getPseudoValue();
1344 if (PSV
== nullptr) continue;
1345 const FixedStackPseudoSourceValue
*Value
=
1346 dyn_cast
<FixedStackPseudoSourceValue
>(PSV
);
1347 if (Value
== nullptr) continue;
1348 if (Value
->getFrameIndex() != FI
) continue;
1356 if (loads
== stores
)
1357 report("Missing fixed stack memoperand.", MI
);
1359 if (loads
&& !LI
.liveAt(Idx
.getRegSlot(true))) {
1360 report("Instruction loads from dead spill slot", MO
, MONum
);
1361 errs() << "Live stack: " << LI
<< '\n';
1363 if (stores
&& !LI
.liveAt(Idx
.getRegSlot())) {
1364 report("Instruction stores to dead spill slot", MO
, MONum
);
1365 errs() << "Live stack: " << LI
<< '\n';
1375 void MachineVerifier::checkLivenessAtUse(const MachineOperand
*MO
,
1376 unsigned MONum
, SlotIndex UseIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
1377 LaneBitmask LaneMask
) {
1378 LiveQueryResult LRQ
= LR
.Query(UseIdx
);
1379 // Check if we have a segment at the use, note however that we only need one
1380 // live subregister range, the others may be dead.
1381 if (!LRQ
.valueIn() && LaneMask
.none()) {
1382 report("No live segment at use", MO
, MONum
);
1383 report_context_liverange(LR
);
1384 report_context_vreg_regunit(VRegOrUnit
);
1385 report_context(UseIdx
);
1387 if (MO
->isKill() && !LRQ
.isKill()) {
1388 report("Live range continues after kill flag", MO
, MONum
);
1389 report_context_liverange(LR
);
1390 report_context_vreg_regunit(VRegOrUnit
);
1392 report_context_lanemask(LaneMask
);
1393 report_context(UseIdx
);
1397 void MachineVerifier::checkLivenessAtDef(const MachineOperand
*MO
,
1398 unsigned MONum
, SlotIndex DefIdx
, const LiveRange
&LR
, unsigned VRegOrUnit
,
1399 LaneBitmask LaneMask
) {
1400 if (const VNInfo
*VNI
= LR
.getVNInfoAt(DefIdx
)) {
1401 assert(VNI
&& "NULL valno is not allowed");
1402 if (VNI
->def
!= DefIdx
) {
1403 report("Inconsistent valno->def", MO
, MONum
);
1404 report_context_liverange(LR
);
1405 report_context_vreg_regunit(VRegOrUnit
);
1407 report_context_lanemask(LaneMask
);
1408 report_context(*VNI
);
1409 report_context(DefIdx
);
1412 report("No live segment at def", MO
, MONum
);
1413 report_context_liverange(LR
);
1414 report_context_vreg_regunit(VRegOrUnit
);
1416 report_context_lanemask(LaneMask
);
1417 report_context(DefIdx
);
1419 // Check that, if the dead def flag is present, LiveInts agree.
1421 LiveQueryResult LRQ
= LR
.Query(DefIdx
);
1422 if (!LRQ
.isDeadDef()) {
1423 // In case of physregs we can have a non-dead definition on another
1425 bool otherDef
= false;
1426 if (!TargetRegisterInfo::isVirtualRegister(VRegOrUnit
)) {
1427 const MachineInstr
&MI
= *MO
->getParent();
1428 for (const MachineOperand
&MO
: MI
.operands()) {
1429 if (!MO
.isReg() || !MO
.isDef() || MO
.isDead())
1431 unsigned Reg
= MO
.getReg();
1432 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
) {
1433 if (*Units
== VRegOrUnit
) {
1442 report("Live range continues after dead def flag", MO
, MONum
);
1443 report_context_liverange(LR
);
1444 report_context_vreg_regunit(VRegOrUnit
);
1446 report_context_lanemask(LaneMask
);
1452 void MachineVerifier::checkLiveness(const MachineOperand
*MO
, unsigned MONum
) {
1453 const MachineInstr
*MI
= MO
->getParent();
1454 const unsigned Reg
= MO
->getReg();
1456 // Both use and def operands can read a register.
1457 if (MO
->readsReg()) {
1459 addRegWithSubRegs(regsKilled
, Reg
);
1461 // Check that LiveVars knows this kill.
1462 if (LiveVars
&& TargetRegisterInfo::isVirtualRegister(Reg
) &&
1464 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
1465 if (!is_contained(VI
.Kills
, MI
))
1466 report("Kill missing from LiveVariables", MO
, MONum
);
1469 // Check LiveInts liveness and kill.
1470 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1471 SlotIndex UseIdx
= LiveInts
->getInstructionIndex(*MI
);
1472 // Check the cached regunit intervals.
1473 if (TargetRegisterInfo::isPhysicalRegister(Reg
) && !isReserved(Reg
)) {
1474 for (MCRegUnitIterator
Units(Reg
, TRI
); Units
.isValid(); ++Units
) {
1475 if (MRI
->isReservedRegUnit(*Units
))
1477 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(*Units
))
1478 checkLivenessAtUse(MO
, MONum
, UseIdx
, *LR
, *Units
);
1482 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1483 if (LiveInts
->hasInterval(Reg
)) {
1484 // This is a virtual register interval.
1485 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1486 checkLivenessAtUse(MO
, MONum
, UseIdx
, LI
, Reg
);
1488 if (LI
.hasSubRanges() && !MO
->isDef()) {
1489 unsigned SubRegIdx
= MO
->getSubReg();
1490 LaneBitmask MOMask
= SubRegIdx
!= 0
1491 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
1492 : MRI
->getMaxLaneMaskForVReg(Reg
);
1493 LaneBitmask LiveInMask
;
1494 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
1495 if ((MOMask
& SR
.LaneMask
).none())
1497 checkLivenessAtUse(MO
, MONum
, UseIdx
, SR
, Reg
, SR
.LaneMask
);
1498 LiveQueryResult LRQ
= SR
.Query(UseIdx
);
1500 LiveInMask
|= SR
.LaneMask
;
1502 // At least parts of the register has to be live at the use.
1503 if ((LiveInMask
& MOMask
).none()) {
1504 report("No live subrange at use", MO
, MONum
);
1506 report_context(UseIdx
);
1510 report("Virtual register has no live interval", MO
, MONum
);
1515 // Use of a dead register.
1516 if (!regsLive
.count(Reg
)) {
1517 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
1518 // Reserved registers may be used even when 'dead'.
1519 bool Bad
= !isReserved(Reg
);
1520 // We are fine if just any subregister has a defined value.
1522 for (MCSubRegIterator
SubRegs(Reg
, TRI
); SubRegs
.isValid();
1524 if (regsLive
.count(*SubRegs
)) {
1530 // If there is an additional implicit-use of a super register we stop
1531 // here. By definition we are fine if the super register is not
1532 // (completely) dead, if the complete super register is dead we will
1533 // get a report for its operand.
1535 for (const MachineOperand
&MOP
: MI
->uses()) {
1536 if (!MOP
.isReg() || !MOP
.isImplicit())
1539 if (!TargetRegisterInfo::isPhysicalRegister(MOP
.getReg()))
1542 for (MCSubRegIterator
SubRegs(MOP
.getReg(), TRI
); SubRegs
.isValid();
1544 if (*SubRegs
== Reg
) {
1552 report("Using an undefined physical register", MO
, MONum
);
1553 } else if (MRI
->def_empty(Reg
)) {
1554 report("Reading virtual register without a def", MO
, MONum
);
1556 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
1557 // We don't know which virtual registers are live in, so only complain
1558 // if vreg was killed in this MBB. Otherwise keep track of vregs that
1559 // must be live in. PHI instructions are handled separately.
1560 if (MInfo
.regsKilled
.count(Reg
))
1561 report("Using a killed virtual register", MO
, MONum
);
1562 else if (!MI
->isPHI())
1563 MInfo
.vregsLiveIn
.insert(std::make_pair(Reg
, MI
));
1569 // Register defined.
1570 // TODO: verify that earlyclobber ops are not used.
1572 addRegWithSubRegs(regsDead
, Reg
);
1574 addRegWithSubRegs(regsDefined
, Reg
);
1577 if (MRI
->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg
) &&
1578 std::next(MRI
->def_begin(Reg
)) != MRI
->def_end())
1579 report("Multiple virtual register defs in SSA form", MO
, MONum
);
1581 // Check LiveInts for a live segment, but only for virtual registers.
1582 if (LiveInts
&& !LiveInts
->isNotInMIMap(*MI
)) {
1583 SlotIndex DefIdx
= LiveInts
->getInstructionIndex(*MI
);
1584 DefIdx
= DefIdx
.getRegSlot(MO
->isEarlyClobber());
1586 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1587 if (LiveInts
->hasInterval(Reg
)) {
1588 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1589 checkLivenessAtDef(MO
, MONum
, DefIdx
, LI
, Reg
);
1591 if (LI
.hasSubRanges()) {
1592 unsigned SubRegIdx
= MO
->getSubReg();
1593 LaneBitmask MOMask
= SubRegIdx
!= 0
1594 ? TRI
->getSubRegIndexLaneMask(SubRegIdx
)
1595 : MRI
->getMaxLaneMaskForVReg(Reg
);
1596 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
1597 if ((SR
.LaneMask
& MOMask
).none())
1599 checkLivenessAtDef(MO
, MONum
, DefIdx
, SR
, Reg
, SR
.LaneMask
);
1603 report("Virtual register has no Live interval", MO
, MONum
);
1610 void MachineVerifier::visitMachineInstrAfter(const MachineInstr
*MI
) {}
1612 // This function gets called after visiting all instructions in a bundle. The
1613 // argument points to the bundle header.
1614 // Normal stand-alone instructions are also considered 'bundles', and this
1615 // function is called for all of them.
1616 void MachineVerifier::visitMachineBundleAfter(const MachineInstr
*MI
) {
1617 BBInfo
&MInfo
= MBBInfoMap
[MI
->getParent()];
1618 set_union(MInfo
.regsKilled
, regsKilled
);
1619 set_subtract(regsLive
, regsKilled
); regsKilled
.clear();
1620 // Kill any masked registers.
1621 while (!regMasks
.empty()) {
1622 const uint32_t *Mask
= regMasks
.pop_back_val();
1623 for (RegSet::iterator I
= regsLive
.begin(), E
= regsLive
.end(); I
!= E
; ++I
)
1624 if (TargetRegisterInfo::isPhysicalRegister(*I
) &&
1625 MachineOperand::clobbersPhysReg(Mask
, *I
))
1626 regsDead
.push_back(*I
);
1628 set_subtract(regsLive
, regsDead
); regsDead
.clear();
1629 set_union(regsLive
, regsDefined
); regsDefined
.clear();
1633 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock
*MBB
) {
1634 MBBInfoMap
[MBB
].regsLiveOut
= regsLive
;
1638 SlotIndex stop
= Indexes
->getMBBEndIdx(MBB
);
1639 if (!(stop
> lastIndex
)) {
1640 report("Block ends before last instruction index", MBB
);
1641 errs() << "Block ends at " << stop
1642 << " last instruction was at " << lastIndex
<< '\n';
1648 // Calculate the largest possible vregsPassed sets. These are the registers that
1649 // can pass through an MBB live, but may not be live every time. It is assumed
1650 // that all vregsPassed sets are empty before the call.
1651 void MachineVerifier::calcRegsPassed() {
1652 // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1653 // have any vregsPassed.
1654 SmallPtrSet
<const MachineBasicBlock
*, 8> todo
;
1655 for (const auto &MBB
: *MF
) {
1656 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1657 if (!MInfo
.reachable
)
1659 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
.succ_begin(),
1660 SuE
= MBB
.succ_end(); SuI
!= SuE
; ++SuI
) {
1661 BBInfo
&SInfo
= MBBInfoMap
[*SuI
];
1662 if (SInfo
.addPassed(MInfo
.regsLiveOut
))
1667 // Iteratively push vregsPassed to successors. This will converge to the same
1668 // final state regardless of DenseSet iteration order.
1669 while (!todo
.empty()) {
1670 const MachineBasicBlock
*MBB
= *todo
.begin();
1672 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
1673 for (MachineBasicBlock::const_succ_iterator SuI
= MBB
->succ_begin(),
1674 SuE
= MBB
->succ_end(); SuI
!= SuE
; ++SuI
) {
1677 BBInfo
&SInfo
= MBBInfoMap
[*SuI
];
1678 if (SInfo
.addPassed(MInfo
.vregsPassed
))
1684 // Calculate the set of virtual registers that must be passed through each basic
1685 // block in order to satisfy the requirements of successor blocks. This is very
1686 // similar to calcRegsPassed, only backwards.
1687 void MachineVerifier::calcRegsRequired() {
1688 // First push live-in regs to predecessors' vregsRequired.
1689 SmallPtrSet
<const MachineBasicBlock
*, 8> todo
;
1690 for (const auto &MBB
: *MF
) {
1691 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1692 for (MachineBasicBlock::const_pred_iterator PrI
= MBB
.pred_begin(),
1693 PrE
= MBB
.pred_end(); PrI
!= PrE
; ++PrI
) {
1694 BBInfo
&PInfo
= MBBInfoMap
[*PrI
];
1695 if (PInfo
.addRequired(MInfo
.vregsLiveIn
))
1700 // Iteratively push vregsRequired to predecessors. This will converge to the
1701 // same final state regardless of DenseSet iteration order.
1702 while (!todo
.empty()) {
1703 const MachineBasicBlock
*MBB
= *todo
.begin();
1705 BBInfo
&MInfo
= MBBInfoMap
[MBB
];
1706 for (MachineBasicBlock::const_pred_iterator PrI
= MBB
->pred_begin(),
1707 PrE
= MBB
->pred_end(); PrI
!= PrE
; ++PrI
) {
1710 BBInfo
&SInfo
= MBBInfoMap
[*PrI
];
1711 if (SInfo
.addRequired(MInfo
.vregsRequired
))
1717 // Check PHI instructions at the beginning of MBB. It is assumed that
1718 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1719 void MachineVerifier::checkPHIOps(const MachineBasicBlock
&MBB
) {
1720 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1722 SmallPtrSet
<const MachineBasicBlock
*, 8> seen
;
1723 for (const MachineInstr
&Phi
: MBB
) {
1728 const MachineOperand
&MODef
= Phi
.getOperand(0);
1729 if (!MODef
.isReg() || !MODef
.isDef()) {
1730 report("Expected first PHI operand to be a register def", &MODef
, 0);
1733 if (MODef
.isTied() || MODef
.isImplicit() || MODef
.isInternalRead() ||
1734 MODef
.isEarlyClobber() || MODef
.isDebug())
1735 report("Unexpected flag on PHI operand", &MODef
, 0);
1736 unsigned DefReg
= MODef
.getReg();
1737 if (!TargetRegisterInfo::isVirtualRegister(DefReg
))
1738 report("Expected first PHI operand to be a virtual register", &MODef
, 0);
1740 for (unsigned I
= 1, E
= Phi
.getNumOperands(); I
!= E
; I
+= 2) {
1741 const MachineOperand
&MO0
= Phi
.getOperand(I
);
1743 report("Expected PHI operand to be a register", &MO0
, I
);
1746 if (MO0
.isImplicit() || MO0
.isInternalRead() || MO0
.isEarlyClobber() ||
1747 MO0
.isDebug() || MO0
.isTied())
1748 report("Unexpected flag on PHI operand", &MO0
, I
);
1750 const MachineOperand
&MO1
= Phi
.getOperand(I
+ 1);
1752 report("Expected PHI operand to be a basic block", &MO1
, I
+ 1);
1756 const MachineBasicBlock
&Pre
= *MO1
.getMBB();
1757 if (!Pre
.isSuccessor(&MBB
)) {
1758 report("PHI input is not a predecessor block", &MO1
, I
+ 1);
1762 if (MInfo
.reachable
) {
1764 BBInfo
&PrInfo
= MBBInfoMap
[&Pre
];
1765 if (!MO0
.isUndef() && PrInfo
.reachable
&&
1766 !PrInfo
.isLiveOut(MO0
.getReg()))
1767 report("PHI operand is not live-out from predecessor", &MO0
, I
);
1771 // Did we see all predecessors?
1772 if (MInfo
.reachable
) {
1773 for (MachineBasicBlock
*Pred
: MBB
.predecessors()) {
1774 if (!seen
.count(Pred
)) {
1775 report("Missing PHI operand", &Phi
);
1776 errs() << printMBBReference(*Pred
)
1777 << " is a predecessor according to the CFG.\n";
1784 void MachineVerifier::visitMachineFunctionAfter() {
1787 for (const MachineBasicBlock
&MBB
: *MF
)
1790 // Now check liveness info if available
1793 // Check for killed virtual registers that should be live out.
1794 for (const auto &MBB
: *MF
) {
1795 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1796 for (RegSet::iterator
1797 I
= MInfo
.vregsRequired
.begin(), E
= MInfo
.vregsRequired
.end(); I
!= E
;
1799 if (MInfo
.regsKilled
.count(*I
)) {
1800 report("Virtual register killed in block, but needed live out.", &MBB
);
1801 errs() << "Virtual register " << printReg(*I
)
1802 << " is used after the block.\n";
1807 BBInfo
&MInfo
= MBBInfoMap
[&MF
->front()];
1808 for (RegSet::iterator
1809 I
= MInfo
.vregsRequired
.begin(), E
= MInfo
.vregsRequired
.end(); I
!= E
;
1811 report("Virtual register defs don't dominate all uses.", MF
);
1812 report_context_vreg(*I
);
1817 verifyLiveVariables();
1819 verifyLiveIntervals();
1822 void MachineVerifier::verifyLiveVariables() {
1823 assert(LiveVars
&& "Don't call verifyLiveVariables without LiveVars");
1824 for (unsigned i
= 0, e
= MRI
->getNumVirtRegs(); i
!= e
; ++i
) {
1825 unsigned Reg
= TargetRegisterInfo::index2VirtReg(i
);
1826 LiveVariables::VarInfo
&VI
= LiveVars
->getVarInfo(Reg
);
1827 for (const auto &MBB
: *MF
) {
1828 BBInfo
&MInfo
= MBBInfoMap
[&MBB
];
1830 // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1831 if (MInfo
.vregsRequired
.count(Reg
)) {
1832 if (!VI
.AliveBlocks
.test(MBB
.getNumber())) {
1833 report("LiveVariables: Block missing from AliveBlocks", &MBB
);
1834 errs() << "Virtual register " << printReg(Reg
)
1835 << " must be live through the block.\n";
1838 if (VI
.AliveBlocks
.test(MBB
.getNumber())) {
1839 report("LiveVariables: Block should not be in AliveBlocks", &MBB
);
1840 errs() << "Virtual register " << printReg(Reg
)
1841 << " is not needed live through the block.\n";
1848 void MachineVerifier::verifyLiveIntervals() {
1849 assert(LiveInts
&& "Don't call verifyLiveIntervals without LiveInts");
1850 for (unsigned i
= 0, e
= MRI
->getNumVirtRegs(); i
!= e
; ++i
) {
1851 unsigned Reg
= TargetRegisterInfo::index2VirtReg(i
);
1853 // Spilling and splitting may leave unused registers around. Skip them.
1854 if (MRI
->reg_nodbg_empty(Reg
))
1857 if (!LiveInts
->hasInterval(Reg
)) {
1858 report("Missing live interval for virtual register", MF
);
1859 errs() << printReg(Reg
, TRI
) << " still has defs or uses\n";
1863 const LiveInterval
&LI
= LiveInts
->getInterval(Reg
);
1864 assert(Reg
== LI
.reg
&& "Invalid reg to interval mapping");
1865 verifyLiveInterval(LI
);
1868 // Verify all the cached regunit intervals.
1869 for (unsigned i
= 0, e
= TRI
->getNumRegUnits(); i
!= e
; ++i
)
1870 if (const LiveRange
*LR
= LiveInts
->getCachedRegUnit(i
))
1871 verifyLiveRange(*LR
, i
);
1874 void MachineVerifier::verifyLiveRangeValue(const LiveRange
&LR
,
1875 const VNInfo
*VNI
, unsigned Reg
,
1876 LaneBitmask LaneMask
) {
1877 if (VNI
->isUnused())
1880 const VNInfo
*DefVNI
= LR
.getVNInfoAt(VNI
->def
);
1883 report("Value not live at VNInfo def and not marked unused", MF
);
1884 report_context(LR
, Reg
, LaneMask
);
1885 report_context(*VNI
);
1889 if (DefVNI
!= VNI
) {
1890 report("Live segment at def has different VNInfo", MF
);
1891 report_context(LR
, Reg
, LaneMask
);
1892 report_context(*VNI
);
1896 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(VNI
->def
);
1898 report("Invalid VNInfo definition index", MF
);
1899 report_context(LR
, Reg
, LaneMask
);
1900 report_context(*VNI
);
1904 if (VNI
->isPHIDef()) {
1905 if (VNI
->def
!= LiveInts
->getMBBStartIdx(MBB
)) {
1906 report("PHIDef VNInfo is not defined at MBB start", MBB
);
1907 report_context(LR
, Reg
, LaneMask
);
1908 report_context(*VNI
);
1914 const MachineInstr
*MI
= LiveInts
->getInstructionFromIndex(VNI
->def
);
1916 report("No instruction at VNInfo def index", MBB
);
1917 report_context(LR
, Reg
, LaneMask
);
1918 report_context(*VNI
);
1923 bool hasDef
= false;
1924 bool isEarlyClobber
= false;
1925 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
1926 if (!MOI
->isReg() || !MOI
->isDef())
1928 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
1929 if (MOI
->getReg() != Reg
)
1932 if (!TargetRegisterInfo::isPhysicalRegister(MOI
->getReg()) ||
1933 !TRI
->hasRegUnit(MOI
->getReg(), Reg
))
1936 if (LaneMask
.any() &&
1937 (TRI
->getSubRegIndexLaneMask(MOI
->getSubReg()) & LaneMask
).none())
1940 if (MOI
->isEarlyClobber())
1941 isEarlyClobber
= true;
1945 report("Defining instruction does not modify register", MI
);
1946 report_context(LR
, Reg
, LaneMask
);
1947 report_context(*VNI
);
1950 // Early clobber defs begin at USE slots, but other defs must begin at
1952 if (isEarlyClobber
) {
1953 if (!VNI
->def
.isEarlyClobber()) {
1954 report("Early clobber def must be at an early-clobber slot", MBB
);
1955 report_context(LR
, Reg
, LaneMask
);
1956 report_context(*VNI
);
1958 } else if (!VNI
->def
.isRegister()) {
1959 report("Non-PHI, non-early clobber def must be at a register slot", MBB
);
1960 report_context(LR
, Reg
, LaneMask
);
1961 report_context(*VNI
);
1966 void MachineVerifier::verifyLiveRangeSegment(const LiveRange
&LR
,
1967 const LiveRange::const_iterator I
,
1968 unsigned Reg
, LaneBitmask LaneMask
)
1970 const LiveRange::Segment
&S
= *I
;
1971 const VNInfo
*VNI
= S
.valno
;
1972 assert(VNI
&& "Live segment has no valno");
1974 if (VNI
->id
>= LR
.getNumValNums() || VNI
!= LR
.getValNumInfo(VNI
->id
)) {
1975 report("Foreign valno in live segment", MF
);
1976 report_context(LR
, Reg
, LaneMask
);
1978 report_context(*VNI
);
1981 if (VNI
->isUnused()) {
1982 report("Live segment valno is marked unused", MF
);
1983 report_context(LR
, Reg
, LaneMask
);
1987 const MachineBasicBlock
*MBB
= LiveInts
->getMBBFromIndex(S
.start
);
1989 report("Bad start of live segment, no basic block", MF
);
1990 report_context(LR
, Reg
, LaneMask
);
1994 SlotIndex MBBStartIdx
= LiveInts
->getMBBStartIdx(MBB
);
1995 if (S
.start
!= MBBStartIdx
&& S
.start
!= VNI
->def
) {
1996 report("Live segment must begin at MBB entry or valno def", MBB
);
1997 report_context(LR
, Reg
, LaneMask
);
2001 const MachineBasicBlock
*EndMBB
=
2002 LiveInts
->getMBBFromIndex(S
.end
.getPrevSlot());
2004 report("Bad end of live segment, no basic block", MF
);
2005 report_context(LR
, Reg
, LaneMask
);
2010 // No more checks for live-out segments.
2011 if (S
.end
== LiveInts
->getMBBEndIdx(EndMBB
))
2014 // RegUnit intervals are allowed dead phis.
2015 if (!TargetRegisterInfo::isVirtualRegister(Reg
) && VNI
->isPHIDef() &&
2016 S
.start
== VNI
->def
&& S
.end
== VNI
->def
.getDeadSlot())
2019 // The live segment is ending inside EndMBB
2020 const MachineInstr
*MI
=
2021 LiveInts
->getInstructionFromIndex(S
.end
.getPrevSlot());
2023 report("Live segment doesn't end at a valid instruction", EndMBB
);
2024 report_context(LR
, Reg
, LaneMask
);
2029 // The block slot must refer to a basic block boundary.
2030 if (S
.end
.isBlock()) {
2031 report("Live segment ends at B slot of an instruction", EndMBB
);
2032 report_context(LR
, Reg
, LaneMask
);
2036 if (S
.end
.isDead()) {
2037 // Segment ends on the dead slot.
2038 // That means there must be a dead def.
2039 if (!SlotIndex::isSameInstr(S
.start
, S
.end
)) {
2040 report("Live segment ending at dead slot spans instructions", EndMBB
);
2041 report_context(LR
, Reg
, LaneMask
);
2046 // A live segment can only end at an early-clobber slot if it is being
2047 // redefined by an early-clobber def.
2048 if (S
.end
.isEarlyClobber()) {
2049 if (I
+1 == LR
.end() || (I
+1)->start
!= S
.end
) {
2050 report("Live segment ending at early clobber slot must be "
2051 "redefined by an EC def in the same instruction", EndMBB
);
2052 report_context(LR
, Reg
, LaneMask
);
2057 // The following checks only apply to virtual registers. Physreg liveness
2058 // is too weird to check.
2059 if (TargetRegisterInfo::isVirtualRegister(Reg
)) {
2060 // A live segment can end with either a redefinition, a kill flag on a
2061 // use, or a dead flag on a def.
2062 bool hasRead
= false;
2063 bool hasSubRegDef
= false;
2064 bool hasDeadDef
= false;
2065 for (ConstMIBundleOperands
MOI(*MI
); MOI
.isValid(); ++MOI
) {
2066 if (!MOI
->isReg() || MOI
->getReg() != Reg
)
2068 unsigned Sub
= MOI
->getSubReg();
2069 LaneBitmask SLM
= Sub
!= 0 ? TRI
->getSubRegIndexLaneMask(Sub
)
2070 : LaneBitmask::getAll();
2073 hasSubRegDef
= true;
2074 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
2075 // mask for subregister defs. Read-undef defs will be handled by
2082 if (LaneMask
.any() && (LaneMask
& SLM
).none())
2084 if (MOI
->readsReg())
2087 if (S
.end
.isDead()) {
2088 // Make sure that the corresponding machine operand for a "dead" live
2089 // range has the dead flag. We cannot perform this check for subregister
2090 // liveranges as partially dead values are allowed.
2091 if (LaneMask
.none() && !hasDeadDef
) {
2092 report("Instruction ending live segment on dead slot has no dead flag",
2094 report_context(LR
, Reg
, LaneMask
);
2099 // When tracking subregister liveness, the main range must start new
2100 // values on partial register writes, even if there is no read.
2101 if (!MRI
->shouldTrackSubRegLiveness(Reg
) || LaneMask
.any() ||
2103 report("Instruction ending live segment doesn't read the register",
2105 report_context(LR
, Reg
, LaneMask
);
2112 // Now check all the basic blocks in this live segment.
2113 MachineFunction::const_iterator MFI
= MBB
->getIterator();
2114 // Is this live segment the beginning of a non-PHIDef VN?
2115 if (S
.start
== VNI
->def
&& !VNI
->isPHIDef()) {
2116 // Not live-in to any blocks.
2123 SmallVector
<SlotIndex
, 4> Undefs
;
2124 if (LaneMask
.any()) {
2125 LiveInterval
&OwnerLI
= LiveInts
->getInterval(Reg
);
2126 OwnerLI
.computeSubRangeUndefs(Undefs
, LaneMask
, *MRI
, *Indexes
);
2130 assert(LiveInts
->isLiveInToMBB(LR
, &*MFI
));
2131 // We don't know how to track physregs into a landing pad.
2132 if (!TargetRegisterInfo::isVirtualRegister(Reg
) &&
2134 if (&*MFI
== EndMBB
)
2140 // Is VNI a PHI-def in the current block?
2141 bool IsPHI
= VNI
->isPHIDef() &&
2142 VNI
->def
== LiveInts
->getMBBStartIdx(&*MFI
);
2144 // Check that VNI is live-out of all predecessors.
2145 for (MachineBasicBlock::const_pred_iterator PI
= MFI
->pred_begin(),
2146 PE
= MFI
->pred_end(); PI
!= PE
; ++PI
) {
2147 SlotIndex PEnd
= LiveInts
->getMBBEndIdx(*PI
);
2148 const VNInfo
*PVNI
= LR
.getVNInfoBefore(PEnd
);
2150 // All predecessors must have a live-out value. However for a phi
2151 // instruction with subregister intervals
2152 // only one of the subregisters (not necessarily the current one) needs to
2154 if (!PVNI
&& (LaneMask
.none() || !IsPHI
)) {
2155 if (LiveRangeCalc::isJointlyDominated(*PI
, Undefs
, *Indexes
))
2157 report("Register not marked live out of predecessor", *PI
);
2158 report_context(LR
, Reg
, LaneMask
);
2159 report_context(*VNI
);
2160 errs() << " live into " << printMBBReference(*MFI
) << '@'
2161 << LiveInts
->getMBBStartIdx(&*MFI
) << ", not live before "
2166 // Only PHI-defs can take different predecessor values.
2167 if (!IsPHI
&& PVNI
!= VNI
) {
2168 report("Different value live out of predecessor", *PI
);
2169 report_context(LR
, Reg
, LaneMask
);
2170 errs() << "Valno #" << PVNI
->id
<< " live out of "
2171 << printMBBReference(*(*PI
)) << '@' << PEnd
<< "\nValno #"
2172 << VNI
->id
<< " live into " << printMBBReference(*MFI
) << '@'
2173 << LiveInts
->getMBBStartIdx(&*MFI
) << '\n';
2176 if (&*MFI
== EndMBB
)
2182 void MachineVerifier::verifyLiveRange(const LiveRange
&LR
, unsigned Reg
,
2183 LaneBitmask LaneMask
) {
2184 for (const VNInfo
*VNI
: LR
.valnos
)
2185 verifyLiveRangeValue(LR
, VNI
, Reg
, LaneMask
);
2187 for (LiveRange::const_iterator I
= LR
.begin(), E
= LR
.end(); I
!= E
; ++I
)
2188 verifyLiveRangeSegment(LR
, I
, Reg
, LaneMask
);
2191 void MachineVerifier::verifyLiveInterval(const LiveInterval
&LI
) {
2192 unsigned Reg
= LI
.reg
;
2193 assert(TargetRegisterInfo::isVirtualRegister(Reg
));
2194 verifyLiveRange(LI
, Reg
);
2197 LaneBitmask MaxMask
= MRI
->getMaxLaneMaskForVReg(Reg
);
2198 for (const LiveInterval::SubRange
&SR
: LI
.subranges()) {
2199 if ((Mask
& SR
.LaneMask
).any()) {
2200 report("Lane masks of sub ranges overlap in live interval", MF
);
2203 if ((SR
.LaneMask
& ~MaxMask
).any()) {
2204 report("Subrange lanemask is invalid", MF
);
2208 report("Subrange must not be empty", MF
);
2209 report_context(SR
, LI
.reg
, SR
.LaneMask
);
2211 Mask
|= SR
.LaneMask
;
2212 verifyLiveRange(SR
, LI
.reg
, SR
.LaneMask
);
2213 if (!LI
.covers(SR
)) {
2214 report("A Subrange is not covered by the main range", MF
);
2219 // Check the LI only has one connected component.
2220 ConnectedVNInfoEqClasses
ConEQ(*LiveInts
);
2221 unsigned NumComp
= ConEQ
.Classify(LI
);
2223 report("Multiple connected components in live interval", MF
);
2225 for (unsigned comp
= 0; comp
!= NumComp
; ++comp
) {
2226 errs() << comp
<< ": valnos";
2227 for (LiveInterval::const_vni_iterator I
= LI
.vni_begin(),
2228 E
= LI
.vni_end(); I
!=E
; ++I
)
2229 if (comp
== ConEQ
.getEqClass(*I
))
2230 errs() << ' ' << (*I
)->id
;
2238 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
2239 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
2241 // We use a bool plus an integer to capture the stack state.
2242 struct StackStateOfBB
{
2243 StackStateOfBB() = default;
2244 StackStateOfBB(int EntryVal
, int ExitVal
, bool EntrySetup
, bool ExitSetup
) :
2245 EntryValue(EntryVal
), ExitValue(ExitVal
), EntryIsSetup(EntrySetup
),
2246 ExitIsSetup(ExitSetup
) {}
2248 // Can be negative, which means we are setting up a frame.
2251 bool EntryIsSetup
= false;
2252 bool ExitIsSetup
= false;
2255 } // end anonymous namespace
2257 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
2258 /// by a FrameDestroy <n>, stack adjustments are identical on all
2259 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
2260 void MachineVerifier::verifyStackFrame() {
2261 unsigned FrameSetupOpcode
= TII
->getCallFrameSetupOpcode();
2262 unsigned FrameDestroyOpcode
= TII
->getCallFrameDestroyOpcode();
2263 if (FrameSetupOpcode
== ~0u && FrameDestroyOpcode
== ~0u)
2266 SmallVector
<StackStateOfBB
, 8> SPState
;
2267 SPState
.resize(MF
->getNumBlockIDs());
2268 df_iterator_default_set
<const MachineBasicBlock
*> Reachable
;
2270 // Visit the MBBs in DFS order.
2271 for (df_ext_iterator
<const MachineFunction
*,
2272 df_iterator_default_set
<const MachineBasicBlock
*>>
2273 DFI
= df_ext_begin(MF
, Reachable
), DFE
= df_ext_end(MF
, Reachable
);
2274 DFI
!= DFE
; ++DFI
) {
2275 const MachineBasicBlock
*MBB
= *DFI
;
2277 StackStateOfBB BBState
;
2278 // Check the exit state of the DFS stack predecessor.
2279 if (DFI
.getPathLength() >= 2) {
2280 const MachineBasicBlock
*StackPred
= DFI
.getPath(DFI
.getPathLength() - 2);
2281 assert(Reachable
.count(StackPred
) &&
2282 "DFS stack predecessor is already visited.\n");
2283 BBState
.EntryValue
= SPState
[StackPred
->getNumber()].ExitValue
;
2284 BBState
.EntryIsSetup
= SPState
[StackPred
->getNumber()].ExitIsSetup
;
2285 BBState
.ExitValue
= BBState
.EntryValue
;
2286 BBState
.ExitIsSetup
= BBState
.EntryIsSetup
;
2289 // Update stack state by checking contents of MBB.
2290 for (const auto &I
: *MBB
) {
2291 if (I
.getOpcode() == FrameSetupOpcode
) {
2292 if (BBState
.ExitIsSetup
)
2293 report("FrameSetup is after another FrameSetup", &I
);
2294 BBState
.ExitValue
-= TII
->getFrameTotalSize(I
);
2295 BBState
.ExitIsSetup
= true;
2298 if (I
.getOpcode() == FrameDestroyOpcode
) {
2299 int Size
= TII
->getFrameTotalSize(I
);
2300 if (!BBState
.ExitIsSetup
)
2301 report("FrameDestroy is not after a FrameSetup", &I
);
2302 int AbsSPAdj
= BBState
.ExitValue
< 0 ? -BBState
.ExitValue
:
2304 if (BBState
.ExitIsSetup
&& AbsSPAdj
!= Size
) {
2305 report("FrameDestroy <n> is after FrameSetup <m>", &I
);
2306 errs() << "FrameDestroy <" << Size
<< "> is after FrameSetup <"
2307 << AbsSPAdj
<< ">.\n";
2309 BBState
.ExitValue
+= Size
;
2310 BBState
.ExitIsSetup
= false;
2313 SPState
[MBB
->getNumber()] = BBState
;
2315 // Make sure the exit state of any predecessor is consistent with the entry
2317 for (MachineBasicBlock::const_pred_iterator I
= MBB
->pred_begin(),
2318 E
= MBB
->pred_end(); I
!= E
; ++I
) {
2319 if (Reachable
.count(*I
) &&
2320 (SPState
[(*I
)->getNumber()].ExitValue
!= BBState
.EntryValue
||
2321 SPState
[(*I
)->getNumber()].ExitIsSetup
!= BBState
.EntryIsSetup
)) {
2322 report("The exit stack state of a predecessor is inconsistent.", MBB
);
2323 errs() << "Predecessor " << printMBBReference(*(*I
))
2324 << " has exit state (" << SPState
[(*I
)->getNumber()].ExitValue
2325 << ", " << SPState
[(*I
)->getNumber()].ExitIsSetup
<< "), while "
2326 << printMBBReference(*MBB
) << " has entry state ("
2327 << BBState
.EntryValue
<< ", " << BBState
.EntryIsSetup
<< ").\n";
2331 // Make sure the entry state of any successor is consistent with the exit
2333 for (MachineBasicBlock::const_succ_iterator I
= MBB
->succ_begin(),
2334 E
= MBB
->succ_end(); I
!= E
; ++I
) {
2335 if (Reachable
.count(*I
) &&
2336 (SPState
[(*I
)->getNumber()].EntryValue
!= BBState
.ExitValue
||
2337 SPState
[(*I
)->getNumber()].EntryIsSetup
!= BBState
.ExitIsSetup
)) {
2338 report("The entry stack state of a successor is inconsistent.", MBB
);
2339 errs() << "Successor " << printMBBReference(*(*I
))
2340 << " has entry state (" << SPState
[(*I
)->getNumber()].EntryValue
2341 << ", " << SPState
[(*I
)->getNumber()].EntryIsSetup
<< "), while "
2342 << printMBBReference(*MBB
) << " has exit state ("
2343 << BBState
.ExitValue
<< ", " << BBState
.ExitIsSetup
<< ").\n";
2347 // Make sure a basic block with return ends with zero stack adjustment.
2348 if (!MBB
->empty() && MBB
->back().isReturn()) {
2349 if (BBState
.ExitIsSetup
)
2350 report("A return block ends with a FrameSetup.", MBB
);
2351 if (BBState
.ExitValue
)
2352 report("A return block ends with a nonzero stack adjustment.", MBB
);