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/CodeGen/MachineVerifier.h"
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SetOperations.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/Twine.h"
35#include "llvm/CodeGen/CodeGenCommonISel.h"
36#include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
37#include "llvm/CodeGen/LiveInterval.h"
38#include "llvm/CodeGen/LiveIntervals.h"
39#include "llvm/CodeGen/LiveRangeCalc.h"
40#include "llvm/CodeGen/LiveStacks.h"
41#include "llvm/CodeGen/MachineBasicBlock.h"
42#include "llvm/CodeGen/MachineConvergenceVerifier.h"
43#include "llvm/CodeGen/MachineDominators.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/RegisterBank.h"
54#include "llvm/CodeGen/RegisterBankInfo.h"
55#include "llvm/CodeGen/SlotIndexes.h"
56#include "llvm/CodeGen/StackMaps.h"
57#include "llvm/CodeGen/TargetInstrInfo.h"
58#include "llvm/CodeGen/TargetLowering.h"
59#include "llvm/CodeGen/TargetOpcodes.h"
60#include "llvm/CodeGen/TargetRegisterInfo.h"
61#include "llvm/CodeGen/TargetSubtargetInfo.h"
62#include "llvm/CodeGenTypes/LowLevelType.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/EHPersonalities.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/InlineAsm.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/InitializePasses.h"
70#include "llvm/MC/LaneBitmask.h"
71#include "llvm/MC/MCDwarf.h"
72#include "llvm/MC/MCInstrDesc.h"
73#include "llvm/MC/MCRegisterInfo.h"
74#include "llvm/MC/MCTargetOptions.h"
75#include "llvm/Pass.h"
76#include "llvm/Support/Casting.h"
77#include "llvm/Support/ErrorHandling.h"
78#include "llvm/Support/ManagedStatic.h"
79#include "llvm/Support/MathExtras.h"
80#include "llvm/Support/ModRef.h"
81#include "llvm/Support/Mutex.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/Target/TargetMachine.h"
84#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <iterator>
89#include <string>
90#include <utility>
91
92using namespace llvm;
93
94namespace {
95
96/// Used the by the ReportedErrors class to guarantee only one error is reported
97/// at one time.
98static ManagedStatic<sys::SmartMutex<true>> ReportedErrorsLock;
99
100static bool hasPhysRegClassForType(const TargetRegisterInfo &TRI,
101 MCRegister Reg, LLT Ty) {
102 assert(Reg.isPhysical() && "reg must be a physical register");
103 assert(Ty.isValid() && "expected a valid type");
104
105 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
106 if (TRI.isTypeLegalForClass(RC: *RC, T: Ty))
107 return true;
108
109 return llvm::any_of(Range: TRI.regclasses(), P: [&](const TargetRegisterClass &RC) {
110 return RC.contains(Reg) && TRI.isTypeLegalForClass(RC, T: Ty);
111 });
112}
113
114struct MachineVerifier {
115 MachineVerifier(MachineFunctionAnalysisManager &MFAM, const char *b,
116 raw_ostream *OS, bool AbortOnError = true)
117 : MFAM(&MFAM), OS(OS ? *OS : nulls()), Banner(b),
118 ReportedErrs(AbortOnError) {}
119
120 MachineVerifier(Pass *pass, const char *b, raw_ostream *OS,
121 bool AbortOnError = true)
122 : PASS(pass), OS(OS ? *OS : nulls()), Banner(b),
123 ReportedErrs(AbortOnError) {}
124
125 MachineVerifier(const char *b, LiveIntervals *LiveInts, LiveStacks *LiveStks,
126 SlotIndexes *Indexes, raw_ostream *OS,
127 bool AbortOnError = true)
128 : OS(OS ? *OS : nulls()), Banner(b), LiveInts(LiveInts),
129 LiveStks(LiveStks), Indexes(Indexes), ReportedErrs(AbortOnError) {}
130
131 /// \returns true if no problems were found.
132 bool verify(const MachineFunction &MF);
133
134 MachineFunctionAnalysisManager *MFAM = nullptr;
135 Pass *const PASS = nullptr;
136 raw_ostream &OS;
137 const char *Banner;
138 const MachineFunction *MF = nullptr;
139 const TargetMachine *TM = nullptr;
140 const TargetInstrInfo *TII = nullptr;
141 const TargetRegisterInfo *TRI = nullptr;
142 const MachineRegisterInfo *MRI = nullptr;
143 const RegisterBankInfo *RBI = nullptr;
144
145 // Avoid querying the MachineFunctionProperties for each operand.
146 bool isFunctionRegBankSelected = false;
147 bool isFunctionSelected = false;
148 bool isFunctionTracksDebugUserValues = false;
149
150 using RegVector = SmallVector<Register, 16>;
151 using RegMaskVector = SmallVector<const uint32_t *, 4>;
152 using RegSet = DenseSet<Register>;
153 using RegMap = DenseMap<Register, const MachineInstr *>;
154 using BlockSet = SmallPtrSet<const MachineBasicBlock *, 8>;
155
156 const MachineInstr *FirstNonPHI = nullptr;
157 const MachineInstr *FirstTerminator = nullptr;
158 BlockSet FunctionBlocks;
159
160 BitVector regsReserved;
161 RegSet regsLive;
162 RegVector regsDefined, regsDead, regsKilled;
163 RegMaskVector regMasks;
164
165 // Live physical register defs of the current instruction, and the operand
166 // indices of its dead physical register defs.
167 SmallVector<MCRegister, 4> LivePhysDefs;
168 SmallVector<unsigned, 4> DeadPhysDefOps;
169
170 SlotIndex lastIndex;
171
172 // Add Reg and any sub-registers to RV
173 void addRegWithSubRegs(RegVector &RV, Register Reg) {
174 RV.push_back(Elt: Reg);
175 if (Reg.isPhysical())
176 append_range(C&: RV, R: TRI->subregs(Reg: Reg.asMCReg()));
177 }
178
179 struct BBInfo {
180 // Is this MBB reachable from the MF entry point?
181 bool reachable = false;
182
183 // Vregs that must be live in because they are used without being
184 // defined. Map value is the user. vregsLiveIn doesn't include regs
185 // that only are used by PHI nodes.
186 RegMap vregsLiveIn;
187
188 // Regs defined in MBB and live out. Note that vregs passing through may
189 // be live out without being mentioned here.
190 RegSet regsLiveOut;
191
192 // Vregs that pass through MBB untouched. This set is disjoint from
193 // regsLiveOut.
194 RegSet vregsPassed;
195
196 // Vregs that must pass through MBB because they are needed by a successor
197 // block. This set is disjoint from regsLiveOut.
198 RegSet vregsRequired;
199
200 // Set versions of block's predecessor and successor lists.
201 BlockSet Preds, Succs;
202
203 BBInfo() = default;
204
205 // Add register to vregsRequired if it belongs there. Return true if
206 // anything changed.
207 bool addRequired(Register Reg) {
208 if (!Reg.isVirtual())
209 return false;
210 if (regsLiveOut.count(V: Reg))
211 return false;
212 return vregsRequired.insert(V: Reg).second;
213 }
214
215 // Same for a full set.
216 bool addRequired(const RegSet &RS) {
217 bool Changed = false;
218 for (Register Reg : RS)
219 Changed |= addRequired(Reg);
220 return Changed;
221 }
222
223 // Same for a full map.
224 bool addRequired(const RegMap &RM) {
225 bool Changed = false;
226 for (const auto &I : RM)
227 Changed |= addRequired(Reg: I.first);
228 return Changed;
229 }
230
231 // Live-out registers are either in regsLiveOut or vregsPassed.
232 bool isLiveOut(Register Reg) const {
233 return regsLiveOut.count(V: Reg) || vregsPassed.count(V: Reg);
234 }
235 };
236
237 // Extra register info per MBB.
238 DenseMap<const MachineBasicBlock *, BBInfo> MBBInfoMap;
239
240 bool isReserved(Register Reg) {
241 return Reg.id() < regsReserved.size() && regsReserved.test(Idx: Reg.id());
242 }
243
244 bool isAllocatable(Register Reg) const {
245 return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(RegNo: Reg) &&
246 !regsReserved.test(Idx: Reg.id());
247 }
248
249 // Analysis information if available
250 LiveIntervals *LiveInts = nullptr;
251 LiveStacks *LiveStks = nullptr;
252 SlotIndexes *Indexes = nullptr;
253
254 /// A class to track the number of reported error and to guarantee that only
255 /// one error is reported at one time.
256 class ReportedErrors {
257 unsigned NumReported = 0;
258 bool AbortOnError;
259
260 public:
261 /// \param AbortOnError -- If set, abort after printing the first error.
262 ReportedErrors(bool AbortOnError) : AbortOnError(AbortOnError) {}
263
264 ~ReportedErrors() {
265 if (!hasError())
266 return;
267 if (AbortOnError)
268 report_fatal_error(reason: "Found " + Twine(NumReported) +
269 " machine code errors.");
270 // Since we haven't aborted, release the lock to allow other threads to
271 // report errors.
272 ReportedErrorsLock->unlock();
273 }
274
275 /// Increment the number of reported errors.
276 /// \returns true if this is the first reported error.
277 bool increment() {
278 // If this is the first error this thread has encountered, grab the lock
279 // to prevent other threads from reporting errors at the same time.
280 // Otherwise we assume we already have the lock.
281 if (!hasError())
282 ReportedErrorsLock->lock();
283 ++NumReported;
284 return NumReported == 1;
285 }
286
287 /// \returns true if an error was reported.
288 bool hasError() { return NumReported; }
289 };
290 ReportedErrors ReportedErrs;
291
292 // This is calculated only when trying to verify convergence control tokens.
293 // Similar to the LLVM IR verifier, we calculate this locally instead of
294 // relying on the pass manager.
295 MachineDominatorTree DT;
296
297 void visitMachineFunctionBefore();
298 void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
299 void visitMachineBundleBefore(const MachineInstr *MI);
300
301 /// Verify that all of \p MI's virtual register operands are scalars.
302 /// \returns True if all virtual register operands are scalar. False
303 /// otherwise.
304 bool verifyAllRegOpsScalar(const MachineInstr &MI,
305 const MachineRegisterInfo &MRI);
306 bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
307
308 bool verifyGIntrinsicSideEffects(const MachineInstr *MI);
309 bool verifyGIntrinsicConvergence(const MachineInstr *MI);
310 void verifyPreISelGenericInstruction(const MachineInstr *MI);
311
312 void visitMachineInstrBefore(const MachineInstr *MI);
313 void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
314 void visitMachineInstrAfter(const MachineInstr *MI);
315 void visitMachineBundleAfter(const MachineInstr *MI);
316 void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
317 void visitMachineFunctionAfter();
318
319 void report(const char *msg, const MachineFunction *MF);
320 void report(const char *msg, const MachineBasicBlock *MBB);
321 void report(const char *msg, const MachineInstr *MI);
322 void report(const char *msg, const MachineOperand *MO, unsigned MONum,
323 LLT MOVRegType = LLT{});
324 void report(const Twine &Msg, const MachineInstr *MI);
325
326 void report_context(const LiveInterval &LI) const;
327 void report_context(const LiveRange &LR, VirtRegOrUnit VRegOrUnit,
328 LaneBitmask LaneMask) const;
329 void report_context(const LiveRange::Segment &S) const;
330 void report_context(const VNInfo &VNI) const;
331 void report_context(SlotIndex Pos) const;
332 void report_context(MCPhysReg PhysReg) const;
333 void report_context_liverange(const LiveRange &LR) const;
334 void report_context_lanemask(LaneBitmask LaneMask) const;
335 void report_context_vreg(Register VReg) const;
336 void report_context_vreg_regunit(VirtRegOrUnit VRegOrUnit) const;
337
338 void verifyInlineAsm(const MachineInstr *MI);
339
340 void checkLiveness(const MachineOperand *MO, unsigned MONum);
341 void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
342 SlotIndex UseIdx, const LiveRange &LR,
343 VirtRegOrUnit VRegOrUnit,
344 LaneBitmask LaneMask = LaneBitmask::getNone());
345 void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
346 SlotIndex DefIdx, const LiveRange &LR,
347 VirtRegOrUnit VRegOrUnit, bool SubRangeCheck = false,
348 LaneBitmask LaneMask = LaneBitmask::getNone());
349
350 void markReachable(const MachineBasicBlock *MBB);
351 void calcRegsPassed();
352 void checkPHIOps(const MachineBasicBlock &MBB);
353
354 void calcRegsRequired();
355 void verifyLiveIntervals();
356 void verifyLiveInterval(const LiveInterval &);
357 void verifyLiveRangeValue(const LiveRange &, const VNInfo *, VirtRegOrUnit,
358 LaneBitmask);
359 void verifyLiveRangeSegment(const LiveRange &,
360 const LiveRange::const_iterator I, VirtRegOrUnit,
361 LaneBitmask);
362 void verifyLiveRange(const LiveRange &, VirtRegOrUnit,
363 LaneBitmask LaneMask = LaneBitmask::getNone());
364
365 void verifyStackFrame();
366 /// Check that the stack protector is the top-most object in the stack.
367 void verifyStackProtector();
368
369 void verifySlotIndexes() const;
370 void verifyProperties(const MachineFunction &MF);
371};
372
373struct MachineVerifierLegacyPass : public MachineFunctionPass {
374 static char ID; // Pass ID, replacement for typeid
375
376 const std::string Banner;
377
378 MachineVerifierLegacyPass(std::string banner = std::string())
379 : MachineFunctionPass(ID), Banner(std::move(banner)) {}
380
381 void getAnalysisUsage(AnalysisUsage &AU) const override {
382 AU.addUsedIfAvailable<LiveStacksWrapperLegacy>();
383 AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
384 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
385 AU.setPreservesAll();
386 MachineFunctionPass::getAnalysisUsage(AU);
387 }
388
389 bool runOnMachineFunction(MachineFunction &MF) override {
390 // Skip functions that have known verification problems.
391 // FIXME: Remove this mechanism when all problematic passes have been
392 // fixed.
393 if (MF.getProperties().hasFailsVerification())
394 return false;
395
396 MachineVerifier(this, Banner.c_str(), &errs()).verify(MF);
397 return false;
398 }
399};
400
401} // end anonymous namespace
402
403PreservedAnalyses
404MachineVerifierPass::run(MachineFunction &MF,
405 MachineFunctionAnalysisManager &MFAM) {
406 // Skip functions that have known verification problems.
407 // FIXME: Remove this mechanism when all problematic passes have been
408 // fixed.
409 if (MF.getProperties().hasFailsVerification())
410 return PreservedAnalyses::all();
411 MachineVerifier(MFAM, Banner.c_str(), &errs()).verify(MF);
412 return PreservedAnalyses::all();
413}
414
415char MachineVerifierLegacyPass::ID = 0;
416
417INITIALIZE_PASS(MachineVerifierLegacyPass, "machineverifier",
418 "Verify generated machine code", false, false)
419
420FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
421 return new MachineVerifierLegacyPass(Banner);
422}
423
424void llvm::verifyMachineFunction(const std::string &Banner,
425 const MachineFunction &MF) {
426 // TODO: Use MFAM after porting below analyses.
427 // LiveIntervals *LiveInts;
428 // LiveStacks *LiveStks;
429 // SlotIndexes *Indexes;
430 MachineVerifier(nullptr, Banner.c_str(), &errs()).verify(MF);
431}
432
433bool MachineFunction::verify(Pass *p, const char *Banner, raw_ostream *OS,
434 bool AbortOnError) const {
435 return MachineVerifier(p, Banner, OS, AbortOnError).verify(MF: *this);
436}
437
438bool MachineFunction::verify(MachineFunctionAnalysisManager &MFAM,
439 const char *Banner, raw_ostream *OS,
440 bool AbortOnError) const {
441 return MachineVerifier(MFAM, Banner, OS, AbortOnError).verify(MF: *this);
442}
443
444bool MachineFunction::verify(LiveIntervals *LiveInts, SlotIndexes *Indexes,
445 const char *Banner, raw_ostream *OS,
446 bool AbortOnError) const {
447 return MachineVerifier(Banner, LiveInts, /*LiveStks=*/nullptr, Indexes, OS,
448 AbortOnError)
449 .verify(MF: *this);
450}
451
452void MachineVerifier::verifySlotIndexes() const {
453 if (Indexes == nullptr)
454 return;
455
456 // Ensure the IdxMBB list is sorted by slot indexes.
457 SlotIndex Last;
458 for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
459 E = Indexes->MBBIndexEnd(); I != E; ++I) {
460 assert(!Last.isValid() || I->first > Last);
461 Last = I->first;
462 }
463}
464
465void MachineVerifier::verifyProperties(const MachineFunction &MF) {
466 // If a pass has introduced virtual registers without clearing the
467 // NoVRegs property (or set it without allocating the vregs)
468 // then report an error.
469 if (MF.getProperties().hasNoVRegs() && MRI->getNumVirtRegs())
470 report(msg: "Function has NoVRegs property but there are VReg operands", MF: &MF);
471}
472
473bool MachineVerifier::verify(const MachineFunction &MF) {
474 this->MF = &MF;
475 TM = &MF.getTarget();
476 TII = MF.getSubtarget().getInstrInfo();
477 TRI = MF.getSubtarget().getRegisterInfo();
478 RBI = MF.getSubtarget().getRegBankInfo();
479 MRI = &MF.getRegInfo();
480
481 const MachineFunctionProperties &Props = MF.getProperties();
482 const bool isFunctionFailedISel = Props.hasFailedISel();
483
484 // If we're mid-GlobalISel and we already triggered the fallback path then
485 // it's expected that the MIR is somewhat broken but that's ok since we'll
486 // reset it and clear the FailedISel attribute in ResetMachineFunctions.
487 if (isFunctionFailedISel)
488 return true;
489
490 isFunctionRegBankSelected = Props.hasRegBankSelected();
491 isFunctionSelected = Props.hasSelected();
492 isFunctionTracksDebugUserValues = Props.hasTracksDebugUserValues();
493
494 if (PASS) {
495 auto *LISWrapper = PASS->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
496 LiveInts = LISWrapper ? &LISWrapper->getLIS() : nullptr;
497 auto *LSWrapper = PASS->getAnalysisIfAvailable<LiveStacksWrapperLegacy>();
498 LiveStks = LSWrapper ? &LSWrapper->getLS() : nullptr;
499 auto *SIWrapper = PASS->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
500 Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
501 }
502 if (MFAM) {
503 MachineFunction &Func = const_cast<MachineFunction &>(MF);
504 LiveInts = MFAM->getCachedResult<LiveIntervalsAnalysis>(IR&: Func);
505 // TODO: LiveStks = MFAM->getCachedResult<LiveStacksAnalysis>(Func);
506 Indexes = MFAM->getCachedResult<SlotIndexesAnalysis>(IR&: Func);
507 }
508
509 verifySlotIndexes();
510
511 verifyProperties(MF);
512
513 visitMachineFunctionBefore();
514 for (const MachineBasicBlock &MBB : MF) {
515 visitMachineBasicBlockBefore(MBB: &MBB);
516 // Keep track of the current bundle header.
517 const MachineInstr *CurBundle = nullptr;
518 // Do we expect the next instruction to be part of the same bundle?
519 bool InBundle = false;
520
521 for (const MachineInstr &MI : MBB.instrs()) {
522 if (MI.getParent() != &MBB) {
523 report(msg: "Bad instruction parent pointer", MBB: &MBB);
524 OS << "Instruction: " << MI;
525 continue;
526 }
527
528 // Check for consistent bundle flags.
529 if (InBundle && !MI.isBundledWithPred())
530 report(msg: "Missing BundledPred flag, "
531 "BundledSucc was set on predecessor",
532 MI: &MI);
533 if (!InBundle && MI.isBundledWithPred())
534 report(msg: "BundledPred flag is set, "
535 "but BundledSucc not set on predecessor",
536 MI: &MI);
537
538 // Is this a bundle header?
539 if (!MI.isInsideBundle()) {
540 if (CurBundle)
541 visitMachineBundleAfter(MI: CurBundle);
542 CurBundle = &MI;
543 visitMachineBundleBefore(MI: CurBundle);
544 } else if (!CurBundle)
545 report(msg: "No bundle header", MI: &MI);
546 visitMachineInstrBefore(MI: &MI);
547 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
548 const MachineOperand &Op = MI.getOperand(i: I);
549 if (Op.getParent() != &MI) {
550 // Make sure to use correct addOperand / removeOperand / ChangeTo
551 // functions when replacing operands of a MachineInstr.
552 report(msg: "Instruction has operand with wrong parent set", MI: &MI);
553 }
554
555 visitMachineOperand(MO: &Op, MONum: I);
556 }
557 visitMachineInstrAfter(MI: &MI);
558
559 // Was this the last bundled instruction?
560 InBundle = MI.isBundledWithSucc();
561 }
562 if (CurBundle)
563 visitMachineBundleAfter(MI: CurBundle);
564 if (InBundle)
565 report(msg: "BundledSucc flag set on last instruction in block", MI: &MBB.back());
566 visitMachineBasicBlockAfter(MBB: &MBB);
567 }
568 visitMachineFunctionAfter();
569
570 // Clean up.
571 regsLive.clear();
572 regsDefined.clear();
573 regsDead.clear();
574 regsKilled.clear();
575 regMasks.clear();
576 MBBInfoMap.clear();
577
578 return !ReportedErrs.hasError();
579}
580
581void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
582 assert(MF);
583 OS << '\n';
584 if (ReportedErrs.increment()) {
585 if (Banner)
586 OS << "# " << Banner << '\n';
587
588 if (LiveInts != nullptr)
589 LiveInts->print(O&: OS);
590 else
591 MF->print(OS, Indexes);
592 }
593
594 OS << "*** Bad machine code: " << msg << " ***\n"
595 << "- function: " << MF->getName() << '\n';
596}
597
598void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
599 assert(MBB);
600 report(msg, MF: MBB->getParent());
601 OS << "- basic block: " << printMBBReference(MBB: *MBB) << ' ' << MBB->getName()
602 << " (" << (const void *)MBB << ')';
603 if (Indexes)
604 OS << " [" << Indexes->getMBBStartIdx(mbb: MBB) << ';'
605 << Indexes->getMBBEndIdx(mbb: MBB) << ')';
606 OS << '\n';
607}
608
609void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
610 assert(MI);
611 report(msg, MBB: MI->getParent());
612 OS << "- instruction: ";
613 if (Indexes && Indexes->hasIndex(instr: *MI))
614 OS << Indexes->getInstructionIndex(MI: *MI) << '\t';
615 MI->print(OS, /*IsStandalone=*/true);
616}
617
618void MachineVerifier::report(const char *msg, const MachineOperand *MO,
619 unsigned MONum, LLT MOVRegType) {
620 assert(MO);
621 report(msg, MI: MO->getParent());
622 OS << "- operand " << MONum << ": ";
623 MO->print(os&: OS, TypeToPrint: MOVRegType, TRI);
624 OS << '\n';
625}
626
627void MachineVerifier::report(const Twine &Msg, const MachineInstr *MI) {
628 report(msg: Msg.str().c_str(), MI);
629}
630
631void MachineVerifier::report_context(SlotIndex Pos) const {
632 OS << "- at: " << Pos << '\n';
633}
634
635void MachineVerifier::report_context(const LiveInterval &LI) const {
636 OS << "- interval: " << LI << '\n';
637}
638
639void MachineVerifier::report_context(const LiveRange &LR,
640 VirtRegOrUnit VRegOrUnit,
641 LaneBitmask LaneMask) const {
642 report_context_liverange(LR);
643 report_context_vreg_regunit(VRegOrUnit);
644 if (LaneMask.any())
645 report_context_lanemask(LaneMask);
646}
647
648void MachineVerifier::report_context(const LiveRange::Segment &S) const {
649 OS << "- segment: " << S << '\n';
650}
651
652void MachineVerifier::report_context(const VNInfo &VNI) const {
653 OS << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
654}
655
656void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
657 OS << "- liverange: " << LR << '\n';
658}
659
660void MachineVerifier::report_context(MCPhysReg PReg) const {
661 OS << "- p. register: " << printReg(Reg: PReg, TRI) << '\n';
662}
663
664void MachineVerifier::report_context_vreg(Register VReg) const {
665 OS << "- v. register: " << printReg(Reg: VReg, TRI) << '\n';
666}
667
668void MachineVerifier::report_context_vreg_regunit(
669 VirtRegOrUnit VRegOrUnit) const {
670 if (VRegOrUnit.isVirtualReg()) {
671 report_context_vreg(VReg: VRegOrUnit.asVirtualReg());
672 } else {
673 OS << "- regunit: " << printRegUnit(Unit: VRegOrUnit.asMCRegUnit(), TRI)
674 << '\n';
675 }
676}
677
678void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
679 OS << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
680}
681
682void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
683 BBInfo &MInfo = MBBInfoMap[MBB];
684 if (!MInfo.reachable) {
685 MInfo.reachable = true;
686 for (const MachineBasicBlock *Succ : MBB->successors())
687 markReachable(MBB: Succ);
688 }
689}
690
691void MachineVerifier::visitMachineFunctionBefore() {
692 lastIndex = SlotIndex();
693 regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
694 : TRI->getReservedRegs(MF: *MF);
695
696 if (!MF->empty())
697 markReachable(MBB: &MF->front());
698
699 // Build a set of the basic blocks in the function.
700 FunctionBlocks.clear();
701 for (const auto &MBB : *MF) {
702 FunctionBlocks.insert(Ptr: &MBB);
703 BBInfo &MInfo = MBBInfoMap[&MBB];
704
705 MInfo.Preds.insert_range(R: MBB.predecessors());
706 if (MInfo.Preds.size() != MBB.pred_size())
707 report(msg: "MBB has duplicate entries in its predecessor list.", MBB: &MBB);
708
709 MInfo.Succs.insert_range(R: MBB.successors());
710 if (MInfo.Succs.size() != MBB.succ_size())
711 report(msg: "MBB has duplicate entries in its successor list.", MBB: &MBB);
712 }
713
714 // Check that the register use lists are sane.
715 MRI->verifyUseLists();
716
717 if (!MF->empty()) {
718 verifyStackFrame();
719 verifyStackProtector();
720 }
721}
722
723static bool hasPHIs(const MachineFunction &MF) {
724 return !MF.getProperties().hasNoPHIs() &&
725 any_of(Range: MF, P: [](const MachineBasicBlock &MBB) {
726 return !MBB.phis().empty();
727 });
728}
729
730void
731MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
732 FirstTerminator = nullptr;
733 FirstNonPHI = nullptr;
734
735 if (MRI->tracksLiveness() && hasPHIs(MF: *MF)) {
736 // If this block has allocatable physical registers live-in, check that
737 // it is an entry block or landing pad.
738 for (const auto &LI : MBB->liveins()) {
739 if (isAllocatable(Reg: LI.PhysReg) && !MBB->isEHPad() &&
740 MBB->getIterator() != MBB->getParent()->begin() &&
741 !MBB->isInlineAsmBrIndirectTarget()) {
742 report(msg: "MBB has allocatable live-in, but isn't entry, landing-pad, or "
743 "inlineasm-br-indirect-target.",
744 MBB);
745 report_context(PReg: LI.PhysReg);
746 }
747 }
748 }
749
750 if (MBB->isIRBlockAddressTaken()) {
751 if (!MBB->getAddressTakenIRBlock()->hasAddressTaken())
752 report(msg: "ir-block-address-taken is associated with basic block not used by "
753 "a blockaddress.",
754 MBB);
755 }
756
757 // Count the number of landing pad successors.
758 SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs;
759 for (const auto *succ : MBB->successors()) {
760 if (succ->isEHPad())
761 LandingPadSuccs.insert(Ptr: succ);
762 if (!FunctionBlocks.count(Ptr: succ))
763 report(msg: "MBB has successor that isn't part of the function.", MBB);
764 if (!MBBInfoMap[succ].Preds.count(Ptr: MBB)) {
765 report(msg: "Inconsistent CFG", MBB);
766 OS << "MBB is not in the predecessor list of the successor "
767 << printMBBReference(MBB: *succ) << ".\n";
768 }
769 }
770
771 // Check the predecessor list.
772 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
773 if (!FunctionBlocks.count(Ptr: Pred))
774 report(msg: "MBB has predecessor that isn't part of the function.", MBB);
775 if (!MBBInfoMap[Pred].Succs.count(Ptr: MBB)) {
776 report(msg: "Inconsistent CFG", MBB);
777 OS << "MBB is not in the successor list of the predecessor "
778 << printMBBReference(MBB: *Pred) << ".\n";
779 }
780 }
781
782 const BasicBlock *BB = MBB->getBasicBlock();
783 const Function &F = MF->getFunction();
784 if (LandingPadSuccs.size() > 1 &&
785 !(BB && isa<SwitchInst>(Val: BB->getTerminator())) &&
786 !isScopedEHPersonality(Pers: classifyEHPersonality(Pers: F.getPersonalityFn())))
787 report(msg: "MBB has more than one landing pad successor", MBB);
788
789 // Call analyzeBranch. If it succeeds, there several more conditions to check.
790 const MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
791 SmallVector<MachineOperand, 4> Cond;
792 if (!TII->analyzeBranch(MBB: *MBB, TBB, FBB, Cond)) {
793 // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
794 // check whether its answers match up with reality.
795 if (!TBB && !FBB) {
796 // Block falls through to its successor.
797 if (!MBB->empty() && MBB->back().isBarrier() &&
798 !TII->isPredicated(MI: MBB->back())) {
799 report(msg: "MBB exits via unconditional fall-through but ends with a "
800 "barrier instruction!", MBB);
801 }
802 if (!Cond.empty()) {
803 report(msg: "MBB exits via unconditional fall-through but has a condition!",
804 MBB);
805 }
806 } else if (TBB && !FBB && Cond.empty()) {
807 // Block unconditionally branches somewhere.
808 if (MBB->empty()) {
809 report(msg: "MBB exits via unconditional branch but doesn't contain "
810 "any instructions!", MBB);
811 } else if (!MBB->back().isBarrier()) {
812 report(msg: "MBB exits via unconditional branch but doesn't end with a "
813 "barrier instruction!", MBB);
814 } else if (!MBB->back().isTerminator()) {
815 report(msg: "MBB exits via unconditional branch but the branch isn't a "
816 "terminator instruction!", MBB);
817 }
818 } else if (TBB && !FBB && !Cond.empty()) {
819 // Block conditionally branches somewhere, otherwise falls through.
820 if (MBB->empty()) {
821 report(msg: "MBB exits via conditional branch/fall-through but doesn't "
822 "contain any instructions!", MBB);
823 } else if (MBB->back().isBarrier()) {
824 report(msg: "MBB exits via conditional branch/fall-through but ends with a "
825 "barrier instruction!", MBB);
826 } else if (!MBB->back().isTerminator()) {
827 report(msg: "MBB exits via conditional branch/fall-through but the branch "
828 "isn't a terminator instruction!", MBB);
829 }
830 } else if (TBB && FBB) {
831 // Block conditionally branches somewhere, otherwise branches
832 // somewhere else.
833 if (MBB->empty()) {
834 report(msg: "MBB exits via conditional branch/branch but doesn't "
835 "contain any instructions!", MBB);
836 } else if (!MBB->back().isBarrier()) {
837 report(msg: "MBB exits via conditional branch/branch but doesn't end with a "
838 "barrier instruction!", MBB);
839 } else if (!MBB->back().isTerminator()) {
840 report(msg: "MBB exits via conditional branch/branch but the branch "
841 "isn't a terminator instruction!", MBB);
842 }
843 if (Cond.empty()) {
844 report(msg: "MBB exits via conditional branch/branch but there's no "
845 "condition!", MBB);
846 }
847 } else {
848 report(msg: "analyzeBranch returned invalid data!", MBB);
849 }
850
851 // Now check that the successors match up with the answers reported by
852 // analyzeBranch.
853 if (TBB && !MBB->isSuccessor(MBB: TBB))
854 report(msg: "MBB exits via jump or conditional branch, but its target isn't a "
855 "CFG successor!",
856 MBB);
857 if (FBB && !MBB->isSuccessor(MBB: FBB))
858 report(msg: "MBB exits via conditional branch, but its target isn't a CFG "
859 "successor!",
860 MBB);
861
862 // There might be a fallthrough to the next block if there's either no
863 // unconditional true branch, or if there's a condition, and one of the
864 // branches is missing.
865 bool Fallthrough = !TBB || (!Cond.empty() && !FBB);
866
867 // A conditional fallthrough must be an actual CFG successor, not
868 // unreachable. (Conversely, an unconditional fallthrough might not really
869 // be a successor, because the block might end in unreachable.)
870 if (!Cond.empty() && !FBB) {
871 MachineFunction::const_iterator MBBI = std::next(x: MBB->getIterator());
872 if (MBBI == MF->end()) {
873 report(msg: "MBB conditionally falls through out of function!", MBB);
874 } else if (!MBB->isSuccessor(MBB: &*MBBI))
875 report(msg: "MBB exits via conditional branch/fall-through but the CFG "
876 "successors don't match the actual successors!",
877 MBB);
878 }
879
880 // Verify that there aren't any extra un-accounted-for successors.
881 for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
882 // If this successor is one of the branch targets, it's okay.
883 if (SuccMBB == TBB || SuccMBB == FBB)
884 continue;
885 // If we might have a fallthrough, and the successor is the fallthrough
886 // block, that's also ok.
887 if (Fallthrough && SuccMBB == MBB->getNextNode())
888 continue;
889 // Also accept successors which are for exception-handling or might be
890 // inlineasm_br targets.
891 if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget())
892 continue;
893 report(msg: "MBB has unexpected successors which are not branch targets, "
894 "fallthrough, EHPads, or inlineasm_br targets.",
895 MBB);
896 }
897 }
898
899 regsLive.clear();
900 if (MRI->tracksLiveness()) {
901 for (const auto &LI : MBB->liveins()) {
902 if (!LI.PhysReg.isPhysical()) {
903 report(msg: "MBB live-in list contains non-physical register", MBB);
904 continue;
905 }
906 regsLive.insert_range(R: TRI->subregs_inclusive(Reg: LI.PhysReg));
907 }
908 }
909
910 const MachineFrameInfo &MFI = MF->getFrameInfo();
911 BitVector PR = MFI.getPristineRegs(MF: *MF);
912 for (unsigned I : PR.set_bits())
913 regsLive.insert_range(R: TRI->subregs_inclusive(Reg: I));
914
915 regsKilled.clear();
916 regsDefined.clear();
917
918 if (Indexes)
919 lastIndex = Indexes->getMBBStartIdx(mbb: MBB);
920}
921
922// This function gets called for all bundle headers, including normal
923// stand-alone unbundled instructions.
924void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
925 if (Indexes && Indexes->hasIndex(instr: *MI)) {
926 SlotIndex idx = Indexes->getInstructionIndex(MI: *MI);
927 if (!(idx > lastIndex)) {
928 report(msg: "Instruction index out of order", MI);
929 OS << "Last instruction was at " << lastIndex << '\n';
930 }
931 lastIndex = idx;
932 }
933
934 // Ensure non-terminators don't follow terminators.
935 if (MI->isTerminator()) {
936 if (!FirstTerminator)
937 FirstTerminator = MI;
938 } else if (FirstTerminator) {
939 // For GlobalISel, G_INVOKE_REGION_START is a terminator that we allow to
940 // precede non-terminators.
941 if (FirstTerminator->getOpcode() != TargetOpcode::G_INVOKE_REGION_START) {
942 report(msg: "Non-terminator instruction after the first terminator", MI);
943 OS << "First terminator was:\t" << *FirstTerminator;
944 }
945 }
946}
947
948// The operands on an INLINEASM instruction must follow a template.
949// Verify that the flag operands make sense.
950void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
951 // The first two operands on INLINEASM are the asm string and global flags.
952 if (MI->getNumOperands() < 2) {
953 report(msg: "Too few operands on inline asm", MI);
954 return;
955 }
956 if (!MI->getOperand(i: 0).isSymbol())
957 report(msg: "Asm string must be an external symbol", MI);
958 if (!MI->getOperand(i: 1).isImm())
959 report(msg: "Asm flags must be an immediate", MI);
960 // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
961 // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
962 // and Extra_IsConvergent = 32, Extra_MayUnwind = 64.
963 if (!isUInt<7>(x: MI->getOperand(i: 1).getImm()))
964 report(msg: "Unknown asm flags", MO: &MI->getOperand(i: 1), MONum: 1);
965
966 static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
967
968 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
969 unsigned NumOps;
970 for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
971 const MachineOperand &MO = MI->getOperand(i: OpNo);
972 // There may be implicit ops after the fixed operands.
973 if (!MO.isImm())
974 break;
975 const InlineAsm::Flag F(MO.getImm());
976 NumOps = 1 + F.getNumOperandRegisters();
977 }
978
979 if (OpNo > MI->getNumOperands())
980 report(msg: "Missing operands in last group", MI);
981
982 // An optional MDNode follows the groups.
983 if (OpNo < MI->getNumOperands() && MI->getOperand(i: OpNo).isMetadata())
984 ++OpNo;
985
986 // All trailing operands must be implicit registers.
987 for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
988 const MachineOperand &MO = MI->getOperand(i: OpNo);
989 if (!MO.isReg() || !MO.isImplicit())
990 report(msg: "Expected implicit register after groups", MO: &MO, MONum: OpNo);
991 }
992
993 if (MI->getOpcode() == TargetOpcode::INLINEASM_BR) {
994 const MachineBasicBlock *MBB = MI->getParent();
995
996 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = MI->getNumOperands();
997 i != e; ++i) {
998 const MachineOperand &MO = MI->getOperand(i);
999
1000 if (!MO.isMBB())
1001 continue;
1002
1003 // Check the successor & predecessor lists look ok, assume they are
1004 // not. Find the indirect target without going through the successors.
1005 const MachineBasicBlock *IndirectTargetMBB = MO.getMBB();
1006 if (!IndirectTargetMBB) {
1007 report(msg: "INLINEASM_BR indirect target does not exist", MO: &MO, MONum: i);
1008 break;
1009 }
1010
1011 if (!MBB->isSuccessor(MBB: IndirectTargetMBB))
1012 report(msg: "INLINEASM_BR indirect target missing from successor list", MO: &MO,
1013 MONum: i);
1014
1015 if (!IndirectTargetMBB->isPredecessor(MBB))
1016 report(msg: "INLINEASM_BR indirect target predecessor list missing parent",
1017 MO: &MO, MONum: i);
1018 }
1019 }
1020}
1021
1022bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr &MI,
1023 const MachineRegisterInfo &MRI) {
1024 if (none_of(Range: MI.explicit_operands(), P: [&MRI](const MachineOperand &Op) {
1025 if (!Op.isReg())
1026 return false;
1027 const auto Reg = Op.getReg();
1028 if (Reg.isPhysical())
1029 return false;
1030 return !MRI.getType(Reg).isScalar();
1031 }))
1032 return true;
1033 report(msg: "All register operands must have scalar types", MI: &MI);
1034 return false;
1035}
1036
1037/// Check that types are consistent when two operands need to have the same
1038/// number of vector elements.
1039/// \return true if the types are valid.
1040bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
1041 const MachineInstr *MI) {
1042 if (Ty0.isVector() != Ty1.isVector()) {
1043 report(msg: "operand types must be all-vector or all-scalar", MI);
1044 // Generally we try to report as many issues as possible at once, but in
1045 // this case it's not clear what should we be comparing the size of the
1046 // scalar with: the size of the whole vector or its lane. Instead of
1047 // making an arbitrary choice and emitting not so helpful message, let's
1048 // avoid the extra noise and stop here.
1049 return false;
1050 }
1051
1052 if (Ty0.isVector() && Ty0.getElementCount() != Ty1.getElementCount()) {
1053 report(msg: "operand types must preserve number of vector elements", MI);
1054 return false;
1055 }
1056
1057 return true;
1058}
1059
1060bool MachineVerifier::verifyGIntrinsicSideEffects(const MachineInstr *MI) {
1061 auto Opcode = MI->getOpcode();
1062 bool NoSideEffects = Opcode == TargetOpcode::G_INTRINSIC ||
1063 Opcode == TargetOpcode::G_INTRINSIC_CONVERGENT;
1064 unsigned IntrID = cast<GIntrinsic>(Val: MI)->getIntrinsicID();
1065 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1066 AttributeSet Attrs = Intrinsic::getFnAttributes(
1067 C&: MF->getFunction().getContext(), id: static_cast<Intrinsic::ID>(IntrID));
1068 bool DeclHasSideEffects = !Attrs.getMemoryEffects().doesNotAccessMemory();
1069 if (NoSideEffects && DeclHasSideEffects) {
1070 report(Msg: Twine(TII->getName(Opcode),
1071 " used with intrinsic that accesses memory"),
1072 MI);
1073 return false;
1074 }
1075 if (!NoSideEffects && !DeclHasSideEffects) {
1076 report(Msg: Twine(TII->getName(Opcode), " used with readnone intrinsic"), MI);
1077 return false;
1078 }
1079 }
1080
1081 return true;
1082}
1083
1084bool MachineVerifier::verifyGIntrinsicConvergence(const MachineInstr *MI) {
1085 auto Opcode = MI->getOpcode();
1086 bool NotConvergent = Opcode == TargetOpcode::G_INTRINSIC ||
1087 Opcode == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS;
1088 unsigned IntrID = cast<GIntrinsic>(Val: MI)->getIntrinsicID();
1089 if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
1090 AttributeSet Attrs = Intrinsic::getFnAttributes(
1091 C&: MF->getFunction().getContext(), id: static_cast<Intrinsic::ID>(IntrID));
1092 bool DeclIsConvergent = Attrs.hasAttribute(Kind: Attribute::Convergent);
1093 if (NotConvergent && DeclIsConvergent) {
1094 report(Msg: Twine(TII->getName(Opcode), " used with a convergent intrinsic"),
1095 MI);
1096 return false;
1097 }
1098 if (!NotConvergent && !DeclIsConvergent) {
1099 report(
1100 Msg: Twine(TII->getName(Opcode), " used with a non-convergent intrinsic"),
1101 MI);
1102 return false;
1103 }
1104 }
1105
1106 return true;
1107}
1108
1109void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
1110 if (isFunctionSelected)
1111 report(msg: "Unexpected generic instruction in a Selected function", MI);
1112
1113 const MCInstrDesc &MCID = MI->getDesc();
1114 unsigned NumOps = MI->getNumOperands();
1115
1116 // Branches must reference a basic block if they are not indirect
1117 if (MI->isBranch() && !MI->isIndirectBranch()) {
1118 bool HasMBB = false;
1119 for (const MachineOperand &Op : MI->operands()) {
1120 if (Op.isMBB()) {
1121 HasMBB = true;
1122 break;
1123 }
1124 }
1125
1126 if (!HasMBB) {
1127 report(msg: "Branch instruction is missing a basic block operand or "
1128 "isIndirectBranch property",
1129 MI);
1130 }
1131 }
1132
1133 // Check types.
1134 SmallVector<LLT, 4> Types;
1135 for (unsigned I = 0, E = std::min(a: MCID.getNumOperands(), b: NumOps);
1136 I != E; ++I) {
1137 if (!MCID.operands()[I].isGenericType())
1138 continue;
1139 // Generic instructions specify type equality constraints between some of
1140 // their operands. Make sure these are consistent.
1141 size_t TypeIdx = MCID.operands()[I].getGenericTypeIndex();
1142 Types.resize(N: std::max(a: TypeIdx + 1, b: Types.size()));
1143
1144 const MachineOperand *MO = &MI->getOperand(i: I);
1145 if (!MO->isReg()) {
1146 report(msg: "generic instruction must use register operands", MI);
1147 continue;
1148 }
1149
1150 LLT OpTy = MRI->getType(Reg: MO->getReg());
1151 // Don't report a type mismatch if there is no actual mismatch, only a
1152 // type missing, to reduce noise:
1153 if (OpTy.isValid()) {
1154 // Only the first valid type for a type index will be printed: don't
1155 // overwrite it later so it's always clear which type was expected:
1156 if (!Types[TypeIdx].isValid())
1157 Types[TypeIdx] = OpTy;
1158 else if (Types[TypeIdx] != OpTy)
1159 report(msg: "Type mismatch in generic instruction", MO, MONum: I, MOVRegType: OpTy);
1160 } else {
1161 // Generic instructions must have types attached to their operands.
1162 report(msg: "Generic instruction is missing a virtual register type", MO, MONum: I);
1163 }
1164 }
1165
1166 // Generic opcodes must not have physical register operands.
1167 for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
1168 const MachineOperand *MO = &MI->getOperand(i: I);
1169 if (MO->isReg() && MO->getReg().isPhysical())
1170 report(msg: "Generic instruction cannot have physical register", MO, MONum: I);
1171 }
1172
1173 // Avoid out of bounds in checks below. This was already reported earlier.
1174 if (MI->getNumOperands() < MCID.getNumOperands())
1175 return;
1176
1177 StringRef ErrorInfo;
1178 if (!TII->verifyInstruction(MI: *MI, ErrInfo&: ErrorInfo))
1179 report(msg: ErrorInfo.data(), MI);
1180
1181 // Verify properties of various specific instruction types
1182 unsigned Opc = MI->getOpcode();
1183 switch (Opc) {
1184 case TargetOpcode::G_ASSERT_SEXT:
1185 case TargetOpcode::G_ASSERT_ZEXT: {
1186 std::string OpcName =
1187 Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
1188 if (!MI->getOperand(i: 2).isImm()) {
1189 report(Msg: Twine(OpcName, " expects an immediate operand #2"), MI);
1190 break;
1191 }
1192
1193 Register Dst = MI->getOperand(i: 0).getReg();
1194 Register Src = MI->getOperand(i: 1).getReg();
1195 LLT SrcTy = MRI->getType(Reg: Src);
1196 int64_t Imm = MI->getOperand(i: 2).getImm();
1197 if (Imm <= 0) {
1198 report(Msg: Twine(OpcName, " size must be >= 1"), MI);
1199 break;
1200 }
1201
1202 if (Imm >= SrcTy.getScalarSizeInBits()) {
1203 report(Msg: Twine(OpcName, " size must be less than source bit width"), MI);
1204 break;
1205 }
1206
1207 const RegisterBank *SrcRB = RBI->getRegBank(Reg: Src, MRI: *MRI, TRI: *TRI);
1208 const RegisterBank *DstRB = RBI->getRegBank(Reg: Dst, MRI: *MRI, TRI: *TRI);
1209
1210 // Allow only the source bank to be set.
1211 if ((SrcRB && DstRB && SrcRB != DstRB) || (DstRB && !SrcRB)) {
1212 report(Msg: Twine(OpcName, " cannot change register bank"), MI);
1213 break;
1214 }
1215
1216 // Don't allow a class change. Do allow member class->regbank.
1217 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(Reg: Dst);
1218 if (DstRC && DstRC != MRI->getRegClassOrNull(Reg: Src)) {
1219 report(
1220 Msg: Twine(OpcName, " source and destination register classes must match"),
1221 MI);
1222 break;
1223 }
1224
1225 break;
1226 }
1227
1228 case TargetOpcode::G_CONSTANT:
1229 case TargetOpcode::G_FCONSTANT: {
1230 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1231 if (DstTy.isVector())
1232 report(msg: "Instruction cannot use a vector result type", MI);
1233
1234 if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
1235 if (!MI->getOperand(i: 1).isCImm()) {
1236 report(msg: "G_CONSTANT operand must be cimm", MI);
1237 break;
1238 }
1239
1240 const ConstantInt *CI = MI->getOperand(i: 1).getCImm();
1241 if (CI->getBitWidth() != DstTy.getSizeInBits())
1242 report(msg: "inconsistent constant size", MI);
1243 } else {
1244 if (!MI->getOperand(i: 1).isFPImm()) {
1245 report(msg: "G_FCONSTANT operand must be fpimm", MI);
1246 break;
1247 }
1248 const ConstantFP *CF = MI->getOperand(i: 1).getFPImm();
1249
1250 if (APFloat::getSizeInBits(Sem: CF->getValueAPF().getSemantics()) !=
1251 DstTy.getSizeInBits()) {
1252 report(msg: "inconsistent constant size", MI);
1253 }
1254 }
1255
1256 break;
1257 }
1258 case TargetOpcode::G_LOAD:
1259 case TargetOpcode::G_STORE:
1260 case TargetOpcode::G_ZEXTLOAD:
1261 case TargetOpcode::G_SEXTLOAD:
1262 case TargetOpcode::G_FPEXTLOAD:
1263 case TargetOpcode::G_FPTRUNCSTORE: {
1264 LLT ValTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1265 LLT PtrTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1266 if (!PtrTy.isPointer())
1267 report(msg: "Generic memory instruction must access a pointer", MI);
1268
1269 // Generic loads and stores must have a single MachineMemOperand
1270 // describing that access.
1271 if (!MI->hasOneMemOperand()) {
1272 report(msg: "Generic instruction accessing memory must have one mem operand",
1273 MI);
1274 } else {
1275 const MachineMemOperand &MMO = **MI->memoperands_begin();
1276 if (isa<GExtLoad>(Val: *MI)) {
1277 if (TypeSize::isKnownGE(LHS: MMO.getSizeInBits().getValue(),
1278 RHS: ValTy.getSizeInBits()))
1279 report(msg: "Generic extload must have a narrower memory type", MI);
1280 } else if (isa<GFPTruncStore>(Val: *MI)) {
1281 if (TypeSize::isKnownGE(LHS: MMO.getSizeInBits().getValue(),
1282 RHS: ValTy.getSizeInBits()))
1283 report(msg: "Generic truncstore must have a narrower memory type", MI);
1284 } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
1285 if (TypeSize::isKnownGT(LHS: MMO.getSize().getValue(),
1286 RHS: ValTy.getSizeInBytes()))
1287 report(msg: "load memory size cannot exceed result size", MI);
1288
1289 if (MMO.getRanges()) {
1290 ConstantInt *i =
1291 mdconst::extract<ConstantInt>(MD: MMO.getRanges()->getOperand(I: 0));
1292 const LLT RangeTy = LLT::scalar(SizeInBits: i->getIntegerType()->getBitWidth());
1293 const LLT MemTy = MMO.getMemoryType();
1294 if (MemTy.getScalarType() != RangeTy ||
1295 ValTy.isScalar() != MemTy.isScalar() ||
1296 (ValTy.isVector() &&
1297 ValTy.getNumElements() != MemTy.getNumElements())) {
1298 report(msg: "range is incompatible with the result type", MI);
1299 }
1300 }
1301 } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
1302 if (TypeSize::isKnownLT(LHS: ValTy.getSizeInBytes(),
1303 RHS: MMO.getSize().getValue()))
1304 report(msg: "store memory size cannot exceed value size", MI);
1305 }
1306
1307 const AtomicOrdering Order = MMO.getSuccessOrdering();
1308 if (isa<GAnyStore>(Val: *MI)) {
1309 if (Order == AtomicOrdering::Acquire ||
1310 Order == AtomicOrdering::AcquireRelease)
1311 report(msg: "atomic store cannot use acquire ordering", MI);
1312
1313 } else {
1314 if (Order == AtomicOrdering::Release ||
1315 Order == AtomicOrdering::AcquireRelease)
1316 report(msg: "atomic load cannot use release ordering", MI);
1317 }
1318 }
1319
1320 break;
1321 }
1322 case TargetOpcode::G_PHI: {
1323 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1324 if (!DstTy.isValid() || !all_of(Range: drop_begin(RangeOrContainer: MI->operands()),
1325 P: [this, &DstTy](const MachineOperand &MO) {
1326 if (!MO.isReg())
1327 return true;
1328 LLT Ty = MRI->getType(Reg: MO.getReg());
1329 if (!Ty.isValid() || (Ty != DstTy))
1330 return false;
1331 return true;
1332 }))
1333 report(msg: "Generic Instruction G_PHI has operands with incompatible/missing "
1334 "types",
1335 MI);
1336 break;
1337 }
1338 case TargetOpcode::G_BITCAST: {
1339 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1340 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1341 if (!DstTy.isValid() || !SrcTy.isValid())
1342 break;
1343
1344 if (SrcTy.isPointer() != DstTy.isPointer())
1345 report(msg: "bitcast cannot convert between pointers and other types", MI);
1346
1347 if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1348 report(msg: "bitcast sizes must match", MI);
1349
1350 bool SameType = SrcTy.getKind() == DstTy.getKind();
1351 if (SameType && SrcTy.isPointerOrPointerVector())
1352 SameType &= SrcTy.getAddressSpace() == DstTy.getAddressSpace();
1353
1354 SameType &= SrcTy.getScalarSizeInBits() == DstTy.getScalarSizeInBits();
1355
1356 if (SameType && SrcTy.isVector())
1357 SameType &= SrcTy.getElementCount() == DstTy.getElementCount();
1358 if (SameType && SrcTy.isFloatOrFloatVector())
1359 SameType &= SrcTy.getFpSemantics() == DstTy.getFpSemantics();
1360
1361 if (SameType)
1362 report(msg: "bitcast must change the type", MI);
1363
1364 break;
1365 }
1366 case TargetOpcode::G_INTTOPTR:
1367 case TargetOpcode::G_PTRTOINT:
1368 case TargetOpcode::G_ADDRSPACE_CAST: {
1369 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1370 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1371 if (!DstTy.isValid() || !SrcTy.isValid())
1372 break;
1373
1374 verifyVectorElementMatch(Ty0: DstTy, Ty1: SrcTy, MI);
1375
1376 DstTy = DstTy.getScalarType();
1377 SrcTy = SrcTy.getScalarType();
1378
1379 if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
1380 if (!DstTy.isPointer())
1381 report(msg: "inttoptr result type must be a pointer", MI);
1382 if (SrcTy.isPointer())
1383 report(msg: "inttoptr source type must not be a pointer", MI);
1384 } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
1385 if (!SrcTy.isPointer())
1386 report(msg: "ptrtoint source type must be a pointer", MI);
1387 if (DstTy.isPointer())
1388 report(msg: "ptrtoint result type must not be a pointer", MI);
1389 } else {
1390 assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
1391 if (!SrcTy.isPointer() || !DstTy.isPointer())
1392 report(msg: "addrspacecast types must be pointers", MI);
1393 else {
1394 if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
1395 report(msg: "addrspacecast must convert different address spaces", MI);
1396 }
1397 }
1398
1399 break;
1400 }
1401 case TargetOpcode::G_PTR_ADD: {
1402 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1403 LLT PtrTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1404 LLT OffsetTy = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
1405 if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
1406 break;
1407
1408 if (!PtrTy.isPointerOrPointerVector())
1409 report(msg: "gep first operand must be a pointer", MI);
1410
1411 if (OffsetTy.isPointerOrPointerVector())
1412 report(msg: "gep offset operand must not be a pointer", MI);
1413
1414 if (PtrTy.isPointerOrPointerVector()) {
1415 const DataLayout &DL = MF->getDataLayout();
1416 unsigned AS = PtrTy.getAddressSpace();
1417 unsigned IndexSizeInBits = DL.getIndexSize(AS) * 8;
1418 if (OffsetTy.getScalarSizeInBits() != IndexSizeInBits) {
1419 report(msg: "gep offset operand must match index size for address space",
1420 MI);
1421 }
1422 }
1423
1424 // TODO: Is the offset allowed to be a scalar with a vector?
1425 break;
1426 }
1427 case TargetOpcode::G_PTRMASK: {
1428 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1429 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1430 LLT MaskTy = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
1431 if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid())
1432 break;
1433
1434 if (!DstTy.isPointerOrPointerVector())
1435 report(msg: "ptrmask result type must be a pointer", MI);
1436
1437 if (!MaskTy.getScalarType().isScalar())
1438 report(msg: "ptrmask mask type must be an integer", MI);
1439
1440 verifyVectorElementMatch(Ty0: DstTy, Ty1: MaskTy, MI);
1441 break;
1442 }
1443 case TargetOpcode::G_SEXT:
1444 case TargetOpcode::G_ZEXT:
1445 case TargetOpcode::G_ANYEXT:
1446 case TargetOpcode::G_TRUNC:
1447 case TargetOpcode::G_TRUNC_SSAT_S:
1448 case TargetOpcode::G_TRUNC_SSAT_U:
1449 case TargetOpcode::G_TRUNC_USAT_U:
1450 case TargetOpcode::G_FPEXT:
1451 case TargetOpcode::G_FPTRUNC: {
1452 // Number of operands and presense of types is already checked (and
1453 // reported in case of any issues), so no need to report them again. As
1454 // we're trying to report as many issues as possible at once, however, the
1455 // instructions aren't guaranteed to have the right number of operands or
1456 // types attached to them at this point
1457 assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
1458 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1459 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1460 if (!DstTy.isValid() || !SrcTy.isValid())
1461 break;
1462
1463 if (DstTy.isPointerOrPointerVector() || SrcTy.isPointerOrPointerVector())
1464 report(msg: "Generic extend/truncate can not operate on pointers", MI);
1465
1466 verifyVectorElementMatch(Ty0: DstTy, Ty1: SrcTy, MI);
1467
1468 unsigned DstSize = DstTy.getScalarSizeInBits();
1469 unsigned SrcSize = SrcTy.getScalarSizeInBits();
1470 switch (MI->getOpcode()) {
1471 default:
1472 if (DstSize <= SrcSize)
1473 report(msg: "Generic extend has destination type no larger than source", MI);
1474 break;
1475 case TargetOpcode::G_TRUNC:
1476 case TargetOpcode::G_TRUNC_SSAT_S:
1477 case TargetOpcode::G_TRUNC_SSAT_U:
1478 case TargetOpcode::G_TRUNC_USAT_U:
1479 case TargetOpcode::G_FPTRUNC:
1480 if (DstSize >= SrcSize)
1481 report(msg: "Generic truncate has destination type no smaller than source",
1482 MI);
1483 break;
1484 }
1485 break;
1486 }
1487 case TargetOpcode::G_SELECT: {
1488 LLT SelTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1489 LLT CondTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1490 if (!SelTy.isValid() || !CondTy.isValid())
1491 break;
1492
1493 // Scalar condition select on a vector is valid.
1494 if (CondTy.isVector())
1495 verifyVectorElementMatch(Ty0: SelTy, Ty1: CondTy, MI);
1496 break;
1497 }
1498 case TargetOpcode::G_MERGE_VALUES: {
1499 // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
1500 // e.g. s2N = MERGE sN, sN
1501 // Merging multiple scalars into a vector is not allowed, should use
1502 // G_BUILD_VECTOR for that.
1503 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1504 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1505 if (DstTy.isVector() || SrcTy.isVector())
1506 report(msg: "G_MERGE_VALUES cannot operate on vectors", MI);
1507
1508 const unsigned NumOps = MI->getNumOperands();
1509 if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
1510 report(msg: "G_MERGE_VALUES result size is inconsistent", MI);
1511
1512 for (unsigned I = 2; I != NumOps; ++I) {
1513 if (MRI->getType(Reg: MI->getOperand(i: I).getReg()) != SrcTy)
1514 report(msg: "G_MERGE_VALUES source types do not match", MI);
1515 }
1516
1517 break;
1518 }
1519 case TargetOpcode::G_UNMERGE_VALUES: {
1520 unsigned NumDsts = MI->getNumOperands() - 1;
1521 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1522 for (unsigned i = 1; i < NumDsts; ++i) {
1523 if (MRI->getType(Reg: MI->getOperand(i).getReg()) != DstTy) {
1524 report(msg: "G_UNMERGE_VALUES destination types do not match", MI);
1525 break;
1526 }
1527 }
1528
1529 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: NumDsts).getReg());
1530 if (DstTy.isVector()) {
1531 // This case is the converse of G_CONCAT_VECTORS.
1532 if (!SrcTy.isVector() ||
1533 (SrcTy.getScalarType() != DstTy.getScalarType() &&
1534 !SrcTy.isPointerVector()) ||
1535 SrcTy.isScalableVector() != DstTy.isScalableVector() ||
1536 SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1537 report(msg: "G_UNMERGE_VALUES source operand does not match vector "
1538 "destination operands",
1539 MI);
1540 } else if (SrcTy.isVector()) {
1541 // This case is the converse of G_BUILD_VECTOR, but relaxed to allow
1542 // mismatched types as long as the total size matches:
1543 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<4 x s32>)
1544 if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits())
1545 report(msg: "G_UNMERGE_VALUES vector source operand does not match scalar "
1546 "destination operands",
1547 MI);
1548 } else {
1549 // This case is the converse of G_MERGE_VALUES.
1550 if (SrcTy.getSizeInBits() != NumDsts * DstTy.getSizeInBits()) {
1551 report(msg: "G_UNMERGE_VALUES scalar source operand does not match scalar "
1552 "destination operands",
1553 MI);
1554 }
1555 }
1556 break;
1557 }
1558 case TargetOpcode::G_BUILD_VECTOR: {
1559 // Source types must be scalars, dest type a vector. Total size of scalars
1560 // must match the dest vector size.
1561 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1562 LLT SrcEltTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1563 if (!DstTy.isVector() || SrcEltTy.isVector()) {
1564 report(msg: "G_BUILD_VECTOR must produce a vector from scalar operands", MI);
1565 break;
1566 }
1567
1568 if (DstTy.getElementType() != SrcEltTy)
1569 report(msg: "G_BUILD_VECTOR result element type must match source type", MI);
1570
1571 if (DstTy.getNumElements() != MI->getNumOperands() - 1)
1572 report(msg: "G_BUILD_VECTOR must have an operand for each element", MI);
1573
1574 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI->operands(), N: 2))
1575 if (MRI->getType(Reg: MI->getOperand(i: 1).getReg()) != MRI->getType(Reg: MO.getReg()))
1576 report(msg: "G_BUILD_VECTOR source operand types are not homogeneous", MI);
1577
1578 break;
1579 }
1580 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1581 // Source types must be scalars, dest type a vector. Scalar types must be
1582 // larger than the dest vector elt type, as this is a truncating operation.
1583 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1584 LLT SrcEltTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1585 if (!DstTy.isVector() || SrcEltTy.isVector())
1586 report(msg: "G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
1587 MI);
1588 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI->operands(), N: 2))
1589 if (MRI->getType(Reg: MI->getOperand(i: 1).getReg()) != MRI->getType(Reg: MO.getReg()))
1590 report(msg: "G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
1591 MI);
1592 if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
1593 report(msg: "G_BUILD_VECTOR_TRUNC source operand types are not larger than "
1594 "dest elt type",
1595 MI);
1596 break;
1597 }
1598 case TargetOpcode::G_CONCAT_VECTORS: {
1599 // Source types should be vectors, and total size should match the dest
1600 // vector size.
1601 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1602 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1603 if (!DstTy.isVector() || !SrcTy.isVector())
1604 report(msg: "G_CONCAT_VECTOR requires vector source and destination operands",
1605 MI);
1606
1607 if (MI->getNumOperands() < 3)
1608 report(msg: "G_CONCAT_VECTOR requires at least 2 source operands", MI);
1609
1610 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI->operands(), N: 2))
1611 if (MRI->getType(Reg: MI->getOperand(i: 1).getReg()) != MRI->getType(Reg: MO.getReg()))
1612 report(msg: "G_CONCAT_VECTOR source operand types are not homogeneous", MI);
1613 if (DstTy.getElementCount() !=
1614 SrcTy.getElementCount() * (MI->getNumOperands() - 1))
1615 report(msg: "G_CONCAT_VECTOR num dest and source elements should match", MI);
1616 break;
1617 }
1618 case TargetOpcode::G_ICMP:
1619 case TargetOpcode::G_FCMP: {
1620 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1621 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
1622
1623 if ((DstTy.isVector() != SrcTy.isVector()) ||
1624 (DstTy.isVector() &&
1625 DstTy.getElementCount() != SrcTy.getElementCount()))
1626 report(msg: "Generic vector icmp/fcmp must preserve number of lanes", MI);
1627
1628 break;
1629 }
1630 case TargetOpcode::G_SCMP:
1631 case TargetOpcode::G_UCMP: {
1632 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1633 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1634
1635 if (SrcTy.isPointerOrPointerVector()) {
1636 report(msg: "Generic scmp/ucmp does not support pointers as operands", MI);
1637 break;
1638 }
1639
1640 if (DstTy.isPointerOrPointerVector()) {
1641 report(msg: "Generic scmp/ucmp does not support pointers as a result", MI);
1642 break;
1643 }
1644
1645 if (DstTy.getScalarSizeInBits() < 2) {
1646 report(msg: "Result type must be at least 2 bits wide", MI);
1647 break;
1648 }
1649
1650 if ((DstTy.isVector() != SrcTy.isVector()) ||
1651 (DstTy.isVector() &&
1652 DstTy.getElementCount() != SrcTy.getElementCount())) {
1653 report(msg: "Generic vector scmp/ucmp must preserve number of lanes", MI);
1654 break;
1655 }
1656
1657 break;
1658 }
1659 case TargetOpcode::G_EXTRACT: {
1660 const MachineOperand &SrcOp = MI->getOperand(i: 1);
1661 if (!SrcOp.isReg()) {
1662 report(msg: "extract source must be a register", MI);
1663 break;
1664 }
1665
1666 const MachineOperand &OffsetOp = MI->getOperand(i: 2);
1667 if (!OffsetOp.isImm()) {
1668 report(msg: "extract offset must be a constant", MI);
1669 break;
1670 }
1671
1672 unsigned DstSize = MRI->getType(Reg: MI->getOperand(i: 0).getReg()).getSizeInBits();
1673 unsigned SrcSize = MRI->getType(Reg: SrcOp.getReg()).getSizeInBits();
1674 if (SrcSize == DstSize)
1675 report(msg: "extract source must be larger than result", MI);
1676
1677 if (DstSize + OffsetOp.getImm() > SrcSize)
1678 report(msg: "extract reads past end of register", MI);
1679 break;
1680 }
1681 case TargetOpcode::G_INSERT: {
1682 const MachineOperand &SrcOp = MI->getOperand(i: 2);
1683 if (!SrcOp.isReg()) {
1684 report(msg: "insert source must be a register", MI);
1685 break;
1686 }
1687
1688 const MachineOperand &OffsetOp = MI->getOperand(i: 3);
1689 if (!OffsetOp.isImm()) {
1690 report(msg: "insert offset must be a constant", MI);
1691 break;
1692 }
1693
1694 unsigned DstSize = MRI->getType(Reg: MI->getOperand(i: 0).getReg()).getSizeInBits();
1695 unsigned SrcSize = MRI->getType(Reg: SrcOp.getReg()).getSizeInBits();
1696
1697 if (DstSize <= SrcSize)
1698 report(msg: "inserted size must be smaller than total register", MI);
1699
1700 if (SrcSize + OffsetOp.getImm() > DstSize)
1701 report(msg: "insert writes past end of register", MI);
1702
1703 break;
1704 }
1705 case TargetOpcode::G_JUMP_TABLE: {
1706 if (!MI->getOperand(i: 1).isJTI())
1707 report(msg: "G_JUMP_TABLE source operand must be a jump table index", MI);
1708 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1709 if (!DstTy.isPointer())
1710 report(msg: "G_JUMP_TABLE dest operand must have a pointer type", MI);
1711 break;
1712 }
1713 case TargetOpcode::G_BRJT: {
1714 if (!MRI->getType(Reg: MI->getOperand(i: 0).getReg()).isPointer())
1715 report(msg: "G_BRJT src operand 0 must be a pointer type", MI);
1716
1717 if (!MI->getOperand(i: 1).isJTI())
1718 report(msg: "G_BRJT src operand 1 must be a jump table index", MI);
1719
1720 const auto &IdxOp = MI->getOperand(i: 2);
1721 if (!IdxOp.isReg() || MRI->getType(Reg: IdxOp.getReg()).isPointer())
1722 report(msg: "G_BRJT src operand 2 must be a scalar reg type", MI);
1723 break;
1724 }
1725 case TargetOpcode::G_INTRINSIC:
1726 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
1727 case TargetOpcode::G_INTRINSIC_CONVERGENT:
1728 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS: {
1729 // TODO: Should verify number of def and use operands, but the current
1730 // interface requires passing in IR types for mangling.
1731 const MachineOperand &IntrIDOp = MI->getOperand(i: MI->getNumExplicitDefs());
1732 if (!IntrIDOp.isIntrinsicID()) {
1733 report(msg: "G_INTRINSIC first src operand must be an intrinsic ID", MI);
1734 break;
1735 }
1736
1737 if (!verifyGIntrinsicSideEffects(MI))
1738 break;
1739 if (!verifyGIntrinsicConvergence(MI))
1740 break;
1741
1742 break;
1743 }
1744 case TargetOpcode::G_SEXT_INREG: {
1745 if (!MI->getOperand(i: 2).isImm()) {
1746 report(msg: "G_SEXT_INREG expects an immediate operand #2", MI);
1747 break;
1748 }
1749
1750 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1751 int64_t Imm = MI->getOperand(i: 2).getImm();
1752 if (Imm <= 0)
1753 report(msg: "G_SEXT_INREG size must be >= 1", MI);
1754 if (Imm >= SrcTy.getScalarSizeInBits())
1755 report(msg: "G_SEXT_INREG size must be less than source bit width", MI);
1756 break;
1757 }
1758 case TargetOpcode::G_BSWAP: {
1759 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1760 if (DstTy.getScalarSizeInBits() % 16 != 0)
1761 report(msg: "G_BSWAP size must be a multiple of 16 bits", MI);
1762 break;
1763 }
1764 case TargetOpcode::G_VSCALE: {
1765 if (!MI->getOperand(i: 1).isCImm()) {
1766 report(msg: "G_VSCALE operand must be cimm", MI);
1767 break;
1768 }
1769 if (MI->getOperand(i: 1).getCImm()->isZero()) {
1770 report(msg: "G_VSCALE immediate cannot be zero", MI);
1771 break;
1772 }
1773 break;
1774 }
1775 case TargetOpcode::G_STEP_VECTOR: {
1776 if (!MI->getOperand(i: 1).isCImm()) {
1777 report(msg: "operand must be cimm", MI);
1778 break;
1779 }
1780
1781 if (!MI->getOperand(i: 1).getCImm()->getValue().isStrictlyPositive()) {
1782 report(msg: "step must be > 0", MI);
1783 break;
1784 }
1785
1786 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1787 if (!DstTy.isScalableVector()) {
1788 report(msg: "Destination type must be a scalable vector", MI);
1789 break;
1790 }
1791
1792 // <vscale x 2 x p0>
1793 if (!DstTy.getElementType().isScalar()) {
1794 report(msg: "Destination element type must be scalar", MI);
1795 break;
1796 }
1797
1798 if (MI->getOperand(i: 1).getCImm()->getBitWidth() !=
1799 DstTy.getElementType().getScalarSizeInBits()) {
1800 report(msg: "step bitwidth differs from result type element bitwidth", MI);
1801 break;
1802 }
1803 break;
1804 }
1805 case TargetOpcode::G_INSERT_SUBVECTOR: {
1806 const MachineOperand &Src0Op = MI->getOperand(i: 1);
1807 if (!Src0Op.isReg()) {
1808 report(msg: "G_INSERT_SUBVECTOR first source must be a register", MI);
1809 break;
1810 }
1811
1812 const MachineOperand &Src1Op = MI->getOperand(i: 2);
1813 if (!Src1Op.isReg()) {
1814 report(msg: "G_INSERT_SUBVECTOR second source must be a register", MI);
1815 break;
1816 }
1817
1818 const MachineOperand &IndexOp = MI->getOperand(i: 3);
1819 if (!IndexOp.isImm()) {
1820 report(msg: "G_INSERT_SUBVECTOR index must be an immediate", MI);
1821 break;
1822 }
1823
1824 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1825 LLT Src1Ty = MRI->getType(Reg: Src1Op.getReg());
1826
1827 if (!DstTy.isVector()) {
1828 report(msg: "Destination type must be a vector", MI);
1829 break;
1830 }
1831
1832 if (!Src1Ty.isVector()) {
1833 report(msg: "Second source must be a vector", MI);
1834 break;
1835 }
1836
1837 if (DstTy.getElementType() != Src1Ty.getElementType()) {
1838 report(msg: "Element type of vectors must be the same", MI);
1839 break;
1840 }
1841
1842 if (!DstTy.isScalable() && Src1Ty.isScalable()) {
1843 report(msg: "Cannot insert a scalable vector into a fixed length vector", MI);
1844 break;
1845 }
1846
1847 bool IsMixedFixedIntoScalable =
1848 DstTy.isScalableVector() && Src1Ty.isFixedVector();
1849
1850 if (!IsMixedFixedIntoScalable &&
1851 ElementCount::isKnownGT(LHS: Src1Ty.getElementCount(),
1852 RHS: DstTy.getElementCount())) {
1853 report(msg: "Second source must be smaller than destination vector", MI);
1854 break;
1855 }
1856
1857 uint64_t Idx = IndexOp.getImm();
1858 uint64_t Src1MinLen = Src1Ty.getElementCount().getKnownMinValue();
1859 if (IndexOp.getImm() % Src1MinLen != 0) {
1860 report(msg: "Index must be a multiple of the second source vector's "
1861 "minimum vector length",
1862 MI);
1863 break;
1864 }
1865
1866 uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1867 if (Idx >= DstMinLen ||
1868 (!IsMixedFixedIntoScalable && Idx + Src1MinLen > DstMinLen)) {
1869 report(msg: "Subvector type and index must not cause insert to overrun the "
1870 "vector being inserted into",
1871 MI);
1872 break;
1873 }
1874
1875 break;
1876 }
1877 case TargetOpcode::G_EXTRACT_SUBVECTOR: {
1878 const MachineOperand &SrcOp = MI->getOperand(i: 1);
1879 if (!SrcOp.isReg()) {
1880 report(msg: "G_EXTRACT_SUBVECTOR first source must be a register", MI);
1881 break;
1882 }
1883
1884 const MachineOperand &IndexOp = MI->getOperand(i: 2);
1885 if (!IndexOp.isImm()) {
1886 report(msg: "G_EXTRACT_SUBVECTOR index must be an immediate", MI);
1887 break;
1888 }
1889
1890 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1891 LLT SrcTy = MRI->getType(Reg: SrcOp.getReg());
1892
1893 if (!DstTy.isVector()) {
1894 report(msg: "Destination type must be a vector", MI);
1895 break;
1896 }
1897
1898 if (!SrcTy.isVector()) {
1899 report(msg: "Source must be a vector", MI);
1900 break;
1901 }
1902
1903 if (DstTy.getElementType() != SrcTy.getElementType()) {
1904 report(msg: "Element type of vectors must be the same", MI);
1905 break;
1906 }
1907
1908 if (DstTy.isScalable() && !SrcTy.isScalable()) {
1909 report(msg: "Cannot extract a scalable vector from a fixed length vector", MI);
1910 break;
1911 }
1912
1913 if (ElementCount::isKnownGT(LHS: DstTy.getElementCount(),
1914 RHS: SrcTy.getElementCount())) {
1915 report(msg: "Destination vector must be smaller than source vector", MI);
1916 break;
1917 }
1918
1919 uint64_t Idx = IndexOp.getImm();
1920 uint64_t DstMinLen = DstTy.getElementCount().getKnownMinValue();
1921 if (Idx % DstMinLen != 0) {
1922 report(msg: "Index must be a multiple of the destination vector's minimum "
1923 "vector length",
1924 MI);
1925 break;
1926 }
1927
1928 bool IsMixedFixedFromScalable =
1929 DstTy.isFixedVector() && SrcTy.isScalableVector();
1930 uint64_t SrcMinLen = SrcTy.getElementCount().getKnownMinValue();
1931 if (Idx >= SrcMinLen ||
1932 (!IsMixedFixedFromScalable && Idx + DstMinLen > SrcMinLen)) {
1933 report(msg: "Destination type and index must not cause extract to overrun the "
1934 "source vector",
1935 MI);
1936 break;
1937 }
1938
1939 break;
1940 }
1941 case TargetOpcode::G_SHUFFLE_VECTOR: {
1942 const MachineOperand &MaskOp = MI->getOperand(i: 3);
1943 if (!MaskOp.isShuffleMask()) {
1944 report(msg: "Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
1945 break;
1946 }
1947
1948 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1949 LLT Src0Ty = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1950 LLT Src1Ty = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
1951
1952 if (Src0Ty != Src1Ty)
1953 report(msg: "Source operands must be the same type", MI);
1954
1955 if (Src0Ty.getScalarType() != DstTy.getScalarType()) {
1956 report(msg: "G_SHUFFLE_VECTOR cannot change element type", MI);
1957 break;
1958 }
1959 if (!Src0Ty.isVector()) {
1960 report(msg: "G_SHUFFLE_VECTOR must have vector src", MI);
1961 break;
1962 }
1963 if (!DstTy.isVector()) {
1964 report(msg: "G_SHUFFLE_VECTOR must have vector dst", MI);
1965 break;
1966 }
1967
1968 // Don't check that all operands are vector because scalars are used in
1969 // place of 1 element vectors.
1970 int SrcNumElts = Src0Ty.getNumElements();
1971 int DstNumElts = DstTy.getNumElements();
1972
1973 ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
1974
1975 if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
1976 report(msg: "Wrong result type for shufflemask", MI);
1977
1978 for (int Idx : MaskIdxes) {
1979 if (Idx < 0)
1980 continue;
1981
1982 if (Idx >= 2 * SrcNumElts)
1983 report(msg: "Out of bounds shuffle index", MI);
1984 }
1985
1986 break;
1987 }
1988
1989 case TargetOpcode::G_SPLAT_VECTOR: {
1990 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
1991 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
1992
1993 if (!DstTy.isVector()) {
1994 report(msg: "Destination type must be a vector", MI);
1995 break;
1996 }
1997
1998 if (!SrcTy.isScalar() && !SrcTy.isPointer()) {
1999 report(msg: "Source type must be a scalar or pointer", MI);
2000 break;
2001 }
2002
2003 if (TypeSize::isKnownGT(LHS: DstTy.getElementType().getSizeInBits(),
2004 RHS: SrcTy.getSizeInBits())) {
2005 report(msg: "Element type of the destination must be the same size or smaller "
2006 "than the source type",
2007 MI);
2008 break;
2009 }
2010
2011 break;
2012 }
2013 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2014 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2015 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2016 LLT IdxTy = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
2017
2018 if (!DstTy.isScalar() && !DstTy.isPointer()) {
2019 report(msg: "Destination type must be a scalar or pointer", MI);
2020 break;
2021 }
2022
2023 if (!SrcTy.isVector()) {
2024 report(msg: "First source must be a vector", MI);
2025 break;
2026 }
2027
2028 auto TLI = MF->getSubtarget().getTargetLowering();
2029 if (IdxTy.getSizeInBits() != TLI->getVectorIdxWidth(DL: MF->getDataLayout())) {
2030 report(msg: "Index type must match VectorIdxTy", MI);
2031 break;
2032 }
2033
2034 break;
2035 }
2036 case TargetOpcode::G_INSERT_VECTOR_ELT: {
2037 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2038 LLT VecTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2039 LLT ScaTy = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
2040 LLT IdxTy = MRI->getType(Reg: MI->getOperand(i: 3).getReg());
2041
2042 if (!DstTy.isVector()) {
2043 report(msg: "Destination type must be a vector", MI);
2044 break;
2045 }
2046
2047 if (VecTy != DstTy) {
2048 report(msg: "Destination type and vector type must match", MI);
2049 break;
2050 }
2051
2052 if (!ScaTy.isScalar() && !ScaTy.isPointer()) {
2053 report(msg: "Inserted element must be a scalar or pointer", MI);
2054 break;
2055 }
2056
2057 auto TLI = MF->getSubtarget().getTargetLowering();
2058 if (IdxTy.getSizeInBits() != TLI->getVectorIdxWidth(DL: MF->getDataLayout())) {
2059 report(msg: "Index type must match VectorIdxTy", MI);
2060 break;
2061 }
2062
2063 break;
2064 }
2065 case TargetOpcode::G_DYN_STACKALLOC: {
2066 const MachineOperand &DstOp = MI->getOperand(i: 0);
2067 const MachineOperand &AllocOp = MI->getOperand(i: 1);
2068 const MachineOperand &AlignOp = MI->getOperand(i: 2);
2069
2070 if (!DstOp.isReg() || !MRI->getType(Reg: DstOp.getReg()).isPointer()) {
2071 report(msg: "dst operand 0 must be a pointer type", MI);
2072 break;
2073 }
2074
2075 if (!AllocOp.isReg() || !MRI->getType(Reg: AllocOp.getReg()).isScalar()) {
2076 report(msg: "src operand 1 must be a scalar reg type", MI);
2077 break;
2078 }
2079
2080 if (!AlignOp.isImm()) {
2081 report(msg: "src operand 2 must be an immediate type", MI);
2082 break;
2083 }
2084 break;
2085 }
2086 case TargetOpcode::G_MEMCPY_INLINE:
2087 case TargetOpcode::G_MEMCPY:
2088 case TargetOpcode::G_MEMMOVE: {
2089 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2090 if (MMOs.size() != 2) {
2091 report(msg: "memcpy/memmove must have 2 memory operands", MI);
2092 break;
2093 }
2094
2095 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
2096 (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
2097 report(msg: "wrong memory operand types", MI);
2098 break;
2099 }
2100
2101 if (MMOs[0]->getSize() != MMOs[1]->getSize())
2102 report(msg: "inconsistent memory operand sizes", MI);
2103
2104 LLT DstPtrTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2105 LLT SrcPtrTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2106
2107 if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
2108 report(msg: "memory instruction operand must be a pointer", MI);
2109 break;
2110 }
2111
2112 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2113 report(msg: "inconsistent store address space", MI);
2114 if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
2115 report(msg: "inconsistent load address space", MI);
2116
2117 if (Opc != TargetOpcode::G_MEMCPY_INLINE)
2118 if (!MI->getOperand(i: 3).isImm() || (MI->getOperand(i: 3).getImm() & ~1LL))
2119 report(msg: "'tail' flag (operand 3) must be an immediate 0 or 1", MI);
2120
2121 break;
2122 }
2123 case TargetOpcode::G_BZERO:
2124 case TargetOpcode::G_MEMSET:
2125 case TargetOpcode::G_MEMSET_INLINE: {
2126 ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
2127 std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset"
2128 : Opc == TargetOpcode::G_MEMSET_INLINE ? "memset_inline"
2129 : "bzero";
2130 if (MMOs.size() != 1) {
2131 report(Msg: Twine(Name, " must have 1 memory operand"), MI);
2132 break;
2133 }
2134
2135 if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
2136 report(Msg: Twine(Name, " memory operand must be a store"), MI);
2137 break;
2138 }
2139
2140 LLT DstPtrTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2141 if (!DstPtrTy.isPointer()) {
2142 report(Msg: Twine(Name, " operand must be a pointer"), MI);
2143 break;
2144 }
2145
2146 if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
2147 report(Msg: "inconsistent " + Twine(Name, " address space"), MI);
2148
2149 if (Opc != TargetOpcode::G_MEMSET_INLINE) {
2150 if (!MI->getOperand(i: MI->getNumOperands() - 1).isImm() ||
2151 (MI->getOperand(i: MI->getNumOperands() - 1).getImm() & ~1LL))
2152 report(msg: "'tail' flag (last operand) must be an immediate 0 or 1", MI);
2153 }
2154
2155 break;
2156 }
2157 case TargetOpcode::G_UBSANTRAP: {
2158 const MachineOperand &KindOp = MI->getOperand(i: 0);
2159 if (!MI->getOperand(i: 0).isImm()) {
2160 report(msg: "Crash kind must be an immediate", MO: &KindOp, MONum: 0);
2161 break;
2162 }
2163 int64_t Kind = MI->getOperand(i: 0).getImm();
2164 if (!isInt<8>(x: Kind))
2165 report(msg: "Crash kind must be 8 bit wide", MO: &KindOp, MONum: 0);
2166 break;
2167 }
2168 case TargetOpcode::G_VECREDUCE_SEQ_FADD:
2169 case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
2170 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2171 LLT Src1Ty = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2172 LLT Src2Ty = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
2173 if (!DstTy.isScalar())
2174 report(msg: "Vector reduction requires a scalar destination type", MI);
2175 if (!Src1Ty.isScalar())
2176 report(msg: "Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
2177 if (!Src2Ty.isVector())
2178 report(msg: "Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
2179 break;
2180 }
2181 case TargetOpcode::G_VECREDUCE_FADD:
2182 case TargetOpcode::G_VECREDUCE_FMUL:
2183 case TargetOpcode::G_VECREDUCE_FMAX:
2184 case TargetOpcode::G_VECREDUCE_FMIN:
2185 case TargetOpcode::G_VECREDUCE_FMAXIMUM:
2186 case TargetOpcode::G_VECREDUCE_FMINIMUM:
2187 case TargetOpcode::G_VECREDUCE_FMAXIMUMNUM:
2188 case TargetOpcode::G_VECREDUCE_FMINIMUMNUM:
2189 case TargetOpcode::G_VECREDUCE_ADD:
2190 case TargetOpcode::G_VECREDUCE_MUL:
2191 case TargetOpcode::G_VECREDUCE_AND:
2192 case TargetOpcode::G_VECREDUCE_OR:
2193 case TargetOpcode::G_VECREDUCE_XOR:
2194 case TargetOpcode::G_VECREDUCE_SMAX:
2195 case TargetOpcode::G_VECREDUCE_SMIN:
2196 case TargetOpcode::G_VECREDUCE_UMAX:
2197 case TargetOpcode::G_VECREDUCE_UMIN: {
2198 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2199 if (!DstTy.isScalar())
2200 report(msg: "Vector reduction requires a scalar destination type", MI);
2201 break;
2202 }
2203
2204 case TargetOpcode::G_SBFX:
2205 case TargetOpcode::G_UBFX: {
2206 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2207 if (DstTy.isVector()) {
2208 report(msg: "Bitfield extraction is not supported on vectors", MI);
2209 break;
2210 }
2211 break;
2212 }
2213 case TargetOpcode::G_SHL:
2214 case TargetOpcode::G_LSHR:
2215 case TargetOpcode::G_ASHR:
2216 case TargetOpcode::G_ROTR:
2217 case TargetOpcode::G_ROTL: {
2218 LLT Src1Ty = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2219 LLT Src2Ty = MRI->getType(Reg: MI->getOperand(i: 2).getReg());
2220 if (Src1Ty.isVector() != Src2Ty.isVector()) {
2221 report(msg: "Shifts and rotates require operands to be either all scalars or "
2222 "all vectors",
2223 MI);
2224 break;
2225 }
2226 break;
2227 }
2228 case TargetOpcode::G_LLROUND:
2229 case TargetOpcode::G_LROUND: {
2230 LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2231 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2232 if (!DstTy.isValid() || !SrcTy.isValid())
2233 break;
2234 if (SrcTy.isPointer() || DstTy.isPointer()) {
2235 StringRef Op = SrcTy.isPointer() ? "Source" : "Destination";
2236 report(Msg: Twine(Op, " operand must not be a pointer type"), MI);
2237 } else if (SrcTy.isScalar()) {
2238 verifyAllRegOpsScalar(MI: *MI, MRI: *MRI);
2239 break;
2240 } else if (SrcTy.isVector()) {
2241 verifyVectorElementMatch(Ty0: SrcTy, Ty1: DstTy, MI);
2242 break;
2243 }
2244 break;
2245 }
2246 case TargetOpcode::G_IS_FPCLASS: {
2247 LLT DestTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2248 LLT DestEltTy = DestTy.getScalarType();
2249 if (!DestEltTy.isScalar()) {
2250 report(msg: "Destination must be a scalar or vector of scalars", MI);
2251 break;
2252 }
2253 LLT SrcTy = MRI->getType(Reg: MI->getOperand(i: 1).getReg());
2254 LLT SrcEltTy = SrcTy.getScalarType();
2255 if (!SrcEltTy.isScalar()) {
2256 report(msg: "Source must be a scalar or vector of scalars", MI);
2257 break;
2258 }
2259 if (!verifyVectorElementMatch(Ty0: DestTy, Ty1: SrcTy, MI))
2260 break;
2261 const MachineOperand &TestMO = MI->getOperand(i: 2);
2262 if (!TestMO.isImm()) {
2263 report(msg: "floating-point class set (operand 2) must be an immediate", MI);
2264 break;
2265 }
2266 int64_t Test = TestMO.getImm();
2267 if (Test < 0 || Test > fcAllFlags) {
2268 report(msg: "Incorrect floating-point class set (operand 2)", MI);
2269 break;
2270 }
2271 break;
2272 }
2273 case TargetOpcode::G_PREFETCH: {
2274 const MachineOperand &AddrOp = MI->getOperand(i: 0);
2275 if (!AddrOp.isReg() || !MRI->getType(Reg: AddrOp.getReg()).isPointer()) {
2276 report(msg: "addr operand must be a pointer", MO: &AddrOp, MONum: 0);
2277 break;
2278 }
2279 const MachineOperand &RWOp = MI->getOperand(i: 1);
2280 if (!RWOp.isImm() || (uint64_t)RWOp.getImm() >= 2) {
2281 report(msg: "rw operand must be an immediate 0-1", MO: &RWOp, MONum: 1);
2282 break;
2283 }
2284 const MachineOperand &LocalityOp = MI->getOperand(i: 2);
2285 if (!LocalityOp.isImm() || (uint64_t)LocalityOp.getImm() >= 4) {
2286 report(msg: "locality operand must be an immediate 0-3", MO: &LocalityOp, MONum: 2);
2287 break;
2288 }
2289 const MachineOperand &CacheTypeOp = MI->getOperand(i: 3);
2290 if (!CacheTypeOp.isImm() || (uint64_t)CacheTypeOp.getImm() >= 2) {
2291 report(msg: "cache type operand must be an immediate 0-1", MO: &CacheTypeOp, MONum: 3);
2292 break;
2293 }
2294 break;
2295 }
2296 case TargetOpcode::G_ASSERT_ALIGN: {
2297 if (MI->getOperand(i: 2).getImm() < 1)
2298 report(msg: "alignment immediate must be >= 1", MI);
2299 break;
2300 }
2301 case TargetOpcode::G_CONSTANT_POOL: {
2302 if (!MI->getOperand(i: 1).isCPI())
2303 report(msg: "Src operand 1 must be a constant pool index", MI);
2304 if (!MRI->getType(Reg: MI->getOperand(i: 0).getReg()).isPointer())
2305 report(msg: "Dst operand 0 must be a pointer", MI);
2306 break;
2307 }
2308 case TargetOpcode::G_PTRAUTH_GLOBAL_VALUE: {
2309 const MachineOperand &AddrOp = MI->getOperand(i: 1);
2310 if (!AddrOp.isReg() || !MRI->getType(Reg: AddrOp.getReg()).isPointer())
2311 report(msg: "addr operand must be a pointer", MO: &AddrOp, MONum: 1);
2312 break;
2313 }
2314 case TargetOpcode::G_SMIN:
2315 case TargetOpcode::G_SMAX:
2316 case TargetOpcode::G_UMIN:
2317 case TargetOpcode::G_UMAX: {
2318 const LLT DstTy = MRI->getType(Reg: MI->getOperand(i: 0).getReg());
2319 if (DstTy.isPointerOrPointerVector())
2320 report(msg: "Generic smin/smax/umin/umax does not support pointer operands",
2321 MI);
2322 break;
2323 }
2324 default:
2325 break;
2326 }
2327}
2328
2329void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
2330 // A dead def is contradictory if the same instruction has a live def of the
2331 // same register. Overlapping dead and live defs of different registers
2332 // describe a partially used def.
2333 if (!LivePhysDefs.empty()) {
2334 for (unsigned MONum : DeadPhysDefOps) {
2335 const MachineOperand &MO = MI->getOperand(i: MONum);
2336 if (is_contained(Range&: LivePhysDefs, Element: MO.getReg().asMCReg())) {
2337 report(msg: "Dead def has a live def of the same register on the same "
2338 "instruction",
2339 MO: &MO, MONum);
2340 }
2341 }
2342 }
2343
2344 LivePhysDefs.clear();
2345 DeadPhysDefOps.clear();
2346}
2347
2348void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
2349 const MCInstrDesc &MCID = MI->getDesc();
2350 if (MI->getNumOperands() < MCID.getNumOperands()) {
2351 report(msg: "Too few operands", MI);
2352 OS << MCID.getNumOperands() << " operands expected, but "
2353 << MI->getNumOperands() << " given.\n";
2354 }
2355
2356 if (MI->getFlag(Flag: MachineInstr::NoConvergent) && !MCID.isConvergent())
2357 report(msg: "NoConvergent flag expected only on convergent instructions.", MI);
2358
2359 if (MI->isPHI()) {
2360 if (MF->getProperties().hasNoPHIs())
2361 report(msg: "Found PHI instruction with NoPHIs property set", MI);
2362
2363 if (FirstNonPHI)
2364 report(msg: "Found PHI instruction after non-PHI", MI);
2365 } else if (FirstNonPHI == nullptr)
2366 FirstNonPHI = MI;
2367
2368 // Check the tied operands.
2369 if (MI->isInlineAsm())
2370 verifyInlineAsm(MI);
2371
2372 // Check that unspillable terminators define a reg and have at most one use.
2373 if (TII->isUnspillableTerminator(MI)) {
2374 if (!MI->getOperand(i: 0).isReg() || !MI->getOperand(i: 0).isDef())
2375 report(msg: "Unspillable Terminator does not define a reg", MI);
2376 Register Def = MI->getOperand(i: 0).getReg();
2377 if (Def.isVirtual() && hasPHIs(MF: *MF) &&
2378 std::distance(first: MRI->use_nodbg_begin(RegNo: Def), last: MRI->use_nodbg_end()) > 1)
2379 report(msg: "Unspillable Terminator expected to have at most one use!", MI);
2380 }
2381
2382 // A fully-formed DBG_VALUE must have a location. Ignore partially formed
2383 // DBG_VALUEs: these are convenient to use in tests, but should never get
2384 // generated.
2385 if (MI->isDebugValue() && MI->getNumOperands() == 4)
2386 if (!MI->getDebugLoc())
2387 report(msg: "Missing DebugLoc for debug instruction", MI);
2388
2389 // Meta instructions should never be the subject of debug value tracking,
2390 // they don't create a value in the output program at all.
2391 if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
2392 report(msg: "Metadata instruction should not have a value tracking number", MI);
2393
2394 // Check the MachineMemOperands for basic consistency.
2395 for (MachineMemOperand *Op : MI->memoperands()) {
2396 if (Op->isLoad() && !MI->mayLoad())
2397 report(msg: "Missing mayLoad flag", MI);
2398 if (Op->isStore() && !MI->mayStore())
2399 report(msg: "Missing mayStore flag", MI);
2400 }
2401
2402 // Debug values must not have a slot index.
2403 // Other instructions must have one, unless they are inside a bundle.
2404 if (LiveInts) {
2405 bool mapped = !LiveInts->isNotInMIMap(Instr: *MI);
2406 if (MI->isDebugOrPseudoInstr()) {
2407 if (mapped)
2408 report(msg: "Debug instruction has a slot index", MI);
2409 } else if (MI->isInsideBundle()) {
2410 if (mapped)
2411 report(msg: "Instruction inside bundle has a slot index", MI);
2412 } else {
2413 if (!mapped)
2414 report(msg: "Missing slot index", MI);
2415 }
2416 }
2417
2418 unsigned Opc = MCID.getOpcode();
2419 if (isPreISelGenericOpcode(Opcode: Opc) || isPreISelGenericOptimizationHint(Opcode: Opc)) {
2420 verifyPreISelGenericInstruction(MI);
2421 return;
2422 }
2423
2424 StringRef ErrorInfo;
2425 if (!TII->verifyInstruction(MI: *MI, ErrInfo&: ErrorInfo))
2426 report(msg: ErrorInfo.data(), MI);
2427
2428 // Verify properties of various specific instruction types
2429 switch (MI->getOpcode()) {
2430 case TargetOpcode::COPY: {
2431 const MachineOperand &DstOp = MI->getOperand(i: 0);
2432 const MachineOperand &SrcOp = MI->getOperand(i: 1);
2433 const Register SrcReg = SrcOp.getReg();
2434 const Register DstReg = DstOp.getReg();
2435
2436 LLT DstTy = MRI->getType(Reg: DstReg);
2437 LLT SrcTy = MRI->getType(Reg: SrcReg);
2438 if (SrcTy.isValid() && DstTy.isValid()) {
2439 // If both types are valid, check that the types are the same.
2440 if (SrcTy != DstTy) {
2441 report(msg: "Copy Instruction is illegal with mismatching types", MI);
2442 OS << "Def = " << DstTy << ", Src = " << SrcTy << '\n';
2443 }
2444
2445 break;
2446 }
2447
2448 if (!SrcTy.isValid() && !DstTy.isValid())
2449 break;
2450
2451 // If we have only one valid type, this is likely a copy between a virtual
2452 // and physical register.
2453 TypeSize SrcSize = TypeSize::getZero();
2454 TypeSize DstSize = TypeSize::getZero();
2455 if (SrcReg.isPhysical() && DstTy.isValid()) {
2456 if (!hasPhysRegClassForType(TRI: *TRI, Reg: SrcReg, Ty: DstTy))
2457 SrcSize = TRI->getRegSizeInBits(Reg: SrcReg, MRI: *MRI);
2458 } else {
2459 SrcSize = TRI->getRegSizeInBits(Reg: SrcReg, MRI: *MRI);
2460 }
2461
2462 if (DstReg.isPhysical() && SrcTy.isValid()) {
2463 if (!hasPhysRegClassForType(TRI: *TRI, Reg: DstReg, Ty: SrcTy))
2464 DstSize = TRI->getRegSizeInBits(Reg: DstReg, MRI: *MRI);
2465 } else {
2466 DstSize = TRI->getRegSizeInBits(Reg: DstReg, MRI: *MRI);
2467 }
2468
2469 // The next two checks allow COPY between physical and virtual registers,
2470 // when the virtual register has a scalable size and the physical register
2471 // has a fixed size. These checks allow COPY between *potentially*
2472 // mismatched sizes. However, once RegisterBankSelection occurs,
2473 // MachineVerifier should be able to resolve a fixed size for the scalable
2474 // vector, and at that point this function will know for sure whether the
2475 // sizes are mismatched and correctly report a size mismatch.
2476 if (SrcReg.isPhysical() && DstReg.isVirtual() && DstSize.isScalable() &&
2477 !SrcSize.isScalable())
2478 break;
2479 if (SrcReg.isVirtual() && DstReg.isPhysical() && SrcSize.isScalable() &&
2480 !DstSize.isScalable())
2481 break;
2482
2483 if (SrcSize.isNonZero() && DstSize.isNonZero() && SrcSize != DstSize) {
2484 if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
2485 report(msg: "Copy Instruction is illegal with mismatching sizes", MI);
2486 OS << "Def Size = " << DstSize << ", Src Size = " << SrcSize << '\n';
2487 }
2488 }
2489 break;
2490 }
2491 case TargetOpcode::FREEZE:
2492 if (!MI->getOperand(i: 0).isReg() || !MI->getOperand(i: 1).isReg())
2493 report(msg: "FREEZE operands must be registers", MI);
2494 break;
2495 case TargetOpcode::COPY_LANEMASK: {
2496 const MachineOperand &DstOp = MI->getOperand(i: 0);
2497 const MachineOperand &SrcOp = MI->getOperand(i: 1);
2498 const MachineOperand &LaneMaskOp = MI->getOperand(i: 2);
2499 const Register SrcReg = SrcOp.getReg();
2500 const LaneBitmask LaneMask = LaneMaskOp.getLaneMask();
2501 LaneBitmask SrcMaxLaneMask = LaneBitmask::getAll();
2502
2503 if (DstOp.getSubReg())
2504 report(msg: "COPY_LANEMASK must not use a subregister index", MO: &DstOp, MONum: 0);
2505
2506 if (SrcOp.getSubReg())
2507 report(msg: "COPY_LANEMASK must not use a subregister index", MO: &SrcOp, MONum: 1);
2508
2509 if (LaneMask.none())
2510 report(msg: "COPY_LANEMASK must read at least one lane", MI);
2511
2512 if (SrcReg.isPhysical()) {
2513 const TargetRegisterClass *SrcRC = TRI->getMinimalPhysRegClass(Reg: SrcReg);
2514 if (SrcRC)
2515 SrcMaxLaneMask = SrcRC->getLaneMask();
2516 } else {
2517 SrcMaxLaneMask = MRI->getMaxLaneMaskForVReg(Reg: SrcReg);
2518 }
2519
2520 // COPY_LANEMASK should be used only for partial copy. For full
2521 // copy, one should strictly use the COPY instruction.
2522 if (SrcMaxLaneMask == LaneMask)
2523 report(msg: "COPY_LANEMASK cannot be used to do full copy", MI);
2524
2525 // If LaneMask is greater than the SrcMaxLaneMask, it implies
2526 // COPY_LANEMASK is attempting to read from the lanes that
2527 // don't exists in the source register.
2528 if (SrcMaxLaneMask < LaneMask)
2529 report(msg: "COPY_LANEMASK attempts to read from the lanes that "
2530 "don't exist in the source register",
2531 MI);
2532
2533 break;
2534 }
2535 case TargetOpcode::STATEPOINT: {
2536 StatepointOpers SO(MI);
2537 if (!MI->getOperand(i: SO.getIDPos()).isImm() ||
2538 !MI->getOperand(i: SO.getNBytesPos()).isImm() ||
2539 !MI->getOperand(i: SO.getNCallArgsPos()).isImm()) {
2540 report(msg: "meta operands to STATEPOINT not constant!", MI);
2541 break;
2542 }
2543
2544 auto VerifyStackMapConstant = [&](unsigned Offset) {
2545 if (Offset >= MI->getNumOperands()) {
2546 report(msg: "stack map constant to STATEPOINT is out of range!", MI);
2547 return;
2548 }
2549 if (!MI->getOperand(i: Offset - 1).isImm() ||
2550 MI->getOperand(i: Offset - 1).getImm() != StackMaps::ConstantOp ||
2551 !MI->getOperand(i: Offset).isImm())
2552 report(msg: "stack map constant to STATEPOINT not well formed!", MI);
2553 };
2554 VerifyStackMapConstant(SO.getCCIdx());
2555 VerifyStackMapConstant(SO.getFlagsIdx());
2556 VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
2557 VerifyStackMapConstant(SO.getNumGCPtrIdx());
2558 VerifyStackMapConstant(SO.getNumAllocaIdx());
2559 VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
2560
2561 // Verify that all explicit statepoint defs are tied to gc operands as
2562 // they are expected to be a relocation of gc operands.
2563 unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
2564 unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
2565 for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
2566 unsigned UseOpIdx;
2567 if (!MI->isRegTiedToUseOperand(DefOpIdx: Idx, UseOpIdx: &UseOpIdx)) {
2568 report(msg: "STATEPOINT defs expected to be tied", MI);
2569 break;
2570 }
2571 if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
2572 report(msg: "STATEPOINT def tied to non-gc operand", MI);
2573 break;
2574 }
2575 }
2576
2577 // TODO: verify we have properly encoded deopt arguments
2578 } break;
2579 case TargetOpcode::INSERT_SUBREG: {
2580 unsigned InsertedSize;
2581 if (unsigned SubIdx = MI->getOperand(i: 2).getSubReg())
2582 InsertedSize = TRI->getSubRegIdxSize(Idx: SubIdx);
2583 else
2584 InsertedSize = TRI->getRegSizeInBits(Reg: MI->getOperand(i: 2).getReg(), MRI: *MRI);
2585 unsigned SubRegSize = TRI->getSubRegIdxSize(Idx: MI->getOperand(i: 3).getImm());
2586 if (SubRegSize < InsertedSize) {
2587 report(msg: "INSERT_SUBREG expected inserted value to have equal or lesser "
2588 "size than the subreg it was inserted into", MI);
2589 break;
2590 }
2591 } break;
2592 case TargetOpcode::REG_SEQUENCE: {
2593 unsigned NumOps = MI->getNumOperands();
2594 if (!(NumOps & 1)) {
2595 report(msg: "Invalid number of operands for REG_SEQUENCE", MI);
2596 break;
2597 }
2598
2599 for (unsigned I = 1; I != NumOps; I += 2) {
2600 const MachineOperand &RegOp = MI->getOperand(i: I);
2601 const MachineOperand &SubRegOp = MI->getOperand(i: I + 1);
2602
2603 if (!RegOp.isReg())
2604 report(msg: "Invalid register operand for REG_SEQUENCE", MO: &RegOp, MONum: I);
2605
2606 if (!SubRegOp.isImm() || SubRegOp.getImm() == 0 ||
2607 SubRegOp.getImm() >= TRI->getNumSubRegIndices()) {
2608 report(msg: "Invalid subregister index operand for REG_SEQUENCE",
2609 MO: &SubRegOp, MONum: I + 1);
2610 }
2611 }
2612
2613 Register DstReg = MI->getOperand(i: 0).getReg();
2614 if (DstReg.isPhysical())
2615 report(msg: "REG_SEQUENCE does not support physical register results", MI);
2616
2617 if (MI->getOperand(i: 0).getSubReg())
2618 report(msg: "Invalid subreg result for REG_SEQUENCE", MI);
2619
2620 break;
2621 }
2622 }
2623}
2624
2625void
2626MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
2627 const MachineInstr *MI = MO->getParent();
2628 const MCInstrDesc &MCID = MI->getDesc();
2629 unsigned NumDefs = MCID.getNumDefs();
2630 if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
2631 NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
2632
2633 // The first MCID.NumDefs operands must be explicit register defines
2634 if (MONum < NumDefs) {
2635 const MCOperandInfo &MCOI = MCID.operands()[MONum];
2636 if (!MO->isReg())
2637 report(msg: "Explicit definition must be a register", MO, MONum);
2638 else if (!MO->isDef() && !MCOI.isOptionalDef())
2639 report(msg: "Explicit definition marked as use", MO, MONum);
2640 else if (MO->isImplicit())
2641 report(msg: "Explicit definition marked as implicit", MO, MONum);
2642 } else if (MONum < MCID.getNumOperands()) {
2643 const MCOperandInfo &MCOI = MCID.operands()[MONum];
2644 // Don't check if it's the last operand in a variadic instruction. See,
2645 // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
2646 bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
2647 if (!IsOptional) {
2648 if (MO->isReg()) {
2649 if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
2650 report(msg: "Explicit operand marked as def", MO, MONum);
2651 if (MO->isImplicit())
2652 report(msg: "Explicit operand marked as implicit", MO, MONum);
2653 }
2654
2655 // Check that an instruction has register operands only as expected.
2656 if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
2657 !MO->isReg() && !MO->isFI())
2658 report(msg: "Expected a register operand.", MO, MONum);
2659 if (MO->isReg()) {
2660 if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
2661 (MCOI.OperandType == MCOI::OPERAND_PCREL &&
2662 !TII->isPCRelRegisterOperandLegal(MI: *MI, OpIdx: MONum)))
2663 report(msg: "Expected a non-register operand.", MO, MONum);
2664 }
2665 }
2666
2667 int TiedTo = MCID.getOperandConstraint(OpNum: MONum, Constraint: MCOI::TIED_TO);
2668 if (TiedTo != -1) {
2669 if (!MO->isReg())
2670 report(msg: "Tied use must be a register", MO, MONum);
2671 else if (!MO->isTied())
2672 report(msg: "Operand should be tied", MO, MONum);
2673 else if (unsigned(TiedTo) != MI->findTiedOperandIdx(OpIdx: MONum))
2674 report(msg: "Tied def doesn't match MCInstrDesc", MO, MONum);
2675 else if (MO->getReg().isPhysical()) {
2676 const MachineOperand &MOTied = MI->getOperand(i: TiedTo);
2677 if (!MOTied.isReg())
2678 report(msg: "Tied counterpart must be a register", MO: &MOTied, MONum: TiedTo);
2679 else if (MOTied.getReg().isPhysical() &&
2680 MO->getReg() != MOTied.getReg())
2681 report(msg: "Tied physical registers must match.", MO: &MOTied, MONum: TiedTo);
2682 }
2683 } else if (MO->isReg() && MO->isTied())
2684 report(msg: "Explicit operand should not be tied", MO, MONum);
2685 } else if (!MI->isVariadic()) {
2686 // ARM adds %reg0 operands to indicate predicates. We'll allow that.
2687 if (!MO->isValidExcessOperand())
2688 report(msg: "Extra explicit operand on non-variadic instruction", MO, MONum);
2689 }
2690
2691 // Verify earlyClobber def operand
2692 if (MCID.getOperandConstraint(OpNum: MONum, Constraint: MCOI::EARLY_CLOBBER) != -1) {
2693 if (!MO->isReg())
2694 report(msg: "Early clobber must be a register", MI);
2695 if (!MO->isEarlyClobber())
2696 report(msg: "Missing earlyClobber flag", MI);
2697 }
2698
2699 switch (MO->getType()) {
2700 case MachineOperand::MO_Register: {
2701 // Verify debug flag on debug instructions. Check this first because reg0
2702 // indicates an undefined debug value.
2703 if (MI->isDebugInstr() && MO->isUse()) {
2704 if (!MO->isDebug())
2705 report(msg: "Register operand must be marked debug", MO, MONum);
2706 } else if (MO->isDebug()) {
2707 report(msg: "Register operand must not be marked debug", MO, MONum);
2708 }
2709
2710 const Register Reg = MO->getReg();
2711 if (!Reg)
2712 return;
2713 if (MRI->tracksLiveness() && !MI->isDebugInstr())
2714 checkLiveness(MO, MONum);
2715
2716 if (MO->isDef() && MO->isUndef() && !MO->getSubReg() &&
2717 MO->getReg().isVirtual()) // TODO: Apply to physregs too
2718 report(msg: "Undef virtual register def operands require a subregister", MO, MONum);
2719
2720 if (MO->isKill() && Reg.isVirtual())
2721 report(msg: "Kill flag on virtual register", MO, MONum);
2722
2723 // Verify the consistency of tied operands.
2724 if (MO->isTied()) {
2725 unsigned OtherIdx = MI->findTiedOperandIdx(OpIdx: MONum);
2726 const MachineOperand &OtherMO = MI->getOperand(i: OtherIdx);
2727 if (!OtherMO.isReg())
2728 report(msg: "Must be tied to a register", MO, MONum);
2729 if (!OtherMO.isTied())
2730 report(msg: "Missing tie flags on tied operand", MO, MONum);
2731 if (MI->findTiedOperandIdx(OpIdx: OtherIdx) != MONum)
2732 report(msg: "Inconsistent tie links", MO, MONum);
2733
2734 // See IsUndef in MachineOperand.h.
2735 if (MO->isUse() && MO->isUndef() && Reg.isVirtual() &&
2736 OtherMO.getReg() != Reg &&
2737 any_of(Range: MI->all_uses(), P: [&](const MachineOperand &Other) {
2738 return &Other != MO && Other.isUndef() && Other.getReg() == Reg &&
2739 Other.getSubReg() == MO->getSubReg();
2740 }))
2741 report(msg: "Tied undef use shares a virtual register with another read", MO,
2742 MONum);
2743
2744 if (MONum < MCID.getNumDefs()) {
2745 if (OtherIdx < MCID.getNumOperands()) {
2746 if (-1 == MCID.getOperandConstraint(OpNum: OtherIdx, Constraint: MCOI::TIED_TO))
2747 report(msg: "Explicit def tied to explicit use without tie constraint",
2748 MO, MONum);
2749 } else {
2750 if (!OtherMO.isImplicit())
2751 report(msg: "Explicit def should be tied to implicit use", MO, MONum);
2752 }
2753 }
2754 }
2755
2756 // Verify two-address constraints after the twoaddressinstruction pass.
2757 // Both twoaddressinstruction pass and phi-node-elimination pass call
2758 // MRI->leaveSSA() to set MF as not IsSSA, we should do the verification
2759 // after twoaddressinstruction pass not after phi-node-elimination pass. So
2760 // we shouldn't use the IsSSA as the condition, we should based on
2761 // TiedOpsRewritten property to verify two-address constraints, this
2762 // property will be set in twoaddressinstruction pass.
2763 unsigned DefIdx;
2764 if (MF->getProperties().hasTiedOpsRewritten() && MO->isUse() &&
2765 MI->isRegTiedToDefOperand(UseOpIdx: MONum, DefOpIdx: &DefIdx) &&
2766 Reg != MI->getOperand(i: DefIdx).getReg())
2767 report(msg: "Two-address instruction operands must be identical", MO, MONum);
2768
2769 // Check register classes.
2770 unsigned SubIdx = MO->getSubReg();
2771
2772 if (Reg.isPhysical()) {
2773 if (SubIdx) {
2774 report(msg: "Illegal subregister index for physical register", MO, MONum);
2775 return;
2776 }
2777 if (MONum < MCID.getNumOperands()) {
2778 if (const TargetRegisterClass *DRC = TII->getRegClass(MCID, OpNum: MONum)) {
2779 if (!DRC->contains(Reg)) {
2780 report(msg: "Illegal physical register for instruction", MO, MONum);
2781 OS << printReg(Reg, TRI) << " is not a "
2782 << TRI->getRegClassName(Class: DRC) << " register.\n";
2783 }
2784 }
2785 }
2786 if (MO->isRenamable()) {
2787 if (MRI->isReserved(PhysReg: Reg)) {
2788 report(msg: "isRenamable set on reserved register", MO, MONum);
2789 return;
2790 }
2791 }
2792 } else {
2793 // Virtual register.
2794 const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
2795 if (!RC) {
2796 // This is a generic virtual register.
2797
2798 // Do not allow undef uses for generic virtual registers. This ensures
2799 // getVRegDef can never fail and return null on a generic register.
2800 //
2801 // FIXME: This restriction should probably be broadened to all SSA
2802 // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
2803 // run on the SSA function just before phi elimination.
2804 if (MO->isUndef())
2805 report(msg: "Generic virtual register use cannot be undef", MO, MONum);
2806
2807 // Debug value instruction is permitted to use undefined vregs.
2808 // This is a performance measure to skip the overhead of immediately
2809 // pruning unused debug operands. The final undef substitution occurs
2810 // when debug values are allocated in LDVImpl::handleDebugValue, so
2811 // these verifications always apply after this pass.
2812 if (isFunctionTracksDebugUserValues || !MO->isUse() ||
2813 !MI->isDebugValue() || !MRI->def_empty(RegNo: Reg)) {
2814 // If we're post-Select, we can't have gvregs anymore.
2815 if (isFunctionSelected) {
2816 report(msg: "Generic virtual register invalid in a Selected function",
2817 MO, MONum);
2818 return;
2819 }
2820
2821 // The gvreg must have a type and it must not have a SubIdx.
2822 LLT Ty = MRI->getType(Reg);
2823 if (!Ty.isValid()) {
2824 report(msg: "Generic virtual register must have a valid type", MO,
2825 MONum);
2826 return;
2827 }
2828
2829 const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
2830 const RegisterBankInfo *RBI = MF->getSubtarget().getRegBankInfo();
2831
2832 // If we're post-RegBankSelect, the gvreg must have a bank.
2833 if (!RegBank && isFunctionRegBankSelected) {
2834 report(msg: "Generic virtual register must have a bank in a "
2835 "RegBankSelected function",
2836 MO, MONum);
2837 return;
2838 }
2839
2840 // Make sure the register fits into its register bank if any.
2841 if (RegBank && Ty.isValid() && !Ty.isScalableVector() &&
2842 RBI->getMaximumSize(RegBankID: RegBank->getID()) < Ty.getSizeInBits()) {
2843 report(msg: "Register bank is too small for virtual register", MO,
2844 MONum);
2845 OS << "Register bank " << RegBank->getName() << " too small("
2846 << RBI->getMaximumSize(RegBankID: RegBank->getID()) << ") to fit "
2847 << Ty.getSizeInBits() << "-bits\n";
2848 return;
2849 }
2850 }
2851
2852 if (SubIdx) {
2853 report(msg: "Generic virtual register does not allow subregister index", MO,
2854 MONum);
2855 return;
2856 }
2857
2858 // If this is a target specific instruction and this operand
2859 // has register class constraint, the virtual register must
2860 // comply to it.
2861 if (!isPreISelGenericOpcode(Opcode: MCID.getOpcode()) &&
2862 MONum < MCID.getNumOperands() && TII->getRegClass(MCID, OpNum: MONum)) {
2863 report(msg: "Virtual register does not match instruction constraint", MO,
2864 MONum);
2865 OS << "Expect register class "
2866 << TRI->getRegClassName(Class: TII->getRegClass(MCID, OpNum: MONum))
2867 << " but got nothing\n";
2868 return;
2869 }
2870
2871 break;
2872 }
2873 // Validate that SubIdx can be applied to the virtual register.
2874 if (!TRI->isSubRegValidForRegClass(RC, Idx: SubIdx)) {
2875 report(msg: "Invalid subregister index for virtual register", MO, MONum);
2876 OS << "Register class " << TRI->getRegClassName(Class: RC)
2877 << " does not support subreg index "
2878 << TRI->getSubRegIndexName(SubIdx) << '\n';
2879 return;
2880 }
2881 if (MONum >= MCID.getNumOperands())
2882 break;
2883 const TargetRegisterClass *DRC = TII->getRegClass(MCID, OpNum: MONum);
2884 if (!DRC)
2885 break;
2886
2887 // If SubIdx is used, verify that RC with SubIdx can be used for an
2888 // operand of class DRC. This is valid if for every register in RC, the
2889 // register obtained by applying SubIdx to it is in DRC.
2890 if (SubIdx && TRI->getMatchingSuperRegClass(A: RC, B: DRC, Idx: SubIdx) != RC) {
2891 report(msg: "Illegal virtual register for instruction", MO, MONum);
2892 OS << TRI->getRegClassName(Class: RC) << "." << TRI->getSubRegIndexName(SubIdx)
2893 << " cannot be used for " << TRI->getRegClassName(Class: DRC)
2894 << " operands.";
2895 }
2896
2897 // If no SubIdx is used, verify that RC is a sub-class of DRC.
2898 if (!SubIdx && !RC->hasSuperClassEq(RC: DRC)) {
2899 report(msg: "Illegal virtual register for instruction", MO, MONum);
2900 OS << "Expected a " << TRI->getRegClassName(Class: DRC)
2901 << " register, but got a " << TRI->getRegClassName(Class: RC)
2902 << " register\n";
2903 }
2904 }
2905 break;
2906 }
2907
2908 case MachineOperand::MO_RegisterMask:
2909 regMasks.push_back(Elt: MO->getRegMask());
2910 break;
2911
2912 case MachineOperand::MO_MachineBasicBlock:
2913 if (MI->isPHI() && !MO->getMBB()->isSuccessor(MBB: MI->getParent()))
2914 report(msg: "PHI operand is not in the CFG", MO, MONum);
2915 break;
2916
2917 case MachineOperand::MO_FrameIndex:
2918 if (LiveStks && LiveStks->hasInterval(Slot: MO->getIndex()) &&
2919 LiveInts && !LiveInts->isNotInMIMap(Instr: *MI)) {
2920 int FI = MO->getIndex();
2921 LiveInterval &LI = LiveStks->getInterval(Slot: FI);
2922 SlotIndex Idx = LiveInts->getInstructionIndex(Instr: *MI);
2923
2924 bool MayStore = MI->mayStore();
2925 bool MayLoad = MI->mayLoad();
2926 // For a memory-to-memory move, we need to check if the frame
2927 // index is used for storing or loading, by inspecting the
2928 // memory operands.
2929 if (MayStore && MayLoad) {
2930 for (const MachineMemOperand *MMO : MI->memoperands()) {
2931 const auto *Value = dyn_cast_if_present<FixedStackPseudoSourceValue>(
2932 Val: MMO->getPseudoValue());
2933 if (!Value || Value->getFrameIndex() != FI)
2934 continue;
2935
2936 if (MMO->isStore())
2937 MayLoad = false;
2938 else
2939 MayStore = false;
2940 break;
2941 }
2942 if (MayLoad == MayStore)
2943 report(msg: "Missing fixed stack memoperand.", MI);
2944 }
2945 if (MayLoad && !LI.liveAt(index: Idx.getRegSlot(EC: true))) {
2946 report(msg: "Instruction loads from dead spill slot", MO, MONum);
2947 OS << "Live stack: " << LI << '\n';
2948 }
2949 if (MayStore && !LI.liveAt(index: Idx.getRegSlot())) {
2950 report(msg: "Instruction stores to dead spill slot", MO, MONum);
2951 OS << "Live stack: " << LI << '\n';
2952 }
2953 }
2954 break;
2955
2956 case MachineOperand::MO_CFIIndex:
2957 if (MO->getCFIIndex() >= MF->getFrameInstructions().size())
2958 report(msg: "CFI instruction has invalid index", MO, MONum);
2959 break;
2960
2961 default:
2962 break;
2963 }
2964}
2965
2966void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
2967 unsigned MONum, SlotIndex UseIdx,
2968 const LiveRange &LR,
2969 VirtRegOrUnit VRegOrUnit,
2970 LaneBitmask LaneMask) {
2971 const MachineInstr *MI = MO->getParent();
2972
2973 if (!LR.verify()) {
2974 report(msg: "invalid live range", MO, MONum);
2975 report_context_liverange(LR);
2976 report_context_vreg_regunit(VRegOrUnit);
2977 report_context(Pos: UseIdx);
2978 return;
2979 }
2980
2981 LiveQueryResult LRQ = LR.Query(Idx: UseIdx);
2982 bool HasValue = LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut());
2983 // Check if we have a segment at the use, note however that we only need one
2984 // live subregister range, the others may be dead.
2985 if (!HasValue && LaneMask.none()) {
2986 report(msg: "No live segment at use", MO, MONum);
2987 report_context_liverange(LR);
2988 report_context_vreg_regunit(VRegOrUnit);
2989 report_context(Pos: UseIdx);
2990 }
2991 if (MO->isKill() && !LRQ.isKill()) {
2992 report(msg: "Live range continues after kill flag", MO, MONum);
2993 report_context_liverange(LR);
2994 report_context_vreg_regunit(VRegOrUnit);
2995 if (LaneMask.any())
2996 report_context_lanemask(LaneMask);
2997 report_context(Pos: UseIdx);
2998 }
2999}
3000
3001void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
3002 unsigned MONum, SlotIndex DefIdx,
3003 const LiveRange &LR,
3004 VirtRegOrUnit VRegOrUnit,
3005 bool SubRangeCheck,
3006 LaneBitmask LaneMask) {
3007 if (!LR.verify()) {
3008 report(msg: "invalid live range", MO, MONum);
3009 report_context_liverange(LR);
3010 report_context_vreg_regunit(VRegOrUnit);
3011 if (LaneMask.any())
3012 report_context_lanemask(LaneMask);
3013 report_context(Pos: DefIdx);
3014 }
3015
3016 if (const VNInfo *VNI = LR.getVNInfoAt(Idx: DefIdx)) {
3017 // The LR can correspond to the whole reg and its def slot is not obliged
3018 // to be the same as the MO' def slot. E.g. when we check here "normal"
3019 // subreg MO but there is other EC subreg MO in the same instruction so the
3020 // whole reg has EC def slot and differs from the currently checked MO' def
3021 // slot. For example:
3022 // %0 [16e,32r:0) 0@16e L..3 [16e,32r:0) 0@16e L..C [16r,32r:0) 0@16r
3023 // Check that there is an early-clobber def of the same superregister
3024 // somewhere is performed in visitMachineFunctionAfter()
3025 if (((SubRangeCheck || MO->getSubReg() == 0) && VNI->def != DefIdx) ||
3026 !SlotIndex::isSameInstr(A: VNI->def, B: DefIdx) ||
3027 (VNI->def != DefIdx &&
3028 (!VNI->def.isEarlyClobber() || !DefIdx.isRegister()))) {
3029 report(msg: "Inconsistent valno->def", MO, MONum);
3030 report_context_liverange(LR);
3031 report_context_vreg_regunit(VRegOrUnit);
3032 if (LaneMask.any())
3033 report_context_lanemask(LaneMask);
3034 report_context(VNI: *VNI);
3035 report_context(Pos: DefIdx);
3036 }
3037 } else {
3038 report(msg: "No live segment at def", MO, MONum);
3039 report_context_liverange(LR);
3040 report_context_vreg_regunit(VRegOrUnit);
3041 if (LaneMask.any())
3042 report_context_lanemask(LaneMask);
3043 report_context(Pos: DefIdx);
3044 }
3045 // Check that, if the dead def flag is present, LiveInts agree.
3046 if (MO->isDead()) {
3047 LiveQueryResult LRQ = LR.Query(Idx: DefIdx);
3048 if (!LRQ.isDeadDef()) {
3049 assert(VRegOrUnit.isVirtualReg() && "Expecting a virtual register.");
3050 // A dead subreg def only tells us that the specific subreg is dead. There
3051 // could be other non-dead defs of other subregs, or we could have other
3052 // parts of the register being live through the instruction. So unless we
3053 // are checking liveness for a subrange it is ok for the live range to
3054 // continue, given that we have a dead def of a subregister.
3055 if (SubRangeCheck || MO->getSubReg() == 0) {
3056 report(msg: "Live range continues after dead def flag", MO, MONum);
3057 report_context_liverange(LR);
3058 report_context_vreg_regunit(VRegOrUnit);
3059 if (LaneMask.any())
3060 report_context_lanemask(LaneMask);
3061 }
3062 }
3063 }
3064}
3065
3066void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
3067 const MachineInstr *MI = MO->getParent();
3068 const Register Reg = MO->getReg();
3069 const unsigned SubRegIdx = MO->getSubReg();
3070
3071 const LiveInterval *LI = nullptr;
3072 if (LiveInts && Reg.isVirtual()) {
3073 if (LiveInts->hasInterval(Reg)) {
3074 LI = &LiveInts->getInterval(Reg);
3075 if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
3076 !LI->hasSubRanges() && MRI->shouldTrackSubRegLiveness(VReg: Reg))
3077 report(msg: "Live interval for subreg operand has no subranges", MO, MONum);
3078 } else {
3079 report(msg: "Virtual register has no live interval", MO, MONum);
3080 }
3081 }
3082
3083 // Both use and def operands can read a register.
3084 if (MO->readsReg()) {
3085 if (MO->isKill() && Reg.isPhysical())
3086 addRegWithSubRegs(RV&: regsKilled, Reg);
3087
3088 // Check LiveInts liveness and kill.
3089 if (LiveInts && !LiveInts->isNotInMIMap(Instr: *MI)) {
3090 SlotIndex UseIdx;
3091 if (MI->isPHI()) {
3092 // PHI use occurs on the edge, so check for live out here instead.
3093 UseIdx = LiveInts->getMBBEndIdx(
3094 mbb: MI->getOperand(i: MONum + 1).getMBB()).getPrevSlot();
3095 } else {
3096 UseIdx = LiveInts->getInstructionIndex(Instr: *MI);
3097 }
3098 // Check the cached regunit intervals.
3099 if (Reg.isPhysical() && !isReserved(Reg)) {
3100 for (MCRegUnit Unit : TRI->regunits(Reg: Reg.asMCReg())) {
3101 if (MRI->isReservedRegUnit(Unit))
3102 continue;
3103 if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
3104 checkLivenessAtUse(MO, MONum, UseIdx, LR: *LR, VRegOrUnit: VirtRegOrUnit(Unit));
3105 }
3106 }
3107
3108 if (Reg.isVirtual()) {
3109 // This is a virtual register interval.
3110 checkLivenessAtUse(MO, MONum, UseIdx, LR: *LI, VRegOrUnit: VirtRegOrUnit(Reg));
3111
3112 if (LI->hasSubRanges() && !MO->isDef()) {
3113 LaneBitmask MOMask = SubRegIdx != 0
3114 ? TRI->getSubRegIndexLaneMask(SubIdx: SubRegIdx)
3115 : MRI->getMaxLaneMaskForVReg(Reg);
3116 LaneBitmask LiveInMask;
3117 for (const LiveInterval::SubRange &SR : LI->subranges()) {
3118 if ((MOMask & SR.LaneMask).none())
3119 continue;
3120 checkLivenessAtUse(MO, MONum, UseIdx, LR: SR, VRegOrUnit: VirtRegOrUnit(Reg),
3121 LaneMask: SR.LaneMask);
3122 LiveQueryResult LRQ = SR.Query(Idx: UseIdx);
3123 if (LRQ.valueIn() || (MI->isPHI() && LRQ.valueOut()))
3124 LiveInMask |= SR.LaneMask;
3125 }
3126 // At least parts of the register has to be live at the use.
3127 if ((LiveInMask & MOMask).none()) {
3128 report(msg: "No live subrange at use", MO, MONum);
3129 report_context(LI: *LI);
3130 report_context(Pos: UseIdx);
3131 }
3132 // For PHIs all lanes should be live
3133 if (MI->isPHI() && LiveInMask != MOMask) {
3134 report(msg: "Not all lanes of PHI source live at use", MO, MONum);
3135 report_context(LI: *LI);
3136 report_context(Pos: UseIdx);
3137 }
3138 }
3139 }
3140 }
3141
3142 // Use of a dead register.
3143 if (!regsLive.count(V: Reg)) {
3144 if (Reg.isPhysical()) {
3145 // Reserved registers may be used even when 'dead'.
3146 bool Bad = !isReserved(Reg);
3147 // We are fine if just any subregister has a defined value.
3148 if (Bad) {
3149
3150 for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
3151 if (regsLive.count(V: SubReg)) {
3152 Bad = false;
3153 break;
3154 }
3155 }
3156 }
3157 // If there is an additional implicit-use of a super register we stop
3158 // here. By definition we are fine if the super register is not
3159 // (completely) dead, if the complete super register is dead we will
3160 // get a report for its operand.
3161 if (Bad) {
3162 for (const MachineOperand &MOP : MI->uses()) {
3163 if (!MOP.isReg() || !MOP.isImplicit())
3164 continue;
3165
3166 if (!MOP.getReg().isPhysical())
3167 continue;
3168
3169 if (MOP.getReg() != Reg &&
3170 all_of(Range: TRI->regunits(Reg), P: [&](const MCRegUnit RegUnit) {
3171 return llvm::is_contained(Range: TRI->regunits(Reg: MOP.getReg()),
3172 Element: RegUnit);
3173 }))
3174 Bad = false;
3175 }
3176 }
3177 if (Bad)
3178 report(msg: "Using an undefined physical register", MO, MONum);
3179 } else if (MRI->def_empty(RegNo: Reg)) {
3180 report(msg: "Reading virtual register without a def", MO, MONum);
3181 } else {
3182 // We don't know which virtual registers are live in, so keep track of
3183 // vregs that must be live in. PHI instructions are handled separately.
3184 if (!MI->isPHI())
3185 MBBInfoMap[MI->getParent()].vregsLiveIn.insert(
3186 KV: std::make_pair(x: Reg, y&: MI));
3187 }
3188 }
3189 }
3190
3191 if (MO->isDef()) {
3192 // Register defined.
3193 // TODO: verify that earlyclobber ops are not used.
3194 if (MO->isDead())
3195 addRegWithSubRegs(RV&: regsDead, Reg);
3196 else
3197 addRegWithSubRegs(RV&: regsDefined, Reg);
3198
3199 if (Reg.isPhysical()) {
3200 if (MO->isDead())
3201 DeadPhysDefOps.push_back(Elt: MONum);
3202 else
3203 LivePhysDefs.push_back(Elt: Reg.asMCReg());
3204 }
3205
3206 // Verify SSA form.
3207 if (MRI->isSSA() && Reg.isVirtual()) {
3208 if (!MRI->hasOneDef(RegNo: Reg))
3209 report(msg: "Multiple virtual register defs in SSA form", MO, MONum);
3210 if (MO->getSubReg())
3211 report(msg: "Subreg def in SSA form", MO, MONum);
3212 }
3213
3214 // Check LiveInts for a live segment, but only for virtual registers.
3215 if (LiveInts && !LiveInts->isNotInMIMap(Instr: *MI)) {
3216 SlotIndex DefIdx = LiveInts->getInstructionIndex(Instr: *MI);
3217 DefIdx = DefIdx.getRegSlot(EC: MO->isEarlyClobber());
3218
3219 if (Reg.isVirtual()) {
3220 checkLivenessAtDef(MO, MONum, DefIdx, LR: *LI, VRegOrUnit: VirtRegOrUnit(Reg));
3221
3222 if (LI->hasSubRanges()) {
3223 LaneBitmask MOMask = SubRegIdx != 0
3224 ? TRI->getSubRegIndexLaneMask(SubIdx: SubRegIdx)
3225 : MRI->getMaxLaneMaskForVReg(Reg);
3226 for (const LiveInterval::SubRange &SR : LI->subranges()) {
3227 if ((SR.LaneMask & MOMask).none())
3228 continue;
3229 checkLivenessAtDef(MO, MONum, DefIdx, LR: SR, VRegOrUnit: VirtRegOrUnit(Reg), SubRangeCheck: true,
3230 LaneMask: SR.LaneMask);
3231 }
3232 }
3233 }
3234 }
3235 }
3236}
3237
3238// This function gets called after visiting all instructions in a bundle. The
3239// argument points to the bundle header.
3240// Normal stand-alone instructions are also considered 'bundles', and this
3241// function is called for all of them.
3242void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
3243 set_subtract(S1&: regsLive, S2: regsKilled); regsKilled.clear();
3244 // Kill any masked registers.
3245 while (!regMasks.empty()) {
3246 const uint32_t *Mask = regMasks.pop_back_val();
3247 for (Register Reg : regsLive)
3248 if (Reg.isPhysical() &&
3249 MachineOperand::clobbersPhysReg(RegMask: Mask, PhysReg: Reg.asMCReg()))
3250 regsDead.push_back(Elt: Reg);
3251 }
3252 set_subtract(S1&: regsLive, S2: regsDead); regsDead.clear();
3253 set_union(S1&: regsLive, S2: regsDefined); regsDefined.clear();
3254}
3255
3256void
3257MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
3258 MBBInfoMap[MBB].regsLiveOut = regsLive;
3259 regsLive.clear();
3260
3261 if (Indexes) {
3262 SlotIndex stop = Indexes->getMBBEndIdx(mbb: MBB);
3263 if (!(stop > lastIndex)) {
3264 report(msg: "Block ends before last instruction index", MBB);
3265 OS << "Block ends at " << stop << " last instruction was at " << lastIndex
3266 << '\n';
3267 }
3268 lastIndex = stop;
3269 }
3270}
3271
3272namespace {
3273// This implements a set of registers that serves as a filter: can filter other
3274// sets by passing through elements not in the filter and blocking those that
3275// are. Any filter implicitly includes the full set of physical registers upon
3276// creation, thus filtering them all out. The filter itself as a set only grows,
3277// and needs to be as efficient as possible.
3278struct VRegFilter {
3279 // Add elements to the filter itself. \pre Input set \p FromRegSet must have
3280 // no duplicates. Both virtual and physical registers are fine.
3281 template <typename RegSetT> void add(const RegSetT &FromRegSet) {
3282 SmallVector<Register, 0> VRegsBuffer;
3283 filterAndAdd(FromRegSet, VRegsBuffer);
3284 }
3285 // Filter \p FromRegSet through the filter and append passed elements into \p
3286 // ToVRegs. All elements appended are then added to the filter itself.
3287 // \returns true if anything changed.
3288 template <typename RegSetT>
3289 bool filterAndAdd(const RegSetT &FromRegSet,
3290 SmallVectorImpl<Register> &ToVRegs) {
3291 unsigned SparseUniverse = Sparse.size();
3292 unsigned NewSparseUniverse = SparseUniverse;
3293 unsigned NewDenseSize = Dense.size();
3294 size_t Begin = ToVRegs.size();
3295 for (Register Reg : FromRegSet) {
3296 if (!Reg.isVirtual())
3297 continue;
3298 unsigned Index = Reg.virtRegIndex();
3299 if (Index < SparseUniverseMax) {
3300 if (Index < SparseUniverse && Sparse.test(Idx: Index))
3301 continue;
3302 NewSparseUniverse = std::max(a: NewSparseUniverse, b: Index + 1);
3303 } else {
3304 if (Dense.count(V: Reg))
3305 continue;
3306 ++NewDenseSize;
3307 }
3308 ToVRegs.push_back(Elt: Reg);
3309 }
3310 size_t End = ToVRegs.size();
3311 if (Begin == End)
3312 return false;
3313 // Reserving space in sets once performs better than doing so continuously
3314 // and pays easily for double look-ups (even in Dense with SparseUniverseMax
3315 // tuned all the way down) and double iteration (the second one is over a
3316 // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
3317 Sparse.resize(N: NewSparseUniverse);
3318 Dense.reserve(Size: NewDenseSize);
3319 for (unsigned I = Begin; I < End; ++I) {
3320 Register Reg = ToVRegs[I];
3321 unsigned Index = Reg.virtRegIndex();
3322 if (Index < SparseUniverseMax)
3323 Sparse.set(Index);
3324 else
3325 Dense.insert(V: Reg);
3326 }
3327 return true;
3328 }
3329
3330private:
3331 static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
3332 // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyond
3333 // are tracked by Dense. The only purpose of the threshold and the Dense set
3334 // is to have a reasonably growing memory usage in pathological cases (large
3335 // number of very sparse VRegFilter instances live at the same time). In
3336 // practice even in the worst-by-execution time cases having all elements
3337 // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
3338 // space efficient than if tracked by Dense. The threshold is set to keep the
3339 // worst-case memory usage within 2x of figures determined empirically for
3340 // "all Dense" scenario in such worst-by-execution-time cases.
3341 BitVector Sparse;
3342 DenseSet<Register> Dense;
3343};
3344
3345// Implements both a transfer function and a (binary, in-place) join operator
3346// for a dataflow over register sets with set union join and filtering transfer
3347// (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
3348// Maintains out_b as its state, allowing for O(n) iteration over it at any
3349// time, where n is the size of the set (as opposed to O(U) where U is the
3350// universe). filter_b implicitly contains all physical registers at all times.
3351class FilteringVRegSet {
3352 VRegFilter Filter;
3353 SmallVector<Register, 0> VRegs;
3354
3355public:
3356 // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
3357 // Both virtual and physical registers are fine.
3358 template <typename RegSetT> void addToFilter(const RegSetT &RS) {
3359 Filter.add(RS);
3360 }
3361 // Passes \p RS through the filter_b (transfer function) and adds what's left
3362 // to itself (out_b).
3363 template <typename RegSetT> bool add(const RegSetT &RS) {
3364 // Double-duty the Filter: to maintain VRegs a set (and the join operation
3365 // a set union) just add everything being added here to the Filter as well.
3366 return Filter.filterAndAdd(RS, VRegs);
3367 }
3368 using const_iterator = decltype(VRegs)::const_iterator;
3369 const_iterator begin() const { return VRegs.begin(); }
3370 const_iterator end() const { return VRegs.end(); }
3371 size_t size() const { return VRegs.size(); }
3372};
3373} // namespace
3374
3375// Calculate the largest possible vregsPassed sets. These are the registers that
3376// can pass through an MBB live, but may not be live every time. It is assumed
3377// that all vregsPassed sets are empty before the call.
3378void MachineVerifier::calcRegsPassed() {
3379 if (MF->empty())
3380 // ReversePostOrderTraversal doesn't handle empty functions.
3381 return;
3382
3383 for (const MachineBasicBlock *MB :
3384 ReversePostOrderTraversal<const MachineFunction *>(MF)) {
3385 FilteringVRegSet VRegs;
3386 BBInfo &Info = MBBInfoMap[MB];
3387 assert(Info.reachable);
3388
3389 VRegs.addToFilter(RS: Info.regsLiveOut);
3390 for (const MachineBasicBlock *Pred : MB->predecessors()) {
3391 const BBInfo &PredInfo = MBBInfoMap[Pred];
3392 if (!PredInfo.reachable)
3393 continue;
3394
3395 VRegs.add(RS: PredInfo.regsLiveOut);
3396 VRegs.add(RS: PredInfo.vregsPassed);
3397 }
3398 Info.vregsPassed.reserve(Size: VRegs.size());
3399 Info.vregsPassed.insert_range(R&: VRegs);
3400 }
3401}
3402
3403// Calculate the set of virtual registers that must be passed through each basic
3404// block in order to satisfy the requirements of successor blocks. This is very
3405// similar to calcRegsPassed, only backwards.
3406void MachineVerifier::calcRegsRequired() {
3407 // First push live-in regs to predecessors' vregsRequired.
3408 SmallPtrSet<const MachineBasicBlock*, 8> todo;
3409 for (const auto &MBB : *MF) {
3410 BBInfo &MInfo = MBBInfoMap[&MBB];
3411 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3412 BBInfo &PInfo = MBBInfoMap[Pred];
3413 if (PInfo.addRequired(RM: MInfo.vregsLiveIn))
3414 todo.insert(Ptr: Pred);
3415 }
3416
3417 // Handle the PHI node.
3418 for (const MachineInstr &MI : MBB.phis()) {
3419 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3420 // Skip those Operands which are undef regs or not regs.
3421 if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
3422 continue;
3423
3424 // Get register and predecessor for one PHI edge.
3425 Register Reg = MI.getOperand(i).getReg();
3426 const MachineBasicBlock *Pred = MI.getOperand(i: i + 1).getMBB();
3427
3428 BBInfo &PInfo = MBBInfoMap[Pred];
3429 if (PInfo.addRequired(Reg))
3430 todo.insert(Ptr: Pred);
3431 }
3432 }
3433 }
3434
3435 // Iteratively push vregsRequired to predecessors. This will converge to the
3436 // same final state regardless of DenseSet iteration order.
3437 while (!todo.empty()) {
3438 const MachineBasicBlock *MBB = *todo.begin();
3439 todo.erase(Ptr: MBB);
3440 BBInfo &MInfo = MBBInfoMap[MBB];
3441 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
3442 if (Pred == MBB)
3443 continue;
3444 BBInfo &SInfo = MBBInfoMap[Pred];
3445 if (SInfo.addRequired(RS: MInfo.vregsRequired))
3446 todo.insert(Ptr: Pred);
3447 }
3448 }
3449}
3450
3451// Check PHI instructions at the beginning of MBB. It is assumed that
3452// calcRegsPassed has been run so BBInfo::isLiveOut is valid.
3453void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
3454 BBInfo &MInfo = MBBInfoMap[&MBB];
3455
3456 SmallPtrSet<const MachineBasicBlock*, 8> seen;
3457 for (const MachineInstr &Phi : MBB) {
3458 if (!Phi.isPHI())
3459 break;
3460 seen.clear();
3461
3462 const MachineOperand &MODef = Phi.getOperand(i: 0);
3463 if (!MODef.isReg() || !MODef.isDef()) {
3464 report(msg: "Expected first PHI operand to be a register def", MO: &MODef, MONum: 0);
3465 continue;
3466 }
3467 if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
3468 MODef.isEarlyClobber() || MODef.isDebug())
3469 report(msg: "Unexpected flag on PHI operand", MO: &MODef, MONum: 0);
3470 Register DefReg = MODef.getReg();
3471 if (!DefReg.isVirtual())
3472 report(msg: "Expected first PHI operand to be a virtual register", MO: &MODef, MONum: 0);
3473
3474 for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
3475 const MachineOperand &MO0 = Phi.getOperand(i: I);
3476 if (!MO0.isReg()) {
3477 report(msg: "Expected PHI operand to be a register", MO: &MO0, MONum: I);
3478 continue;
3479 }
3480 if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
3481 MO0.isDebug() || MO0.isTied())
3482 report(msg: "Unexpected flag on PHI operand", MO: &MO0, MONum: I);
3483
3484 const MachineOperand &MO1 = Phi.getOperand(i: I + 1);
3485 if (!MO1.isMBB()) {
3486 report(msg: "Expected PHI operand to be a basic block", MO: &MO1, MONum: I + 1);
3487 continue;
3488 }
3489
3490 const MachineBasicBlock &Pre = *MO1.getMBB();
3491 if (!Pre.isSuccessor(MBB: &MBB)) {
3492 report(msg: "PHI input is not a predecessor block", MO: &MO1, MONum: I + 1);
3493 continue;
3494 }
3495
3496 if (MInfo.reachable) {
3497 seen.insert(Ptr: &Pre);
3498 BBInfo &PrInfo = MBBInfoMap[&Pre];
3499 if (!MO0.isUndef() && PrInfo.reachable &&
3500 !PrInfo.isLiveOut(Reg: MO0.getReg()))
3501 report(msg: "PHI operand is not live-out from predecessor", MO: &MO0, MONum: I);
3502 }
3503 }
3504
3505 // Did we see all predecessors?
3506 if (MInfo.reachable) {
3507 for (MachineBasicBlock *Pred : MBB.predecessors()) {
3508 if (!seen.count(Ptr: Pred)) {
3509 report(msg: "Missing PHI operand", MI: &Phi);
3510 OS << printMBBReference(MBB: *Pred)
3511 << " is a predecessor according to the CFG.\n";
3512 }
3513 }
3514 }
3515 }
3516}
3517
3518static void
3519verifyConvergenceControl(const MachineFunction &MF, MachineDominatorTree &DT,
3520 std::function<void(const Twine &Message)> FailureCB,
3521 raw_ostream &OS) {
3522 MachineConvergenceVerifier CV;
3523 CV.initialize(OS: &OS, FailureCB, F: MF);
3524
3525 for (const auto &MBB : MF) {
3526 CV.visit(BB: MBB);
3527 for (const auto &MI : MBB.instrs())
3528 CV.visit(I: MI);
3529 }
3530
3531 if (CV.sawTokens()) {
3532 DT.recalculate(Func&: const_cast<MachineFunction &>(MF));
3533 CV.verify(DT);
3534 }
3535}
3536
3537void MachineVerifier::visitMachineFunctionAfter() {
3538 auto FailureCB = [this](const Twine &Message) {
3539 report(msg: Message.str().c_str(), MF);
3540 };
3541 verifyConvergenceControl(MF: *MF, DT, FailureCB, OS);
3542
3543 calcRegsPassed();
3544
3545 for (const MachineBasicBlock &MBB : *MF)
3546 checkPHIOps(MBB);
3547
3548 // Now check liveness info if available
3549 calcRegsRequired();
3550
3551 if (!MF->empty()) {
3552 BBInfo &MInfo = MBBInfoMap[&MF->front()];
3553 for (Register VReg : MInfo.vregsRequired) {
3554 report(msg: "Virtual register defs don't dominate all uses.", MF);
3555 report_context_vreg(VReg);
3556 }
3557 }
3558
3559 if (LiveInts)
3560 verifyLiveIntervals();
3561
3562 // Check live-in list of each MBB. If a register is live into MBB, check
3563 // that the register is in regsLiveOut of each predecessor block. Since
3564 // this must come from a definition in the predecessor or its live-in
3565 // list, this will catch a live-through case where the predecessor does not
3566 // have the register in its live-in list. This currently only checks
3567 // registers that have no aliases, are not allocatable and are not
3568 // reserved, which could mean a condition code register for instance.
3569 if (MRI->tracksLiveness())
3570 for (const auto &MBB : *MF)
3571 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
3572 MCRegister LiveInReg = P.PhysReg;
3573 bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
3574 if (hasAliases || isAllocatable(Reg: LiveInReg) || isReserved(Reg: LiveInReg))
3575 continue;
3576 for (const MachineBasicBlock *Pred : MBB.predecessors()) {
3577 BBInfo &PInfo = MBBInfoMap[Pred];
3578 if (!PInfo.regsLiveOut.count(V: LiveInReg)) {
3579 report(msg: "Live in register not found to be live out from predecessor.",
3580 MBB: &MBB);
3581 OS << TRI->getName(RegNo: LiveInReg) << " not found to be live out from "
3582 << printMBBReference(MBB: *Pred) << '\n';
3583 }
3584 }
3585 }
3586
3587 for (auto CSInfo : MF->getCallSitesInfo())
3588 if (!CSInfo.first->isCall())
3589 report(msg: "Call site info referencing instruction that is not call", MF);
3590
3591 // If there's debug-info, check that we don't have any duplicate value
3592 // tracking numbers.
3593 if (MF->getFunction().getSubprogram()) {
3594 DenseSet<unsigned> SeenNumbers;
3595 for (const auto &MBB : *MF) {
3596 for (const auto &MI : MBB) {
3597 if (auto Num = MI.peekDebugInstrNum()) {
3598 auto Result = SeenNumbers.insert(V: (unsigned)Num);
3599 if (!Result.second)
3600 report(msg: "Instruction has a duplicated value tracking number", MI: &MI);
3601 }
3602 }
3603 }
3604 }
3605}
3606
3607void MachineVerifier::verifyLiveIntervals() {
3608 assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
3609 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
3610 Register Reg = Register::index2VirtReg(Index: I);
3611
3612 // Spilling and splitting may leave unused registers around. Skip them.
3613 if (MRI->reg_nodbg_empty(RegNo: Reg))
3614 continue;
3615
3616 if (!LiveInts->hasInterval(Reg)) {
3617 report(msg: "Missing live interval for virtual register", MF);
3618 OS << printReg(Reg, TRI) << " still has defs or uses\n";
3619 continue;
3620 }
3621
3622 const LiveInterval &LI = LiveInts->getInterval(Reg);
3623 assert(Reg == LI.reg() && "Invalid reg to interval mapping");
3624 verifyLiveInterval(LI);
3625 }
3626
3627 // Verify all the cached regunit intervals.
3628 for (MCRegUnit Unit : TRI->regunits())
3629 if (const LiveRange *LR = LiveInts->getCachedRegUnit(Unit))
3630 verifyLiveRange(*LR, VirtRegOrUnit(Unit));
3631}
3632
3633void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
3634 const VNInfo *VNI,
3635 VirtRegOrUnit VRegOrUnit,
3636 LaneBitmask LaneMask) {
3637 if (VNI->isUnused())
3638 return;
3639
3640 const VNInfo *DefVNI = LR.getVNInfoAt(Idx: VNI->def);
3641
3642 if (!DefVNI) {
3643 report(msg: "Value not live at VNInfo def and not marked unused", MF);
3644 report_context(LR, VRegOrUnit, LaneMask);
3645 report_context(VNI: *VNI);
3646 return;
3647 }
3648
3649 if (DefVNI != VNI) {
3650 report(msg: "Live segment at def has different VNInfo", MF);
3651 report_context(LR, VRegOrUnit, LaneMask);
3652 report_context(VNI: *VNI);
3653 return;
3654 }
3655
3656 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(index: VNI->def);
3657 if (!MBB) {
3658 report(msg: "Invalid VNInfo definition index", MF);
3659 report_context(LR, VRegOrUnit, LaneMask);
3660 report_context(VNI: *VNI);
3661 return;
3662 }
3663
3664 if (VNI->isPHIDef()) {
3665 if (VNI->def != LiveInts->getMBBStartIdx(mbb: MBB)) {
3666 report(msg: "PHIDef VNInfo is not defined at MBB start", MBB);
3667 report_context(LR, VRegOrUnit, LaneMask);
3668 report_context(VNI: *VNI);
3669 }
3670 return;
3671 }
3672
3673 // Non-PHI def.
3674 const MachineInstr *MI = LiveInts->getInstructionFromIndex(index: VNI->def);
3675 if (!MI) {
3676 report(msg: "No instruction at VNInfo def index", MBB);
3677 report_context(LR, VRegOrUnit, LaneMask);
3678 report_context(VNI: *VNI);
3679 return;
3680 }
3681
3682 bool hasDef = false;
3683 bool isEarlyClobber = false;
3684 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3685 if (!MOI->isReg() || !MOI->isDef())
3686 continue;
3687 if (VRegOrUnit.isVirtualReg()) {
3688 if (MOI->getReg() != VRegOrUnit.asVirtualReg())
3689 continue;
3690 } else {
3691 if (!MOI->getReg().isPhysical() ||
3692 !TRI->hasRegUnit(Reg: MOI->getReg(), RegUnit: VRegOrUnit.asMCRegUnit()))
3693 continue;
3694 }
3695 if (LaneMask.any() &&
3696 (TRI->getSubRegIndexLaneMask(SubIdx: MOI->getSubReg()) & LaneMask).none())
3697 continue;
3698 hasDef = true;
3699 if (MOI->isEarlyClobber())
3700 isEarlyClobber = true;
3701 }
3702
3703 if (!hasDef) {
3704 report(msg: "Defining instruction does not modify register", MI);
3705 report_context(LR, VRegOrUnit, LaneMask);
3706 report_context(VNI: *VNI);
3707 }
3708
3709 // Early clobber defs begin at USE slots, but other defs must begin at
3710 // DEF slots.
3711 if (isEarlyClobber) {
3712 if (!VNI->def.isEarlyClobber()) {
3713 report(msg: "Early clobber def must be at an early-clobber slot", MBB);
3714 report_context(LR, VRegOrUnit, LaneMask);
3715 report_context(VNI: *VNI);
3716 }
3717 } else if (!VNI->def.isRegister()) {
3718 report(msg: "Non-PHI, non-early clobber def must be at a register slot", MBB);
3719 report_context(LR, VRegOrUnit, LaneMask);
3720 report_context(VNI: *VNI);
3721 }
3722}
3723
3724void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
3725 const LiveRange::const_iterator I,
3726 VirtRegOrUnit VRegOrUnit,
3727 LaneBitmask LaneMask) {
3728 const LiveRange::Segment &S = *I;
3729 const VNInfo *VNI = S.valno;
3730 assert(VNI && "Live segment has no valno");
3731
3732 if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(ValNo: VNI->id)) {
3733 report(msg: "Foreign valno in live segment", MF);
3734 report_context(LR, VRegOrUnit, LaneMask);
3735 report_context(S);
3736 report_context(VNI: *VNI);
3737 }
3738
3739 if (VNI->isUnused()) {
3740 report(msg: "Live segment valno is marked unused", MF);
3741 report_context(LR, VRegOrUnit, LaneMask);
3742 report_context(S);
3743 }
3744
3745 const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(index: S.start);
3746 if (!MBB) {
3747 report(msg: "Bad start of live segment, no basic block", MF);
3748 report_context(LR, VRegOrUnit, LaneMask);
3749 report_context(S);
3750 return;
3751 }
3752 SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(mbb: MBB);
3753 if (S.start != MBBStartIdx && S.start != VNI->def) {
3754 report(msg: "Live segment must begin at MBB entry or valno def", MBB);
3755 report_context(LR, VRegOrUnit, LaneMask);
3756 report_context(S);
3757 }
3758
3759 const MachineBasicBlock *EndMBB =
3760 LiveInts->getMBBFromIndex(index: S.end.getPrevSlot());
3761 if (!EndMBB) {
3762 report(msg: "Bad end of live segment, no basic block", MF);
3763 report_context(LR, VRegOrUnit, LaneMask);
3764 report_context(S);
3765 return;
3766 }
3767
3768 // Checks for non-live-out segments.
3769 if (S.end != LiveInts->getMBBEndIdx(mbb: EndMBB)) {
3770 // RegUnit intervals are allowed dead phis.
3771 if (!VRegOrUnit.isVirtualReg() && VNI->isPHIDef() && S.start == VNI->def &&
3772 S.end == VNI->def.getDeadSlot())
3773 return;
3774
3775 // The live segment is ending inside EndMBB
3776 const MachineInstr *MI =
3777 LiveInts->getInstructionFromIndex(index: S.end.getPrevSlot());
3778 if (!MI) {
3779 report(msg: "Live segment doesn't end at a valid instruction", MBB: EndMBB);
3780 report_context(LR, VRegOrUnit, LaneMask);
3781 report_context(S);
3782 return;
3783 }
3784
3785 // The block slot must refer to a basic block boundary.
3786 if (S.end.isBlock()) {
3787 report(msg: "Live segment ends at B slot of an instruction", MBB: EndMBB);
3788 report_context(LR, VRegOrUnit, LaneMask);
3789 report_context(S);
3790 }
3791
3792 if (S.end.isDead()) {
3793 // Segment ends on the dead slot.
3794 // That means there must be a dead def.
3795 if (!SlotIndex::isSameInstr(A: S.start, B: S.end)) {
3796 report(msg: "Live segment ending at dead slot spans instructions", MBB: EndMBB);
3797 report_context(LR, VRegOrUnit, LaneMask);
3798 report_context(S);
3799 }
3800 }
3801
3802 // After tied operands are rewritten, a live segment can only end at an
3803 // early-clobber slot if it is being redefined by an early-clobber def.
3804 // TODO: Before tied operands are rewritten, a live segment can only end at
3805 // an early-clobber slot if the last use is tied to an early-clobber def.
3806 if (MF->getProperties().hasTiedOpsRewritten() && S.end.isEarlyClobber()) {
3807 if (I + 1 == LR.end() || (I + 1)->start != S.end) {
3808 report(msg: "Live segment ending at early clobber slot must be "
3809 "redefined by an EC def in the same instruction",
3810 MBB: EndMBB);
3811 report_context(LR, VRegOrUnit, LaneMask);
3812 report_context(S);
3813 }
3814 }
3815
3816 // The following checks only apply to virtual registers. Physreg liveness
3817 // is too weird to check.
3818 if (VRegOrUnit.isVirtualReg()) {
3819 // A live segment can end with either a redefinition, a use, or a dead
3820 // flag on a def.
3821 bool hasRead = false;
3822 bool hasSubRegDef = false;
3823 bool hasDeadDef = false;
3824 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
3825 if (!MOI->isReg() || MOI->getReg() != VRegOrUnit.asVirtualReg())
3826 continue;
3827 unsigned Sub = MOI->getSubReg();
3828 LaneBitmask SLM =
3829 Sub != 0 ? TRI->getSubRegIndexLaneMask(SubIdx: Sub) : LaneBitmask::getAll();
3830 if (MOI->isDef()) {
3831 if (Sub != 0) {
3832 hasSubRegDef = true;
3833 // An operand %0:sub0 reads %0:sub1..n. Invert the lane
3834 // mask for subregister defs. Read-undef defs will be handled by
3835 // readsReg below.
3836 SLM = ~SLM;
3837 }
3838 if (MOI->isDead())
3839 hasDeadDef = true;
3840 }
3841 if (LaneMask.any() && (LaneMask & SLM).none())
3842 continue;
3843 if (MOI->readsReg())
3844 hasRead = true;
3845 }
3846 if (S.end.isDead()) {
3847 // Make sure that the corresponding machine operand for a "dead" live
3848 // range has the dead flag. We cannot perform this check for subregister
3849 // liveranges as partially dead values are allowed.
3850 if (LaneMask.none() && !hasDeadDef) {
3851 report(
3852 msg: "Instruction ending live segment on dead slot has no dead flag",
3853 MI);
3854 report_context(LR, VRegOrUnit, LaneMask);
3855 report_context(S);
3856 }
3857 } else {
3858 if (!hasRead) {
3859 // When tracking subregister liveness, the main range must start new
3860 // values on partial register writes, even if there is no read.
3861 if (!MRI->shouldTrackSubRegLiveness(VReg: VRegOrUnit.asVirtualReg()) ||
3862 LaneMask.any() || !hasSubRegDef) {
3863 report(msg: "Instruction ending live segment doesn't read the register",
3864 MI);
3865 report_context(LR, VRegOrUnit, LaneMask);
3866 report_context(S);
3867 }
3868 }
3869 }
3870 }
3871 }
3872
3873 // Now check all the basic blocks in this live segment.
3874 MachineFunction::const_iterator MFI = MBB->getIterator();
3875 // Is this live segment the beginning of a non-PHIDef VN?
3876 if (S.start == VNI->def && !VNI->isPHIDef()) {
3877 // Not live-in to any blocks.
3878 if (MBB == EndMBB)
3879 return;
3880 // Skip this block.
3881 ++MFI;
3882 }
3883
3884 SmallVector<SlotIndex, 4> Undefs;
3885 if (LaneMask.any()) {
3886 LiveInterval &OwnerLI = LiveInts->getInterval(Reg: VRegOrUnit.asVirtualReg());
3887 OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, MRI: *MRI, Indexes: *Indexes);
3888 }
3889
3890 while (true) {
3891 assert(LiveInts->isLiveInToMBB(LR, &*MFI));
3892 // We don't know how to track physregs into a landing pad.
3893 if (!VRegOrUnit.isVirtualReg() && MFI->isEHPad()) {
3894 if (&*MFI == EndMBB)
3895 break;
3896 ++MFI;
3897 continue;
3898 }
3899
3900 // Is VNI a PHI-def in the current block?
3901 bool IsPHI = VNI->isPHIDef() &&
3902 VNI->def == LiveInts->getMBBStartIdx(mbb: &*MFI);
3903
3904 // Check that VNI is live-out of all predecessors.
3905 for (const MachineBasicBlock *Pred : MFI->predecessors()) {
3906 SlotIndex PEnd = LiveInts->getMBBEndIdx(mbb: Pred);
3907 // Predecessor of landing pad live-out on last call.
3908 if (MFI->isEHPad()) {
3909 for (const MachineInstr &MI : llvm::reverse(C: *Pred)) {
3910 if (MI.isCall()) {
3911 PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
3912 break;
3913 }
3914 }
3915 }
3916 const VNInfo *PVNI = LR.getVNInfoBefore(Idx: PEnd);
3917
3918 // All predecessors must have a live-out value. However for a phi
3919 // instruction with subregister intervals
3920 // only one of the subregisters (not necessarily the current one) needs to
3921 // be defined.
3922 if (!PVNI && (LaneMask.none() || !IsPHI)) {
3923 if (LiveRangeCalc::isJointlyDominated(MBB: Pred, Defs: Undefs, Indexes: *Indexes))
3924 continue;
3925 report(msg: "Register not marked live out of predecessor", MBB: Pred);
3926 report_context(LR, VRegOrUnit, LaneMask);
3927 report_context(VNI: *VNI);
3928 OS << " live into " << printMBBReference(MBB: *MFI) << '@'
3929 << LiveInts->getMBBStartIdx(mbb: &*MFI) << ", not live before " << PEnd
3930 << '\n';
3931 continue;
3932 }
3933
3934 // Only PHI-defs can take different predecessor values.
3935 if (!IsPHI && PVNI != VNI) {
3936 report(msg: "Different value live out of predecessor", MBB: Pred);
3937 report_context(LR, VRegOrUnit, LaneMask);
3938 OS << "Valno #" << PVNI->id << " live out of "
3939 << printMBBReference(MBB: *Pred) << '@' << PEnd << "\nValno #" << VNI->id
3940 << " live into " << printMBBReference(MBB: *MFI) << '@'
3941 << LiveInts->getMBBStartIdx(mbb: &*MFI) << '\n';
3942 }
3943 }
3944 if (&*MFI == EndMBB)
3945 break;
3946 ++MFI;
3947 }
3948}
3949
3950void MachineVerifier::verifyLiveRange(const LiveRange &LR,
3951 VirtRegOrUnit VRegOrUnit,
3952 LaneBitmask LaneMask) {
3953 for (const VNInfo *VNI : LR.valnos)
3954 verifyLiveRangeValue(LR, VNI, VRegOrUnit, LaneMask);
3955
3956 for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
3957 verifyLiveRangeSegment(LR, I, VRegOrUnit, LaneMask);
3958}
3959
3960void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
3961 Register Reg = LI.reg();
3962 assert(Reg.isVirtual());
3963 verifyLiveRange(LR: LI, VRegOrUnit: VirtRegOrUnit(Reg));
3964
3965 if (LI.hasSubRanges()) {
3966 LaneBitmask Mask;
3967 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
3968 for (const LiveInterval::SubRange &SR : LI.subranges()) {
3969 if ((Mask & SR.LaneMask).any()) {
3970 report(msg: "Lane masks of sub ranges overlap in live interval", MF);
3971 report_context(LI);
3972 }
3973 if ((SR.LaneMask & ~MaxMask).any()) {
3974 report(msg: "Subrange lanemask is invalid", MF);
3975 report_context(LI);
3976 }
3977 if (SR.empty()) {
3978 report(msg: "Subrange must not be empty", MF);
3979 report_context(LR: SR, VRegOrUnit: VirtRegOrUnit(LI.reg()), LaneMask: SR.LaneMask);
3980 }
3981 Mask |= SR.LaneMask;
3982 verifyLiveRange(LR: SR, VRegOrUnit: VirtRegOrUnit(LI.reg()), LaneMask: SR.LaneMask);
3983 if (!LI.covers(Other: SR)) {
3984 report(msg: "A Subrange is not covered by the main range", MF);
3985 report_context(LI);
3986 }
3987 }
3988 }
3989
3990 // Check the LI only has one connected component.
3991 ConnectedVNInfoEqClasses ConEQ(*LiveInts);
3992 unsigned NumComp = ConEQ.Classify(LR: LI);
3993 if (NumComp > 1) {
3994 report(msg: "Multiple connected components in live interval", MF);
3995 report_context(LI);
3996 for (unsigned comp = 0; comp != NumComp; ++comp) {
3997 OS << comp << ": valnos";
3998 for (const VNInfo *I : LI.valnos)
3999 if (comp == ConEQ.getEqClass(VNI: I))
4000 OS << ' ' << I->id;
4001 OS << '\n';
4002 }
4003 }
4004}
4005
4006namespace {
4007
4008 // FrameSetup and FrameDestroy can have zero adjustment, so using a single
4009 // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
4010 // value is zero.
4011 // We use a bool plus an integer to capture the stack state.
4012struct StackStateOfBB {
4013 StackStateOfBB() = default;
4014 StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup)
4015 : EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
4016 ExitIsSetup(ExitSetup) {}
4017
4018 // Can be negative, which means we are setting up a frame.
4019 int EntryValue = 0;
4020 int ExitValue = 0;
4021 bool EntryIsSetup = false;
4022 bool ExitIsSetup = false;
4023};
4024
4025} // end anonymous namespace
4026
4027/// Make sure on every path through the CFG, a FrameSetup <n> is always followed
4028/// by a FrameDestroy <n>, stack adjustments are identical on all
4029/// CFG edges to a merge point, and frame is destroyed at end of a return block.
4030void MachineVerifier::verifyStackFrame() {
4031 unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
4032 unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
4033 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
4034 return;
4035
4036 SmallVector<StackStateOfBB, 8> SPState;
4037 SPState.resize(N: MF->getNumBlockIDs());
4038 df_iterator_default_set<const MachineBasicBlock*> Reachable;
4039
4040 // Visit the MBBs in DFS order.
4041 for (df_ext_iterator<const MachineFunction *,
4042 df_iterator_default_set<const MachineBasicBlock *>>
4043 DFI = df_ext_begin(G: MF, S&: Reachable), DFE = df_ext_end(G: MF, S&: Reachable);
4044 DFI != DFE; ++DFI) {
4045 const MachineBasicBlock *MBB = *DFI;
4046
4047 StackStateOfBB BBState;
4048 // Check the exit state of the DFS stack predecessor.
4049 if (DFI.getPathLength() >= 2) {
4050 const MachineBasicBlock *StackPred = DFI.getPath(n: DFI.getPathLength() - 2);
4051 assert(Reachable.count(StackPred) &&
4052 "DFS stack predecessor is already visited.\n");
4053 BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
4054 BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
4055 BBState.ExitValue = BBState.EntryValue;
4056 BBState.ExitIsSetup = BBState.EntryIsSetup;
4057 }
4058
4059 if ((int)MBB->getCallFrameSize() != -BBState.EntryValue) {
4060 report(msg: "Call frame size on entry does not match value computed from "
4061 "predecessor",
4062 MBB);
4063 OS << "Call frame size on entry " << MBB->getCallFrameSize()
4064 << " does not match value computed from predecessor "
4065 << -BBState.EntryValue << '\n';
4066 }
4067
4068 // Update stack state by checking contents of MBB.
4069 for (const auto &I : *MBB) {
4070 if (I.getOpcode() == FrameSetupOpcode) {
4071 if (BBState.ExitIsSetup)
4072 report(msg: "FrameSetup is after another FrameSetup", MI: &I);
4073 if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
4074 report(msg: "AdjustsStack not set in presence of a frame pseudo "
4075 "instruction.", MI: &I);
4076 BBState.ExitValue -= TII->getFrameTotalSize(I);
4077 BBState.ExitIsSetup = true;
4078 }
4079
4080 if (I.getOpcode() == FrameDestroyOpcode) {
4081 int Size = TII->getFrameTotalSize(I);
4082 if (!BBState.ExitIsSetup)
4083 report(msg: "FrameDestroy is not after a FrameSetup", MI: &I);
4084 int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
4085 BBState.ExitValue;
4086 if (BBState.ExitIsSetup && AbsSPAdj != Size) {
4087 report(msg: "FrameDestroy <n> is after FrameSetup <m>", MI: &I);
4088 OS << "FrameDestroy <" << Size << "> is after FrameSetup <"
4089 << AbsSPAdj << ">.\n";
4090 }
4091 if (!MRI->isSSA() && !MF->getFrameInfo().adjustsStack())
4092 report(msg: "AdjustsStack not set in presence of a frame pseudo "
4093 "instruction.", MI: &I);
4094 BBState.ExitValue += Size;
4095 BBState.ExitIsSetup = false;
4096 }
4097 }
4098 SPState[MBB->getNumber()] = BBState;
4099
4100 // Make sure the exit state of any predecessor is consistent with the entry
4101 // state.
4102 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
4103 if (Reachable.count(Ptr: Pred) &&
4104 (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
4105 SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
4106 report(msg: "The exit stack state of a predecessor is inconsistent.", MBB);
4107 OS << "Predecessor " << printMBBReference(MBB: *Pred) << " has exit state ("
4108 << SPState[Pred->getNumber()].ExitValue << ", "
4109 << SPState[Pred->getNumber()].ExitIsSetup << "), while "
4110 << printMBBReference(MBB: *MBB) << " has entry state ("
4111 << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
4112 }
4113 }
4114
4115 // Make sure the entry state of any successor is consistent with the exit
4116 // state.
4117 for (const MachineBasicBlock *Succ : MBB->successors()) {
4118 if (Reachable.count(Ptr: Succ) &&
4119 (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
4120 SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
4121 report(msg: "The entry stack state of a successor is inconsistent.", MBB);
4122 OS << "Successor " << printMBBReference(MBB: *Succ) << " has entry state ("
4123 << SPState[Succ->getNumber()].EntryValue << ", "
4124 << SPState[Succ->getNumber()].EntryIsSetup << "), while "
4125 << printMBBReference(MBB: *MBB) << " has exit state ("
4126 << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
4127 }
4128 }
4129
4130 // Make sure a basic block with return ends with zero stack adjustment.
4131 if (!MBB->empty() && MBB->back().isReturn()) {
4132 if (BBState.ExitIsSetup)
4133 report(msg: "A return block ends with a FrameSetup.", MBB);
4134 if (BBState.ExitValue)
4135 report(msg: "A return block ends with a nonzero stack adjustment.", MBB);
4136 }
4137 }
4138}
4139
4140void MachineVerifier::verifyStackProtector() {
4141 const MachineFrameInfo &MFI = MF->getFrameInfo();
4142 if (!MFI.hasStackProtectorIndex())
4143 return;
4144 // Only applicable when the offsets of frame objects have been determined,
4145 // which is indicated by a non-zero stack size.
4146 if (!MFI.getStackSize())
4147 return;
4148 const TargetFrameLowering &TFI = *MF->getSubtarget().getFrameLowering();
4149 bool StackGrowsDown =
4150 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
4151 unsigned FI = MFI.getStackProtectorIndex();
4152 int64_t SPStart = MFI.getObjectOffset(ObjectIdx: FI);
4153 int64_t SPEnd = SPStart + MFI.getObjectSize(ObjectIdx: FI);
4154 for (unsigned I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
4155 if (I == FI)
4156 continue;
4157 if (MFI.isDeadObjectIndex(ObjectIdx: I))
4158 continue;
4159 // FIXME: Skip non-default stack objects, as some targets may place them
4160 // above the stack protector. This is a workaround for the fact that
4161 // backends such as AArch64 may place SVE stack objects *above* the stack
4162 // protector.
4163 if (MFI.getStackID(ObjectIdx: I) != TargetStackID::Default)
4164 continue;
4165 // Skip variable-sized objects because they do not have a fixed offset.
4166 if (MFI.isVariableSizedObjectIndex(ObjectIdx: I))
4167 continue;
4168 // FIXME: Skip spill slots which may be allocated above the stack protector.
4169 // Ideally this would only skip callee-saved registers, but we don't have
4170 // that information here. For example, spill-slots used for scavenging are
4171 // not described in CalleeSavedInfo.
4172 if (MFI.isSpillSlotObjectIndex(ObjectIdx: I))
4173 continue;
4174 int64_t ObjStart = MFI.getObjectOffset(ObjectIdx: I);
4175 int64_t ObjEnd = ObjStart + MFI.getObjectSize(ObjectIdx: I);
4176 if (SPStart < ObjEnd && ObjStart < SPEnd) {
4177 report(msg: "Stack protector overlaps with another stack object", MF);
4178 break;
4179 }
4180 if ((StackGrowsDown && SPStart <= ObjStart) ||
4181 (!StackGrowsDown && SPStart >= ObjStart)) {
4182 report(msg: "Stack protector is not the top-most object on the stack", MF);
4183 break;
4184 }
4185 }
4186}
4187