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