LLVM 23.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module 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// This file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "llvm/ADT/APFloat.h"
52#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/MapVector.h"
56#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Twine.h"
63#include "llvm/IR/Argument.h"
65#include "llvm/IR/Attributes.h"
66#include "llvm/IR/BasicBlock.h"
67#include "llvm/IR/CFG.h"
68#include "llvm/IR/CallingConv.h"
69#include "llvm/IR/Comdat.h"
70#include "llvm/IR/Constant.h"
73#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DebugInfo.h"
78#include "llvm/IR/DebugLoc.h"
80#include "llvm/IR/Dominators.h"
82#include "llvm/IR/FPEnv.h"
83#include "llvm/IR/Function.h"
84#include "llvm/IR/GCStrategy.h"
86#include "llvm/IR/GlobalAlias.h"
87#include "llvm/IR/GlobalValue.h"
89#include "llvm/IR/InlineAsm.h"
90#include "llvm/IR/InstVisitor.h"
91#include "llvm/IR/InstrTypes.h"
92#include "llvm/IR/Instruction.h"
95#include "llvm/IR/Intrinsics.h"
96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsNVPTX.h"
100#include "llvm/IR/IntrinsicsWebAssembly.h"
101#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Metadata.h"
104#include "llvm/IR/Module.h"
106#include "llvm/IR/PassManager.h"
108#include "llvm/IR/Statepoint.h"
109#include "llvm/IR/Type.h"
110#include "llvm/IR/Use.h"
111#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
115#include "llvm/Pass.h"
119#include "llvm/Support/Casting.h"
123#include "llvm/Support/ModRef.h"
126#include <algorithm>
127#include <cassert>
128#include <cstdint>
129#include <memory>
130#include <optional>
131#include <string>
132#include <utility>
133
134using namespace llvm;
135
137 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
138 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
139 "scopes are not dominating"));
140
143 const Module &M;
145 const Triple &TT;
148
149 /// Track the brokenness of the module while recursively visiting.
150 bool Broken = false;
151 /// Broken debug info can be "recovered" from by stripping the debug info.
152 bool BrokenDebugInfo = false;
153 /// Whether to treat broken debug info as an error.
155
157 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
158 Context(M.getContext()) {}
159
160private:
161 void Write(const Module *M) {
162 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
163 }
164
165 void Write(const Value *V) {
166 if (V)
167 Write(*V);
168 }
169
170 void Write(const Value &V) {
171 if (isa<Instruction>(V)) {
172 V.print(*OS, MST);
173 *OS << '\n';
174 } else {
175 V.printAsOperand(*OS, true, MST);
176 *OS << '\n';
177 }
178 }
179
180 void Write(const DbgRecord *DR) {
181 if (DR) {
182 DR->print(*OS, MST, false);
183 *OS << '\n';
184 }
185 }
186
188 switch (Type) {
190 *OS << "value";
191 break;
193 *OS << "declare";
194 break;
196 *OS << "declare_value";
197 break;
199 *OS << "assign";
200 break;
202 *OS << "end";
203 break;
205 *OS << "any";
206 break;
207 };
208 }
209
210 void Write(const Metadata *MD) {
211 if (!MD)
212 return;
213 MD->print(*OS, MST, &M);
214 *OS << '\n';
215 }
216
217 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
218 Write(MD.get());
219 }
220
221 void Write(const NamedMDNode *NMD) {
222 if (!NMD)
223 return;
224 NMD->print(*OS, MST);
225 *OS << '\n';
226 }
227
228 void Write(Type *T) {
229 if (!T)
230 return;
231 *OS << ' ' << *T;
232 }
233
234 void Write(const Comdat *C) {
235 if (!C)
236 return;
237 *OS << *C;
238 }
239
240 void Write(const APInt *AI) {
241 if (!AI)
242 return;
243 *OS << *AI << '\n';
244 }
245
246 void Write(const unsigned i) { *OS << i << '\n'; }
247
248 // NOLINTNEXTLINE(readability-identifier-naming)
249 void Write(const Attribute *A) {
250 if (!A)
251 return;
252 *OS << A->getAsString() << '\n';
253 }
254
255 // NOLINTNEXTLINE(readability-identifier-naming)
256 void Write(const AttributeSet *AS) {
257 if (!AS)
258 return;
259 *OS << AS->getAsString() << '\n';
260 }
261
262 // NOLINTNEXTLINE(readability-identifier-naming)
263 void Write(const AttributeList *AL) {
264 if (!AL)
265 return;
266 AL->print(*OS);
267 }
268
269 void Write(Printable P) { *OS << P << '\n'; }
270
271 template <typename T> void Write(ArrayRef<T> Vs) {
272 for (const T &V : Vs)
273 Write(V);
274 }
275
276 template <typename T1, typename... Ts>
277 void WriteTs(const T1 &V1, const Ts &... Vs) {
278 Write(V1);
279 WriteTs(Vs...);
280 }
281
282 template <typename... Ts> void WriteTs() {}
283
284public:
285 /// A check failed, so printout out the condition and the message.
286 ///
287 /// This provides a nice place to put a breakpoint if you want to see why
288 /// something is not correct.
289 void CheckFailed(const Twine &Message) {
290 if (OS)
291 *OS << Message << '\n';
292 Broken = true;
293 }
294
295 /// A check failed (with values to print).
296 ///
297 /// This calls the Message-only version so that the above is easier to set a
298 /// breakpoint on.
299 template <typename T1, typename... Ts>
300 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
301 CheckFailed(Message);
302 if (OS)
303 WriteTs(V1, Vs...);
304 }
305
306 /// A debug info check failed.
307 void DebugInfoCheckFailed(const Twine &Message) {
308 if (OS)
309 *OS << Message << '\n';
311 BrokenDebugInfo = true;
312 }
313
314 /// A debug info check failed (with values to print).
315 template <typename T1, typename... Ts>
316 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
317 const Ts &... Vs) {
318 DebugInfoCheckFailed(Message);
319 if (OS)
320 WriteTs(V1, Vs...);
321 }
322};
323
324namespace {
325
326class Verifier : public InstVisitor<Verifier>, VerifierSupport {
327 friend class InstVisitor<Verifier>;
328 DominatorTree DT;
329
330 /// When verifying a basic block, keep track of all of the
331 /// instructions we have seen so far.
332 ///
333 /// This allows us to do efficient dominance checks for the case when an
334 /// instruction has an operand that is an instruction in the same block.
335 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
336
337 /// Keep track of the metadata nodes that have been checked already.
339
340 /// Keep track which DISubprogram is attached to which function.
342
343 /// Track all DICompileUnits visited.
345
346 /// The result type for a landingpad.
347 Type *LandingPadResultTy;
348
349 /// Whether we've seen a call to @llvm.localescape in this function
350 /// already.
351 bool SawFrameEscape;
352
353 /// Whether the current function has a DISubprogram attached to it.
354 bool HasDebugInfo = false;
355
356 /// Stores the count of how many objects were passed to llvm.localescape for a
357 /// given function and the largest index passed to llvm.localrecover.
359
360 // Maps catchswitches and cleanuppads that unwind to siblings to the
361 // terminators that indicate the unwind, used to detect cycles therein.
363
364 /// Cache which blocks are in which funclet, if an EH funclet personality is
365 /// in use. Otherwise empty.
366 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
367
368 /// Cache of constants visited in search of ConstantExprs.
369 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
370
371 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
372 SmallVector<const Function *, 4> DeoptimizeDeclarations;
373
374 /// Cache of attribute lists verified.
375 SmallPtrSet<const void *, 32> AttributeListsVisited;
376
377 // Verify that this GlobalValue is only used in this module.
378 // This map is used to avoid visiting uses twice. We can arrive at a user
379 // twice, if they have multiple operands. In particular for very large
380 // constant expressions, we can arrive at a particular user many times.
381 SmallPtrSet<const Value *, 32> GlobalValueVisited;
382
383 // Keeps track of duplicate function argument debug info.
385
386 TBAAVerifier TBAAVerifyHelper;
387 ConvergenceVerifier ConvergenceVerifyHelper;
388
389 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
390
391 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
392
393public:
394 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
395 const Module &M)
396 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
397 SawFrameEscape(false), TBAAVerifyHelper(this) {
398 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
399 }
400
401 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
402
403 bool verify(const Function &F) {
404 llvm::TimeTraceScope timeScope("Verifier");
405 assert(F.getParent() == &M &&
406 "An instance of this class only works with a specific module!");
407
408 // First ensure the function is well-enough formed to compute dominance
409 // information, and directly compute a dominance tree. We don't rely on the
410 // pass manager to provide this as it isolates us from a potentially
411 // out-of-date dominator tree and makes it significantly more complex to run
412 // this code outside of a pass manager.
413 // FIXME: It's really gross that we have to cast away constness here.
414 if (!F.empty())
415 DT.recalculate(const_cast<Function &>(F));
416
417 for (const BasicBlock &BB : F) {
418 if (!BB.empty() && BB.back().isTerminator())
419 continue;
420
421 if (OS) {
422 *OS << "Basic Block in function '" << F.getName()
423 << "' does not have terminator!\n";
424 BB.printAsOperand(*OS, true, MST);
425 *OS << "\n";
426 }
427 return false;
428 }
429
430 auto FailureCB = [this](const Twine &Message) {
431 this->CheckFailed(Message);
432 };
433 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
434
435 Broken = false;
436 // FIXME: We strip const here because the inst visitor strips const.
437 visit(const_cast<Function &>(F));
438 verifySiblingFuncletUnwinds();
439
440 if (ConvergenceVerifyHelper.sawTokens())
441 ConvergenceVerifyHelper.verify(DT);
442
443 InstsInThisBlock.clear();
444 DebugFnArgs.clear();
445 LandingPadResultTy = nullptr;
446 SawFrameEscape = false;
447 SiblingFuncletInfo.clear();
448 verifyNoAliasScopeDecl();
449 NoAliasScopeDecls.clear();
450
451 return !Broken;
452 }
453
454 /// Verify the module that this instance of \c Verifier was initialized with.
455 bool verify() {
456 Broken = false;
457
458 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
459 for (const Function &F : M)
460 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
461 DeoptimizeDeclarations.push_back(&F);
462
463 // Now that we've visited every function, verify that we never asked to
464 // recover a frame index that wasn't escaped.
465 verifyFrameRecoverIndices();
466 for (const GlobalVariable &GV : M.globals())
467 visitGlobalVariable(GV);
468
469 for (const GlobalAlias &GA : M.aliases())
470 visitGlobalAlias(GA);
471
472 for (const GlobalIFunc &GI : M.ifuncs())
473 visitGlobalIFunc(GI);
474
475 for (const NamedMDNode &NMD : M.named_metadata())
476 visitNamedMDNode(NMD);
477
478 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
479 visitComdat(SMEC.getValue());
480
481 visitModuleFlags();
482 visitModuleIdents();
483 visitModuleCommandLines();
484 visitModuleErrnoTBAA();
485
486 verifyCompileUnits();
487
488 verifyDeoptimizeCallingConvs();
489 DISubprogramAttachments.clear();
490 return !Broken;
491 }
492
493private:
494 /// Whether a metadata node is allowed to be, or contain, a DILocation.
495 enum class AreDebugLocsAllowed { No, Yes };
496
497 /// Metadata that should be treated as a range, with slightly different
498 /// requirements.
499 enum class RangeLikeMetadataKind {
500 Range, // MD_range
501 AbsoluteSymbol, // MD_absolute_symbol
502 NoaliasAddrspace // MD_noalias_addrspace
503 };
504
505 // Verification methods...
506 void visitGlobalValue(const GlobalValue &GV);
507 void visitGlobalVariable(const GlobalVariable &GV);
508 void visitGlobalAlias(const GlobalAlias &GA);
509 void visitGlobalIFunc(const GlobalIFunc &GI);
510 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
511 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
512 const GlobalAlias &A, const Constant &C);
513 void visitNamedMDNode(const NamedMDNode &NMD);
514 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
515 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
516 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
517 void visitDIArgList(const DIArgList &AL, Function *F);
518 void visitComdat(const Comdat &C);
519 void visitModuleIdents();
520 void visitModuleCommandLines();
521 void visitModuleErrnoTBAA();
522 void visitModuleFlags();
523 void visitModuleFlag(const MDNode *Op,
524 DenseMap<const MDString *, const MDNode *> &SeenIDs,
525 SmallVectorImpl<const MDNode *> &Requirements);
526 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
527 void visitFunction(const Function &F);
528 void visitBasicBlock(BasicBlock &BB);
529 void verifyRangeLikeMetadata(const Value &V, const MDNode *Range, Type *Ty,
530 RangeLikeMetadataKind Kind);
531 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
532 void visitNoFPClassMetadata(Instruction &I, MDNode *Range, Type *Ty);
533 void visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range, Type *Ty);
534 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
535 void visitNofreeMetadata(Instruction &I, MDNode *MD);
536 void visitProfMetadata(Instruction &I, MDNode *MD);
537 void visitCallStackMetadata(MDNode *MD);
538 void visitMemProfMetadata(Instruction &I, MDNode *MD);
539 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
540 void visitCalleeTypeMetadata(Instruction &I, MDNode *MD);
541 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
542 void visitMMRAMetadata(Instruction &I, MDNode *MD);
543 void visitAnnotationMetadata(MDNode *Annotation);
544 void visitAliasScopeMetadata(const MDNode *MD);
545 void visitAliasScopeListMetadata(const MDNode *MD);
546 void visitAccessGroupMetadata(const MDNode *MD);
547 void visitCapturesMetadata(Instruction &I, const MDNode *Captures);
548 void visitAllocTokenMetadata(Instruction &I, MDNode *MD);
549
550 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
551#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
552#include "llvm/IR/Metadata.def"
553 void visitDIScope(const DIScope &N);
554 void visitDIVariable(const DIVariable &N);
555 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
556 void visitDITemplateParameter(const DITemplateParameter &N);
557
558 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
559
560 void visit(DbgLabelRecord &DLR);
561 void visit(DbgVariableRecord &DVR);
562 // InstVisitor overrides...
563 using InstVisitor<Verifier>::visit;
564 void visitDbgRecords(Instruction &I);
565 void visit(Instruction &I);
566
567 void visitTruncInst(TruncInst &I);
568 void visitZExtInst(ZExtInst &I);
569 void visitSExtInst(SExtInst &I);
570 void visitFPTruncInst(FPTruncInst &I);
571 void visitFPExtInst(FPExtInst &I);
572 void visitFPToUIInst(FPToUIInst &I);
573 void visitFPToSIInst(FPToSIInst &I);
574 void visitUIToFPInst(UIToFPInst &I);
575 void visitSIToFPInst(SIToFPInst &I);
576 void visitIntToPtrInst(IntToPtrInst &I);
577 void checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V);
578 void visitPtrToAddrInst(PtrToAddrInst &I);
579 void visitPtrToIntInst(PtrToIntInst &I);
580 void visitBitCastInst(BitCastInst &I);
581 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
582 void visitPHINode(PHINode &PN);
583 void visitCallBase(CallBase &Call);
584 void visitUnaryOperator(UnaryOperator &U);
585 void visitBinaryOperator(BinaryOperator &B);
586 void visitICmpInst(ICmpInst &IC);
587 void visitFCmpInst(FCmpInst &FC);
588 void visitExtractElementInst(ExtractElementInst &EI);
589 void visitInsertElementInst(InsertElementInst &EI);
590 void visitShuffleVectorInst(ShuffleVectorInst &EI);
591 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
592 void visitCallInst(CallInst &CI);
593 void visitInvokeInst(InvokeInst &II);
594 void visitGetElementPtrInst(GetElementPtrInst &GEP);
595 void visitLoadInst(LoadInst &LI);
596 void visitStoreInst(StoreInst &SI);
597 void verifyDominatesUse(Instruction &I, unsigned i);
598 void visitInstruction(Instruction &I);
599 void visitTerminator(Instruction &I);
600 void visitBranchInst(BranchInst &BI);
601 void visitReturnInst(ReturnInst &RI);
602 void visitSwitchInst(SwitchInst &SI);
603 void visitIndirectBrInst(IndirectBrInst &BI);
604 void visitCallBrInst(CallBrInst &CBI);
605 void visitSelectInst(SelectInst &SI);
606 void visitUserOp1(Instruction &I);
607 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
608 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
609 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
610 void visitVPIntrinsic(VPIntrinsic &VPI);
611 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
612 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
613 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
614 void visitFenceInst(FenceInst &FI);
615 void visitAllocaInst(AllocaInst &AI);
616 void visitExtractValueInst(ExtractValueInst &EVI);
617 void visitInsertValueInst(InsertValueInst &IVI);
618 void visitEHPadPredecessors(Instruction &I);
619 void visitLandingPadInst(LandingPadInst &LPI);
620 void visitResumeInst(ResumeInst &RI);
621 void visitCatchPadInst(CatchPadInst &CPI);
622 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
623 void visitCleanupPadInst(CleanupPadInst &CPI);
624 void visitFuncletPadInst(FuncletPadInst &FPI);
625 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
626 void visitCleanupReturnInst(CleanupReturnInst &CRI);
627
628 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
629 void verifySwiftErrorValue(const Value *SwiftErrorVal);
630 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
631 void verifyMustTailCall(CallInst &CI);
632 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
633 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
634 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
635 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
636 const Value *V);
637 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
638 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
639 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
640 void verifyUnknownProfileMetadata(MDNode *MD);
641 void visitConstantExprsRecursively(const Constant *EntryC);
642 void visitConstantExpr(const ConstantExpr *CE);
643 void visitConstantPtrAuth(const ConstantPtrAuth *CPA);
644 void verifyInlineAsmCall(const CallBase &Call);
645 void verifyStatepoint(const CallBase &Call);
646 void verifyFrameRecoverIndices();
647 void verifySiblingFuncletUnwinds();
648
649 void verifyFragmentExpression(const DbgVariableRecord &I);
650 template <typename ValueOrMetadata>
651 void verifyFragmentExpression(const DIVariable &V,
653 ValueOrMetadata *Desc);
654 void verifyFnArgs(const DbgVariableRecord &DVR);
655 void verifyNotEntryValue(const DbgVariableRecord &I);
656
657 /// Module-level debug info verification...
658 void verifyCompileUnits();
659
660 /// Module-level verification that all @llvm.experimental.deoptimize
661 /// declarations share the same calling convention.
662 void verifyDeoptimizeCallingConvs();
663
664 void verifyAttachedCallBundle(const CallBase &Call,
665 const OperandBundleUse &BU);
666
667 /// Verify the llvm.experimental.noalias.scope.decl declarations
668 void verifyNoAliasScopeDecl();
669};
670
671} // end anonymous namespace
672
673/// We know that cond should be true, if not print an error message.
674#define Check(C, ...) \
675 do { \
676 if (!(C)) { \
677 CheckFailed(__VA_ARGS__); \
678 return; \
679 } \
680 } while (false)
681
682/// We know that a debug info condition should be true, if not print
683/// an error message.
684#define CheckDI(C, ...) \
685 do { \
686 if (!(C)) { \
687 DebugInfoCheckFailed(__VA_ARGS__); \
688 return; \
689 } \
690 } while (false)
691
692void Verifier::visitDbgRecords(Instruction &I) {
693 if (!I.DebugMarker)
694 return;
695 CheckDI(I.DebugMarker->MarkedInstr == &I,
696 "Instruction has invalid DebugMarker", &I);
697 CheckDI(!isa<PHINode>(&I) || !I.hasDbgRecords(),
698 "PHI Node must not have any attached DbgRecords", &I);
699 for (DbgRecord &DR : I.getDbgRecordRange()) {
700 CheckDI(DR.getMarker() == I.DebugMarker,
701 "DbgRecord had invalid DebugMarker", &I, &DR);
702 if (auto *Loc =
704 visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
705 if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
706 visit(*DVR);
707 // These have to appear after `visit` for consistency with existing
708 // intrinsic behaviour.
709 verifyFragmentExpression(*DVR);
710 verifyNotEntryValue(*DVR);
711 } else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
712 visit(*DLR);
713 }
714 }
715}
716
717void Verifier::visit(Instruction &I) {
718 visitDbgRecords(I);
719 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
720 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
722}
723
724// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
725static void forEachUser(const Value *User,
727 llvm::function_ref<bool(const Value *)> Callback) {
728 if (!Visited.insert(User).second)
729 return;
730
732 while (!WorkList.empty()) {
733 const Value *Cur = WorkList.pop_back_val();
734 if (!Visited.insert(Cur).second)
735 continue;
736 if (Callback(Cur))
737 append_range(WorkList, Cur->materialized_users());
738 }
739}
740
741void Verifier::visitGlobalValue(const GlobalValue &GV) {
743 "Global is external, but doesn't have external or weak linkage!", &GV);
744
745 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
746 if (const MDNode *Associated =
747 GO->getMetadata(LLVMContext::MD_associated)) {
748 Check(Associated->getNumOperands() == 1,
749 "associated metadata must have one operand", &GV, Associated);
750 const Metadata *Op = Associated->getOperand(0).get();
751 Check(Op, "associated metadata must have a global value", GO, Associated);
752
753 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
754 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
755 if (VM) {
756 Check(isa<PointerType>(VM->getValue()->getType()),
757 "associated value must be pointer typed", GV, Associated);
758
759 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
760 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
761 "associated metadata must point to a GlobalObject", GO, Stripped);
762 Check(Stripped != GO,
763 "global values should not associate to themselves", GO,
764 Associated);
765 }
766 }
767
768 // FIXME: Why is getMetadata on GlobalValue protected?
769 if (const MDNode *AbsoluteSymbol =
770 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
771 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
772 DL.getIntPtrType(GO->getType()),
773 RangeLikeMetadataKind::AbsoluteSymbol);
774 }
775
776 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
777 Check(!GO->isDeclaration(),
778 "ref metadata must not be placed on a declaration", GO);
779
781 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
782 for (const MDNode *MD : MDs) {
783 Check(MD->getNumOperands() == 1, "ref metadata must have one operand",
784 &GV, MD);
785 const Metadata *Op = MD->getOperand(0).get();
786 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
787 Check(VM, "ref metadata must be ValueAsMetadata", GO, MD);
788 if (VM) {
789 Check(isa<PointerType>(VM->getValue()->getType()),
790 "ref value must be pointer typed", GV, MD);
791
792 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
793 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
794 "ref metadata must point to a GlobalObject", GO, Stripped);
795 Check(Stripped != GO, "values should not reference themselves", GO,
796 MD);
797 }
798 }
799 }
800 }
801
803 "Only global variables can have appending linkage!", &GV);
804
805 if (GV.hasAppendingLinkage()) {
806 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
807 Check(GVar && GVar->getValueType()->isArrayTy(),
808 "Only global arrays can have appending linkage!", GVar);
809 }
810
811 if (GV.isDeclarationForLinker())
812 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
813
814 if (GV.hasDLLExportStorageClass()) {
816 "dllexport GlobalValue must have default or protected visibility",
817 &GV);
818 }
819 if (GV.hasDLLImportStorageClass()) {
821 "dllimport GlobalValue must have default visibility", &GV);
822 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
823 &GV);
824
825 Check((GV.isDeclaration() &&
828 "Global is marked as dllimport, but not external", &GV);
829 }
830
831 if (GV.isImplicitDSOLocal())
832 Check(GV.isDSOLocal(),
833 "GlobalValue with local linkage or non-default "
834 "visibility must be dso_local!",
835 &GV);
836
837 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
838 if (const Instruction *I = dyn_cast<Instruction>(V)) {
839 if (!I->getParent() || !I->getParent()->getParent())
840 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
841 I);
842 else if (I->getParent()->getParent()->getParent() != &M)
843 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
844 I->getParent()->getParent(),
845 I->getParent()->getParent()->getParent());
846 return false;
847 } else if (const Function *F = dyn_cast<Function>(V)) {
848 if (F->getParent() != &M)
849 CheckFailed("Global is used by function in a different module", &GV, &M,
850 F, F->getParent());
851 return false;
852 }
853 return true;
854 });
855}
856
857void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
858 Type *GVType = GV.getValueType();
859
860 if (MaybeAlign A = GV.getAlign()) {
861 Check(A->value() <= Value::MaximumAlignment,
862 "huge alignment values are unsupported", &GV);
863 }
864
865 if (GV.hasInitializer()) {
866 Check(GV.getInitializer()->getType() == GVType,
867 "Global variable initializer type does not match global "
868 "variable type!",
869 &GV);
871 "Global variable initializer must be sized", &GV);
872 visitConstantExprsRecursively(GV.getInitializer());
873 // If the global has common linkage, it must have a zero initializer and
874 // cannot be constant.
875 if (GV.hasCommonLinkage()) {
877 "'common' global must have a zero initializer!", &GV);
878 Check(!GV.isConstant(), "'common' global may not be marked constant!",
879 &GV);
880 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
881 }
882 }
883
884 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
885 GV.getName() == "llvm.global_dtors")) {
887 "invalid linkage for intrinsic global variable", &GV);
889 "invalid uses of intrinsic global variable", &GV);
890
891 // Don't worry about emitting an error for it not being an array,
892 // visitGlobalValue will complain on appending non-array.
893 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
894 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
895 PointerType *FuncPtrTy =
896 PointerType::get(Context, DL.getProgramAddressSpace());
897 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
898 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
899 STy->getTypeAtIndex(1) == FuncPtrTy,
900 "wrong type for intrinsic global variable", &GV);
901 Check(STy->getNumElements() == 3,
902 "the third field of the element type is mandatory, "
903 "specify ptr null to migrate from the obsoleted 2-field form");
904 Type *ETy = STy->getTypeAtIndex(2);
905 Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
906 &GV);
907 }
908 }
909
910 if (GV.hasName() && (GV.getName() == "llvm.used" ||
911 GV.getName() == "llvm.compiler.used")) {
913 "invalid linkage for intrinsic global variable", &GV);
915 "invalid uses of intrinsic global variable", &GV);
916
917 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
918 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
919 Check(PTy, "wrong type for intrinsic global variable", &GV);
920 if (GV.hasInitializer()) {
921 const Constant *Init = GV.getInitializer();
922 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
923 Check(InitArray, "wrong initializer for intrinsic global variable",
924 Init);
925 for (Value *Op : InitArray->operands()) {
926 Value *V = Op->stripPointerCasts();
929 Twine("invalid ") + GV.getName() + " member", V);
930 Check(V->hasName(),
931 Twine("members of ") + GV.getName() + " must be named", V);
932 }
933 }
934 }
935 }
936
937 // Visit any debug info attachments.
939 GV.getMetadata(LLVMContext::MD_dbg, MDs);
940 for (auto *MD : MDs) {
941 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
942 visitDIGlobalVariableExpression(*GVE);
943 else
944 CheckDI(false, "!dbg attachment of global variable must be a "
945 "DIGlobalVariableExpression");
946 }
947
948 // Scalable vectors cannot be global variables, since we don't know
949 // the runtime size.
950 Check(!GVType->isScalableTy(), "Globals cannot contain scalable types", &GV);
951
952 // Check if it is or contains a target extension type that disallows being
953 // used as a global.
955 "Global @" + GV.getName() + " has illegal target extension type",
956 GVType);
957
958 // Check that the the address space can hold all bits of the type, recognized
959 // by an access in the address space being able to reach all bytes of the
960 // type.
961 Check(!GVType->isSized() ||
962 isUIntN(DL.getAddressSizeInBits(GV.getAddressSpace()),
963 GV.getGlobalSize(DL)),
964 "Global variable is too large to fit into the address space", &GV,
965 GVType);
966
967 if (!GV.hasInitializer()) {
968 visitGlobalValue(GV);
969 return;
970 }
971
972 // Walk any aggregate initializers looking for bitcasts between address spaces
973 visitConstantExprsRecursively(GV.getInitializer());
974
975 visitGlobalValue(GV);
976}
977
978void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
979 SmallPtrSet<const GlobalAlias*, 4> Visited;
980 Visited.insert(&GA);
981 visitAliaseeSubExpr(Visited, GA, C);
982}
983
984void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
985 const GlobalAlias &GA, const Constant &C) {
988 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
989 "available_externally alias must point to available_externally "
990 "global value",
991 &GA);
992 }
993 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
995 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
996 &GA);
997 }
998
999 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
1000 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
1001
1002 Check(!GA2->isInterposable(),
1003 "Alias cannot point to an interposable alias", &GA);
1004 } else {
1005 // Only continue verifying subexpressions of GlobalAliases.
1006 // Do not recurse into global initializers.
1007 return;
1008 }
1009 }
1010
1011 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
1012 visitConstantExprsRecursively(CE);
1013
1014 for (const Use &U : C.operands()) {
1015 Value *V = &*U;
1016 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
1017 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
1018 else if (const auto *C2 = dyn_cast<Constant>(V))
1019 visitAliaseeSubExpr(Visited, GA, *C2);
1020 }
1021}
1022
1023void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
1025 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
1026 "weak_odr, external, or available_externally linkage!",
1027 &GA);
1028 const Constant *Aliasee = GA.getAliasee();
1029 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
1030 Check(GA.getType() == Aliasee->getType(),
1031 "Alias and aliasee types should match!", &GA);
1032
1033 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
1034 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
1035
1036 visitAliaseeSubExpr(GA, *Aliasee);
1037
1038 visitGlobalValue(GA);
1039}
1040
1041void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
1042 visitGlobalValue(GI);
1043
1045 GI.getAllMetadata(MDs);
1046 for (const auto &I : MDs) {
1047 CheckDI(I.first != LLVMContext::MD_dbg,
1048 "an ifunc may not have a !dbg attachment", &GI);
1049 Check(I.first != LLVMContext::MD_prof,
1050 "an ifunc may not have a !prof attachment", &GI);
1051 visitMDNode(*I.second, AreDebugLocsAllowed::No);
1052 }
1053
1055 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
1056 "weak_odr, or external linkage!",
1057 &GI);
1058 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
1059 // is a Function definition.
1060 const Function *Resolver = GI.getResolverFunction();
1061 Check(Resolver, "IFunc must have a Function resolver", &GI);
1062 Check(!Resolver->isDeclarationForLinker(),
1063 "IFunc resolver must be a definition", &GI);
1064
1065 // Check that the immediate resolver operand (prior to any bitcasts) has the
1066 // correct type.
1067 const Type *ResolverTy = GI.getResolver()->getType();
1068
1070 "IFunc resolver must return a pointer", &GI);
1071
1072 Check(ResolverTy == PointerType::get(Context, GI.getAddressSpace()),
1073 "IFunc resolver has incorrect type", &GI);
1074}
1075
1076void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
1077 // There used to be various other llvm.dbg.* nodes, but we don't support
1078 // upgrading them and we want to reserve the namespace for future uses.
1079 if (NMD.getName().starts_with("llvm.dbg."))
1080 CheckDI(NMD.getName() == "llvm.dbg.cu",
1081 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
1082 for (const MDNode *MD : NMD.operands()) {
1083 if (NMD.getName() == "llvm.dbg.cu")
1084 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
1085
1086 if (!MD)
1087 continue;
1088
1089 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
1090 }
1091}
1092
1093void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
1094 // Only visit each node once. Metadata can be mutually recursive, so this
1095 // avoids infinite recursion here, as well as being an optimization.
1096 if (!MDNodes.insert(&MD).second)
1097 return;
1098
1099 Check(&MD.getContext() == &Context,
1100 "MDNode context does not match Module context!", &MD);
1101
1102 switch (MD.getMetadataID()) {
1103 default:
1104 llvm_unreachable("Invalid MDNode subclass");
1105 case Metadata::MDTupleKind:
1106 break;
1107#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1108 case Metadata::CLASS##Kind: \
1109 visit##CLASS(cast<CLASS>(MD)); \
1110 break;
1111#include "llvm/IR/Metadata.def"
1112 }
1113
1114 for (const Metadata *Op : MD.operands()) {
1115 if (!Op)
1116 continue;
1117 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
1118 &MD, Op);
1119 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1120 "DILocation not allowed within this metadata node", &MD, Op);
1121 if (auto *N = dyn_cast<MDNode>(Op)) {
1122 visitMDNode(*N, AllowLocs);
1123 continue;
1124 }
1125 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
1126 visitValueAsMetadata(*V, nullptr);
1127 continue;
1128 }
1129 }
1130
1131 // Check llvm.loop.estimated_trip_count.
1132 if (MD.getNumOperands() > 0 &&
1134 Check(MD.getNumOperands() == 2, "Expected two operands", &MD);
1136 Check(Count && Count->getType()->isIntegerTy() &&
1137 cast<IntegerType>(Count->getType())->getBitWidth() <= 32,
1138 "Expected second operand to be an integer constant of type i32 or "
1139 "smaller",
1140 &MD);
1141 }
1142
1143 // Check these last, so we diagnose problems in operands first.
1144 Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
1145 Check(MD.isResolved(), "All nodes should be resolved!", &MD);
1146}
1147
1148void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1149 Check(MD.getValue(), "Expected valid value", &MD);
1150 Check(!MD.getValue()->getType()->isMetadataTy(),
1151 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1152
1153 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1154 if (!L)
1155 return;
1156
1157 Check(F, "function-local metadata used outside a function", L);
1158
1159 // If this was an instruction, bb, or argument, verify that it is in the
1160 // function that we expect.
1161 Function *ActualF = nullptr;
1162 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
1163 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1164 ActualF = I->getParent()->getParent();
1165 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
1166 ActualF = BB->getParent();
1167 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
1168 ActualF = A->getParent();
1169 assert(ActualF && "Unimplemented function local metadata case!");
1170
1171 Check(ActualF == F, "function-local metadata used in wrong function", L);
1172}
1173
1174void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
1175 for (const ValueAsMetadata *VAM : AL.getArgs())
1176 visitValueAsMetadata(*VAM, F);
1177}
1178
1179void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1180 Metadata *MD = MDV.getMetadata();
1181 if (auto *N = dyn_cast<MDNode>(MD)) {
1182 visitMDNode(*N, AreDebugLocsAllowed::No);
1183 return;
1184 }
1185
1186 // Only visit each node once. Metadata can be mutually recursive, so this
1187 // avoids infinite recursion here, as well as being an optimization.
1188 if (!MDNodes.insert(MD).second)
1189 return;
1190
1191 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1192 visitValueAsMetadata(*V, F);
1193
1194 if (auto *AL = dyn_cast<DIArgList>(MD))
1195 visitDIArgList(*AL, F);
1196}
1197
1198static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1199static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1200static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1201static bool isMDTuple(const Metadata *MD) { return !MD || isa<MDTuple>(MD); }
1202
1203void Verifier::visitDILocation(const DILocation &N) {
1204 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1205 "location requires a valid scope", &N, N.getRawScope());
1206 if (auto *IA = N.getRawInlinedAt())
1207 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1208 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1209 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1210}
1211
1212void Verifier::visitGenericDINode(const GenericDINode &N) {
1213 CheckDI(N.getTag(), "invalid tag", &N);
1214}
1215
1216void Verifier::visitDIScope(const DIScope &N) {
1217 if (auto *F = N.getRawFile())
1218 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1219}
1220
1221void Verifier::visitDISubrangeType(const DISubrangeType &N) {
1222 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1223 auto *BaseType = N.getRawBaseType();
1224 CheckDI(!BaseType || isType(BaseType), "BaseType must be a type");
1225 auto *LBound = N.getRawLowerBound();
1226 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1227 isa<DIVariable>(LBound) || isa<DIExpression>(LBound) ||
1228 isa<DIDerivedType>(LBound),
1229 "LowerBound must be signed constant or DIVariable or DIExpression or "
1230 "DIDerivedType",
1231 &N);
1232 auto *UBound = N.getRawUpperBound();
1233 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1234 isa<DIVariable>(UBound) || isa<DIExpression>(UBound) ||
1235 isa<DIDerivedType>(UBound),
1236 "UpperBound must be signed constant or DIVariable or DIExpression or "
1237 "DIDerivedType",
1238 &N);
1239 auto *Stride = N.getRawStride();
1240 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1241 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1242 "Stride must be signed constant or DIVariable or DIExpression", &N);
1243 auto *Bias = N.getRawBias();
1244 CheckDI(!Bias || isa<ConstantAsMetadata>(Bias) || isa<DIVariable>(Bias) ||
1245 isa<DIExpression>(Bias),
1246 "Bias must be signed constant or DIVariable or DIExpression", &N);
1247 // Subrange types currently only support constant size.
1248 auto *Size = N.getRawSizeInBits();
1250 "SizeInBits must be a constant");
1251}
1252
1253void Verifier::visitDISubrange(const DISubrange &N) {
1254 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1255 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1256 "Subrange can have any one of count or upperBound", &N);
1257 auto *CBound = N.getRawCountNode();
1258 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1259 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1260 "Count must be signed constant or DIVariable or DIExpression", &N);
1261 auto Count = N.getCount();
1263 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1264 "invalid subrange count", &N);
1265 auto *LBound = N.getRawLowerBound();
1266 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1267 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1268 "LowerBound must be signed constant or DIVariable or DIExpression",
1269 &N);
1270 auto *UBound = N.getRawUpperBound();
1271 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1272 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1273 "UpperBound must be signed constant or DIVariable or DIExpression",
1274 &N);
1275 auto *Stride = N.getRawStride();
1276 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1277 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1278 "Stride must be signed constant or DIVariable or DIExpression", &N);
1279}
1280
1281void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1282 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1283 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1284 "GenericSubrange can have any one of count or upperBound", &N);
1285 auto *CBound = N.getRawCountNode();
1286 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1287 "Count must be signed constant or DIVariable or DIExpression", &N);
1288 auto *LBound = N.getRawLowerBound();
1289 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1290 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1291 "LowerBound must be signed constant or DIVariable or DIExpression",
1292 &N);
1293 auto *UBound = N.getRawUpperBound();
1294 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1295 "UpperBound must be signed constant or DIVariable or DIExpression",
1296 &N);
1297 auto *Stride = N.getRawStride();
1298 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1299 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1300 "Stride must be signed constant or DIVariable or DIExpression", &N);
1301}
1302
1303void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1304 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1305}
1306
1307void Verifier::visitDIBasicType(const DIBasicType &N) {
1308 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1309 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1310 N.getTag() == dwarf::DW_TAG_string_type,
1311 "invalid tag", &N);
1312 // Basic types currently only support constant size.
1313 auto *Size = N.getRawSizeInBits();
1315 "SizeInBits must be a constant");
1316}
1317
1318void Verifier::visitDIFixedPointType(const DIFixedPointType &N) {
1319 visitDIBasicType(N);
1320
1321 CheckDI(N.getTag() == dwarf::DW_TAG_base_type, "invalid tag", &N);
1322 CheckDI(N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1323 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1324 "invalid encoding", &N);
1328 "invalid kind", &N);
1330 N.getFactorRaw() == 0,
1331 "factor should be 0 for rationals", &N);
1333 (N.getNumeratorRaw() == 0 && N.getDenominatorRaw() == 0),
1334 "numerator and denominator should be 0 for non-rationals", &N);
1335}
1336
1337void Verifier::visitDIStringType(const DIStringType &N) {
1338 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1339 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1340 &N);
1341}
1342
1343void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1344 // Common scope checks.
1345 visitDIScope(N);
1346
1347 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1348 N.getTag() == dwarf::DW_TAG_pointer_type ||
1349 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1350 N.getTag() == dwarf::DW_TAG_reference_type ||
1351 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1352 N.getTag() == dwarf::DW_TAG_const_type ||
1353 N.getTag() == dwarf::DW_TAG_immutable_type ||
1354 N.getTag() == dwarf::DW_TAG_volatile_type ||
1355 N.getTag() == dwarf::DW_TAG_restrict_type ||
1356 N.getTag() == dwarf::DW_TAG_atomic_type ||
1357 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1358 N.getTag() == dwarf::DW_TAG_member ||
1359 (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
1360 N.getTag() == dwarf::DW_TAG_inheritance ||
1361 N.getTag() == dwarf::DW_TAG_friend ||
1362 N.getTag() == dwarf::DW_TAG_set_type ||
1363 N.getTag() == dwarf::DW_TAG_template_alias,
1364 "invalid tag", &N);
1365 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1366 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1367 N.getRawExtraData());
1368 } else if (N.getTag() == dwarf::DW_TAG_template_alias) {
1369 CheckDI(isMDTuple(N.getRawExtraData()), "invalid template parameters", &N,
1370 N.getRawExtraData());
1371 } else if (N.getTag() == dwarf::DW_TAG_inheritance ||
1372 N.getTag() == dwarf::DW_TAG_member ||
1373 N.getTag() == dwarf::DW_TAG_variable) {
1374 auto *ExtraData = N.getRawExtraData();
1375 auto IsValidExtraData = [&]() {
1376 if (ExtraData == nullptr)
1377 return true;
1378 if (isa<ConstantAsMetadata>(ExtraData) || isa<MDString>(ExtraData) ||
1379 isa<DIObjCProperty>(ExtraData))
1380 return true;
1381 if (auto *Tuple = dyn_cast<MDTuple>(ExtraData)) {
1382 if (Tuple->getNumOperands() != 1)
1383 return false;
1384 return isa_and_nonnull<ConstantAsMetadata>(Tuple->getOperand(0).get());
1385 }
1386 return false;
1387 };
1388 CheckDI(IsValidExtraData(),
1389 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1390 "or MDTuple with single ConstantAsMetadata operand",
1391 &N, ExtraData);
1392 }
1393
1394 if (N.getTag() == dwarf::DW_TAG_set_type) {
1395 if (auto *T = N.getRawBaseType()) {
1399 CheckDI(
1400 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1401 (Subrange && Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1402 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1403 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1404 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1405 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1406 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1407 "invalid set base type", &N, T);
1408 }
1409 }
1410
1411 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1412 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1413 N.getRawBaseType());
1414
1415 if (N.getDWARFAddressSpace()) {
1416 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1417 N.getTag() == dwarf::DW_TAG_reference_type ||
1418 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1419 "DWARF address space only applies to pointer or reference types",
1420 &N);
1421 }
1422
1423 auto *Size = N.getRawSizeInBits();
1426 "SizeInBits must be a constant or DIVariable or DIExpression");
1427}
1428
1429/// Detect mutually exclusive flags.
1430static bool hasConflictingReferenceFlags(unsigned Flags) {
1431 return ((Flags & DINode::FlagLValueReference) &&
1432 (Flags & DINode::FlagRValueReference)) ||
1433 ((Flags & DINode::FlagTypePassByValue) &&
1434 (Flags & DINode::FlagTypePassByReference));
1435}
1436
1437void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1438 auto *Params = dyn_cast<MDTuple>(&RawParams);
1439 CheckDI(Params, "invalid template params", &N, &RawParams);
1440 for (Metadata *Op : Params->operands()) {
1441 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1442 &N, Params, Op);
1443 }
1444}
1445
1446void Verifier::visitDICompositeType(const DICompositeType &N) {
1447 // Common scope checks.
1448 visitDIScope(N);
1449
1450 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1451 N.getTag() == dwarf::DW_TAG_structure_type ||
1452 N.getTag() == dwarf::DW_TAG_union_type ||
1453 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1454 N.getTag() == dwarf::DW_TAG_class_type ||
1455 N.getTag() == dwarf::DW_TAG_variant_part ||
1456 N.getTag() == dwarf::DW_TAG_variant ||
1457 N.getTag() == dwarf::DW_TAG_namelist,
1458 "invalid tag", &N);
1459
1460 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1461 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1462 N.getRawBaseType());
1463
1464 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1465 "invalid composite elements", &N, N.getRawElements());
1466 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1467 N.getRawVTableHolder());
1469 "invalid reference flags", &N);
1470 unsigned DIBlockByRefStruct = 1 << 4;
1471 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1472 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1473 CheckDI(llvm::all_of(N.getElements(), [](const DINode *N) { return N; }),
1474 "DISubprogram contains null entry in `elements` field", &N);
1475
1476 if (N.isVector()) {
1477 const DINodeArray Elements = N.getElements();
1478 CheckDI(Elements.size() == 1 &&
1479 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1480 "invalid vector, expected one element of type subrange", &N);
1481 }
1482
1483 if (auto *Params = N.getRawTemplateParams())
1484 visitTemplateParams(N, *Params);
1485
1486 if (auto *D = N.getRawDiscriminator()) {
1487 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1488 "discriminator can only appear on variant part");
1489 }
1490
1491 if (N.getRawDataLocation()) {
1492 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1493 "dataLocation can only appear in array type");
1494 }
1495
1496 if (N.getRawAssociated()) {
1497 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1498 "associated can only appear in array type");
1499 }
1500
1501 if (N.getRawAllocated()) {
1502 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1503 "allocated can only appear in array type");
1504 }
1505
1506 if (N.getRawRank()) {
1507 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1508 "rank can only appear in array type");
1509 }
1510
1511 if (N.getTag() == dwarf::DW_TAG_array_type) {
1512 CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
1513 }
1514
1515 auto *Size = N.getRawSizeInBits();
1518 "SizeInBits must be a constant or DIVariable or DIExpression");
1519}
1520
1521void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1522 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1523 if (auto *Types = N.getRawTypeArray()) {
1524 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1525 for (Metadata *Ty : N.getTypeArray()->operands()) {
1526 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1527 }
1528 }
1530 "invalid reference flags", &N);
1531}
1532
1533void Verifier::visitDIFile(const DIFile &N) {
1534 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1535 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1536 if (Checksum) {
1537 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1538 "invalid checksum kind", &N);
1539 size_t Size;
1540 switch (Checksum->Kind) {
1541 case DIFile::CSK_MD5:
1542 Size = 32;
1543 break;
1544 case DIFile::CSK_SHA1:
1545 Size = 40;
1546 break;
1547 case DIFile::CSK_SHA256:
1548 Size = 64;
1549 break;
1550 }
1551 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1552 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1553 "invalid checksum", &N);
1554 }
1555}
1556
1557void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1558 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1559 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1560
1561 // Don't bother verifying the compilation directory or producer string
1562 // as those could be empty.
1563 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1564 N.getRawFile());
1565 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1566 N.getFile());
1567
1568 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1569 "invalid emission kind", &N);
1570
1571 if (auto *Array = N.getRawEnumTypes()) {
1572 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1573 for (Metadata *Op : N.getEnumTypes()->operands()) {
1575 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1576 "invalid enum type", &N, N.getEnumTypes(), Op);
1577 }
1578 }
1579 if (auto *Array = N.getRawRetainedTypes()) {
1580 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1581 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1582 CheckDI(
1583 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1584 !cast<DISubprogram>(Op)->isDefinition())),
1585 "invalid retained type", &N, Op);
1586 }
1587 }
1588 if (auto *Array = N.getRawGlobalVariables()) {
1589 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1590 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1592 "invalid global variable ref", &N, Op);
1593 }
1594 }
1595 if (auto *Array = N.getRawImportedEntities()) {
1596 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1597 for (Metadata *Op : N.getImportedEntities()->operands()) {
1598 CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1599 &N, Op);
1600 }
1601 }
1602 if (auto *Array = N.getRawMacros()) {
1603 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1604 for (Metadata *Op : N.getMacros()->operands()) {
1605 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1606 }
1607 }
1608 CUVisited.insert(&N);
1609}
1610
1611void Verifier::visitDISubprogram(const DISubprogram &N) {
1612 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1613 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1614 if (auto *F = N.getRawFile())
1615 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1616 else
1617 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1618 if (auto *T = N.getRawType())
1619 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1620 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1621 N.getRawContainingType());
1622 if (auto *Params = N.getRawTemplateParams())
1623 visitTemplateParams(N, *Params);
1624 if (auto *S = N.getRawDeclaration())
1625 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1626 "invalid subprogram declaration", &N, S);
1627 if (auto *RawNode = N.getRawRetainedNodes()) {
1628 auto *Node = dyn_cast<MDTuple>(RawNode);
1629 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1630 for (Metadata *Op : Node->operands()) {
1631 CheckDI(Op, "nullptr in retained nodes", &N, Node);
1632
1633 auto True = [](const Metadata *) { return true; };
1634 auto False = [](const Metadata *) { return false; };
1635 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1636 Op, True, True, True, True, False);
1637 CheckDI(IsTypeCorrect,
1638 "invalid retained nodes, expected DILocalVariable, DILabel, "
1639 "DIImportedEntity or DIType",
1640 &N, Node, Op);
1641
1642 auto *RetainedNode = cast<DINode>(Op);
1643 auto *RetainedNodeScope = dyn_cast_or_null<DILocalScope>(
1645 CheckDI(RetainedNodeScope,
1646 "invalid retained nodes, retained node is not local", &N, Node,
1647 RetainedNode);
1648
1649 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1650 DICompileUnit *RetainedNodeUnit =
1651 RetainedNodeSP ? RetainedNodeSP->getUnit() : nullptr;
1652 CheckDI(
1653 RetainedNodeSP == &N,
1654 "invalid retained nodes, retained node does not belong to subprogram",
1655 &N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1656 RetainedNodeUnit);
1657 }
1658 }
1660 "invalid reference flags", &N);
1661
1662 auto *Unit = N.getRawUnit();
1663 if (N.isDefinition()) {
1664 // Subprogram definitions (not part of the type hierarchy).
1665 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1666 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1667 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1668 // There's no good way to cross the CU boundary to insert a nested
1669 // DISubprogram definition in one CU into a type defined in another CU.
1670 auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
1671 if (CT && CT->getRawIdentifier() &&
1672 M.getContext().isODRUniquingDebugTypes())
1673 CheckDI(N.getDeclaration(),
1674 "definition subprograms cannot be nested within DICompositeType "
1675 "when enabling ODR",
1676 &N);
1677 } else {
1678 // Subprogram declarations (part of the type hierarchy).
1679 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1680 CheckDI(!N.getRawDeclaration(),
1681 "subprogram declaration must not have a declaration field");
1682 }
1683
1684 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1685 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1686 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1687 for (Metadata *Op : ThrownTypes->operands())
1688 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1689 Op);
1690 }
1691
1692 if (N.areAllCallsDescribed())
1693 CheckDI(N.isDefinition(),
1694 "DIFlagAllCallsDescribed must be attached to a definition");
1695}
1696
1697void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1698 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1699 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1700 "invalid local scope", &N, N.getRawScope());
1701 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1702 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1703}
1704
1705void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1706 visitDILexicalBlockBase(N);
1707
1708 CheckDI(N.getLine() || !N.getColumn(),
1709 "cannot have column info without line info", &N);
1710}
1711
1712void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1713 visitDILexicalBlockBase(N);
1714}
1715
1716void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1717 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1718 if (auto *S = N.getRawScope())
1719 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1720 if (auto *S = N.getRawDecl())
1721 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1722}
1723
1724void Verifier::visitDINamespace(const DINamespace &N) {
1725 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1726 if (auto *S = N.getRawScope())
1727 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1728}
1729
1730void Verifier::visitDIMacro(const DIMacro &N) {
1731 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1732 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1733 "invalid macinfo type", &N);
1734 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1735 if (!N.getValue().empty()) {
1736 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1737 }
1738}
1739
1740void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1741 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1742 "invalid macinfo type", &N);
1743 if (auto *F = N.getRawFile())
1744 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1745
1746 if (auto *Array = N.getRawElements()) {
1747 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1748 for (Metadata *Op : N.getElements()->operands()) {
1749 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1750 }
1751 }
1752}
1753
1754void Verifier::visitDIModule(const DIModule &N) {
1755 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1756 CheckDI(!N.getName().empty(), "anonymous module", &N);
1757}
1758
1759void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1760 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1761}
1762
1763void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1764 visitDITemplateParameter(N);
1765
1766 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1767 &N);
1768}
1769
1770void Verifier::visitDITemplateValueParameter(
1771 const DITemplateValueParameter &N) {
1772 visitDITemplateParameter(N);
1773
1774 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1775 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1776 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1777 "invalid tag", &N);
1778}
1779
1780void Verifier::visitDIVariable(const DIVariable &N) {
1781 if (auto *S = N.getRawScope())
1782 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1783 if (auto *F = N.getRawFile())
1784 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1785}
1786
1787void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1788 // Checks common to all variables.
1789 visitDIVariable(N);
1790
1791 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1792 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1793 // Check only if the global variable is not an extern
1794 if (N.isDefinition())
1795 CheckDI(N.getType(), "missing global variable type", &N);
1796 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1798 "invalid static data member declaration", &N, Member);
1799 }
1800}
1801
1802void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1803 // Checks common to all variables.
1804 visitDIVariable(N);
1805
1806 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1807 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1808 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1809 "local variable requires a valid scope", &N, N.getRawScope());
1810 if (auto Ty = N.getType())
1811 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1812}
1813
1814void Verifier::visitDIAssignID(const DIAssignID &N) {
1815 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1816 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1817}
1818
1819void Verifier::visitDILabel(const DILabel &N) {
1820 if (auto *S = N.getRawScope())
1821 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1822 if (auto *F = N.getRawFile())
1823 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1824
1825 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1826 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1827 "label requires a valid scope", &N, N.getRawScope());
1828}
1829
1830void Verifier::visitDIExpression(const DIExpression &N) {
1831 CheckDI(N.isValid(), "invalid expression", &N);
1832}
1833
1834void Verifier::visitDIGlobalVariableExpression(
1835 const DIGlobalVariableExpression &GVE) {
1836 CheckDI(GVE.getVariable(), "missing variable");
1837 if (auto *Var = GVE.getVariable())
1838 visitDIGlobalVariable(*Var);
1839 if (auto *Expr = GVE.getExpression()) {
1840 visitDIExpression(*Expr);
1841 if (auto Fragment = Expr->getFragmentInfo())
1842 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1843 }
1844}
1845
1846void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1847 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1848 if (auto *T = N.getRawType())
1849 CheckDI(isType(T), "invalid type ref", &N, T);
1850 if (auto *F = N.getRawFile())
1851 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1852}
1853
1854void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1855 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1856 N.getTag() == dwarf::DW_TAG_imported_declaration,
1857 "invalid tag", &N);
1858 if (auto *S = N.getRawScope())
1859 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1860 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1861 N.getRawEntity());
1862}
1863
1864void Verifier::visitComdat(const Comdat &C) {
1865 // In COFF the Module is invalid if the GlobalValue has private linkage.
1866 // Entities with private linkage don't have entries in the symbol table.
1867 if (TT.isOSBinFormatCOFF())
1868 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1869 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1870 GV);
1871}
1872
1873void Verifier::visitModuleIdents() {
1874 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1875 if (!Idents)
1876 return;
1877
1878 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1879 // Scan each llvm.ident entry and make sure that this requirement is met.
1880 for (const MDNode *N : Idents->operands()) {
1881 Check(N->getNumOperands() == 1,
1882 "incorrect number of operands in llvm.ident metadata", N);
1883 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1884 ("invalid value for llvm.ident metadata entry operand"
1885 "(the operand should be a string)"),
1886 N->getOperand(0));
1887 }
1888}
1889
1890void Verifier::visitModuleCommandLines() {
1891 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1892 if (!CommandLines)
1893 return;
1894
1895 // llvm.commandline takes a list of metadata entry. Each entry has only one
1896 // string. Scan each llvm.commandline entry and make sure that this
1897 // requirement is met.
1898 for (const MDNode *N : CommandLines->operands()) {
1899 Check(N->getNumOperands() == 1,
1900 "incorrect number of operands in llvm.commandline metadata", N);
1901 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
1902 ("invalid value for llvm.commandline metadata entry operand"
1903 "(the operand should be a string)"),
1904 N->getOperand(0));
1905 }
1906}
1907
1908void Verifier::visitModuleErrnoTBAA() {
1909 const NamedMDNode *ErrnoTBAA = M.getNamedMetadata("llvm.errno.tbaa");
1910 if (!ErrnoTBAA)
1911 return;
1912
1913 Check(ErrnoTBAA->getNumOperands() >= 1,
1914 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1915
1916 for (const MDNode *N : ErrnoTBAA->operands())
1917 TBAAVerifyHelper.visitTBAAMetadata(nullptr, N);
1918}
1919
1920void Verifier::visitModuleFlags() {
1921 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1922 if (!Flags) return;
1923
1924 // Scan each flag, and track the flags and requirements.
1925 DenseMap<const MDString*, const MDNode*> SeenIDs;
1926 SmallVector<const MDNode*, 16> Requirements;
1927 uint64_t PAuthABIPlatform = -1;
1928 uint64_t PAuthABIVersion = -1;
1929 for (const MDNode *MDN : Flags->operands()) {
1930 visitModuleFlag(MDN, SeenIDs, Requirements);
1931 if (MDN->getNumOperands() != 3)
1932 continue;
1933 if (const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
1934 if (FlagName->getString() == "aarch64-elf-pauthabi-platform") {
1935 if (const auto *PAP =
1937 PAuthABIPlatform = PAP->getZExtValue();
1938 } else if (FlagName->getString() == "aarch64-elf-pauthabi-version") {
1939 if (const auto *PAV =
1941 PAuthABIVersion = PAV->getZExtValue();
1942 }
1943 }
1944 }
1945
1946 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1947 CheckFailed("either both or no 'aarch64-elf-pauthabi-platform' and "
1948 "'aarch64-elf-pauthabi-version' module flags must be present");
1949
1950 // Validate that the requirements in the module are valid.
1951 for (const MDNode *Requirement : Requirements) {
1952 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1953 const Metadata *ReqValue = Requirement->getOperand(1);
1954
1955 const MDNode *Op = SeenIDs.lookup(Flag);
1956 if (!Op) {
1957 CheckFailed("invalid requirement on flag, flag is not present in module",
1958 Flag);
1959 continue;
1960 }
1961
1962 if (Op->getOperand(2) != ReqValue) {
1963 CheckFailed(("invalid requirement on flag, "
1964 "flag does not have the required value"),
1965 Flag);
1966 continue;
1967 }
1968 }
1969}
1970
1971void
1972Verifier::visitModuleFlag(const MDNode *Op,
1973 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1974 SmallVectorImpl<const MDNode *> &Requirements) {
1975 // Each module flag should have three arguments, the merge behavior (a
1976 // constant int), the flag ID (an MDString), and the value.
1977 Check(Op->getNumOperands() == 3,
1978 "incorrect number of operands in module flag", Op);
1979 Module::ModFlagBehavior MFB;
1980 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1982 "invalid behavior operand in module flag (expected constant integer)",
1983 Op->getOperand(0));
1984 Check(false,
1985 "invalid behavior operand in module flag (unexpected constant)",
1986 Op->getOperand(0));
1987 }
1988 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1989 Check(ID, "invalid ID operand in module flag (expected metadata string)",
1990 Op->getOperand(1));
1991
1992 // Check the values for behaviors with additional requirements.
1993 switch (MFB) {
1994 case Module::Error:
1995 case Module::Warning:
1996 case Module::Override:
1997 // These behavior types accept any value.
1998 break;
1999
2000 case Module::Min: {
2001 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
2002 Check(V && V->getValue().isNonNegative(),
2003 "invalid value for 'min' module flag (expected constant non-negative "
2004 "integer)",
2005 Op->getOperand(2));
2006 break;
2007 }
2008
2009 case Module::Max: {
2011 "invalid value for 'max' module flag (expected constant integer)",
2012 Op->getOperand(2));
2013 break;
2014 }
2015
2016 case Module::Require: {
2017 // The value should itself be an MDNode with two operands, a flag ID (an
2018 // MDString), and a value.
2019 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
2020 Check(Value && Value->getNumOperands() == 2,
2021 "invalid value for 'require' module flag (expected metadata pair)",
2022 Op->getOperand(2));
2023 Check(isa<MDString>(Value->getOperand(0)),
2024 ("invalid value for 'require' module flag "
2025 "(first value operand should be a string)"),
2026 Value->getOperand(0));
2027
2028 // Append it to the list of requirements, to check once all module flags are
2029 // scanned.
2030 Requirements.push_back(Value);
2031 break;
2032 }
2033
2034 case Module::Append:
2035 case Module::AppendUnique: {
2036 // These behavior types require the operand be an MDNode.
2037 Check(isa<MDNode>(Op->getOperand(2)),
2038 "invalid value for 'append'-type module flag "
2039 "(expected a metadata node)",
2040 Op->getOperand(2));
2041 break;
2042 }
2043 }
2044
2045 // Unless this is a "requires" flag, check the ID is unique.
2046 if (MFB != Module::Require) {
2047 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
2048 Check(Inserted,
2049 "module flag identifiers must be unique (or of 'require' type)", ID);
2050 }
2051
2052 if (ID->getString() == "wchar_size") {
2053 ConstantInt *Value
2055 Check(Value, "wchar_size metadata requires constant integer argument");
2056 }
2057
2058 if (ID->getString() == "Linker Options") {
2059 // If the llvm.linker.options named metadata exists, we assume that the
2060 // bitcode reader has upgraded the module flag. Otherwise the flag might
2061 // have been created by a client directly.
2062 Check(M.getNamedMetadata("llvm.linker.options"),
2063 "'Linker Options' named metadata no longer supported");
2064 }
2065
2066 if (ID->getString() == "SemanticInterposition") {
2067 ConstantInt *Value =
2069 Check(Value,
2070 "SemanticInterposition metadata requires constant integer argument");
2071 }
2072
2073 if (ID->getString() == "CG Profile") {
2074 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
2075 visitModuleFlagCGProfileEntry(MDO);
2076 }
2077}
2078
2079void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
2080 auto CheckFunction = [&](const MDOperand &FuncMDO) {
2081 if (!FuncMDO)
2082 return;
2083 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
2084 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
2085 "expected a Function or null", FuncMDO);
2086 };
2087 auto Node = dyn_cast_or_null<MDNode>(MDO);
2088 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
2089 CheckFunction(Node->getOperand(0));
2090 CheckFunction(Node->getOperand(1));
2091 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
2092 Check(Count && Count->getType()->isIntegerTy(),
2093 "expected an integer constant", Node->getOperand(2));
2094}
2095
2096void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
2097 for (Attribute A : Attrs) {
2098
2099 if (A.isStringAttribute()) {
2100#define GET_ATTR_NAMES
2101#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2102#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2103 if (A.getKindAsString() == #DISPLAY_NAME) { \
2104 auto V = A.getValueAsString(); \
2105 if (!(V.empty() || V == "true" || V == "false")) \
2106 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2107 ""); \
2108 }
2109
2110#include "llvm/IR/Attributes.inc"
2111 continue;
2112 }
2113
2114 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
2115 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
2116 V);
2117 return;
2118 }
2119 }
2120}
2121
2122// VerifyParameterAttrs - Check the given attributes for an argument or return
2123// value of the specified type. The value V is printed in error messages.
2124void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
2125 const Value *V) {
2126 if (!Attrs.hasAttributes())
2127 return;
2128
2129 verifyAttributeTypes(Attrs, V);
2130
2131 for (Attribute Attr : Attrs)
2132 Check(Attr.isStringAttribute() ||
2133 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2134 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
2135 V);
2136
2137 if (Attrs.hasAttribute(Attribute::ImmArg)) {
2138 unsigned AttrCount =
2139 Attrs.getNumAttributes() - Attrs.hasAttribute(Attribute::Range);
2140 Check(AttrCount == 1,
2141 "Attribute 'immarg' is incompatible with other attributes except the "
2142 "'range' attribute",
2143 V);
2144 }
2145
2146 // Check for mutually incompatible attributes. Only inreg is compatible with
2147 // sret.
2148 unsigned AttrCount = 0;
2149 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
2150 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
2151 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
2152 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
2153 Attrs.hasAttribute(Attribute::InReg);
2154 AttrCount += Attrs.hasAttribute(Attribute::Nest);
2155 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
2156 Check(AttrCount <= 1,
2157 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2158 "'byref', and 'sret' are incompatible!",
2159 V);
2160
2161 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
2162 Attrs.hasAttribute(Attribute::ReadOnly)),
2163 "Attributes "
2164 "'inalloca and readonly' are incompatible!",
2165 V);
2166
2167 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
2168 Attrs.hasAttribute(Attribute::Returned)),
2169 "Attributes "
2170 "'sret and returned' are incompatible!",
2171 V);
2172
2173 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
2174 Attrs.hasAttribute(Attribute::SExt)),
2175 "Attributes "
2176 "'zeroext and signext' are incompatible!",
2177 V);
2178
2179 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2180 Attrs.hasAttribute(Attribute::ReadOnly)),
2181 "Attributes "
2182 "'readnone and readonly' are incompatible!",
2183 V);
2184
2185 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2186 Attrs.hasAttribute(Attribute::WriteOnly)),
2187 "Attributes "
2188 "'readnone and writeonly' are incompatible!",
2189 V);
2190
2191 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
2192 Attrs.hasAttribute(Attribute::WriteOnly)),
2193 "Attributes "
2194 "'readonly and writeonly' are incompatible!",
2195 V);
2196
2197 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
2198 Attrs.hasAttribute(Attribute::AlwaysInline)),
2199 "Attributes "
2200 "'noinline and alwaysinline' are incompatible!",
2201 V);
2202
2203 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2204 Attrs.hasAttribute(Attribute::ReadNone)),
2205 "Attributes writable and readnone are incompatible!", V);
2206
2207 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2208 Attrs.hasAttribute(Attribute::ReadOnly)),
2209 "Attributes writable and readonly are incompatible!", V);
2210
2211 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2212 for (Attribute Attr : Attrs) {
2213 if (!Attr.isStringAttribute() &&
2214 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
2215 CheckFailed("Attribute '" + Attr.getAsString() +
2216 "' applied to incompatible type!", V);
2217 return;
2218 }
2219 }
2220
2221 if (isa<PointerType>(Ty)) {
2222 if (Attrs.hasAttribute(Attribute::Alignment)) {
2223 Align AttrAlign = Attrs.getAlignment().valueOrOne();
2224 Check(AttrAlign.value() <= Value::MaximumAlignment,
2225 "huge alignment values are unsupported", V);
2226 }
2227 if (Attrs.hasAttribute(Attribute::ByVal)) {
2228 Type *ByValTy = Attrs.getByValType();
2229 SmallPtrSet<Type *, 4> Visited;
2230 Check(ByValTy->isSized(&Visited),
2231 "Attribute 'byval' does not support unsized types!", V);
2232 // Check if it is or contains a target extension type that disallows being
2233 // used on the stack.
2235 "'byval' argument has illegal target extension type", V);
2236 Check(DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2237 "huge 'byval' arguments are unsupported", V);
2238 }
2239 if (Attrs.hasAttribute(Attribute::ByRef)) {
2240 SmallPtrSet<Type *, 4> Visited;
2241 Check(Attrs.getByRefType()->isSized(&Visited),
2242 "Attribute 'byref' does not support unsized types!", V);
2243 Check(DL.getTypeAllocSize(Attrs.getByRefType()).getKnownMinValue() <
2244 (1ULL << 32),
2245 "huge 'byref' arguments are unsupported", V);
2246 }
2247 if (Attrs.hasAttribute(Attribute::InAlloca)) {
2248 SmallPtrSet<Type *, 4> Visited;
2249 Check(Attrs.getInAllocaType()->isSized(&Visited),
2250 "Attribute 'inalloca' does not support unsized types!", V);
2251 Check(DL.getTypeAllocSize(Attrs.getInAllocaType()).getKnownMinValue() <
2252 (1ULL << 32),
2253 "huge 'inalloca' arguments are unsupported", V);
2254 }
2255 if (Attrs.hasAttribute(Attribute::Preallocated)) {
2256 SmallPtrSet<Type *, 4> Visited;
2257 Check(Attrs.getPreallocatedType()->isSized(&Visited),
2258 "Attribute 'preallocated' does not support unsized types!", V);
2259 Check(
2260 DL.getTypeAllocSize(Attrs.getPreallocatedType()).getKnownMinValue() <
2261 (1ULL << 32),
2262 "huge 'preallocated' arguments are unsupported", V);
2263 }
2264 }
2265
2266 if (Attrs.hasAttribute(Attribute::Initializes)) {
2267 auto Inits = Attrs.getAttribute(Attribute::Initializes).getInitializes();
2268 Check(!Inits.empty(), "Attribute 'initializes' does not support empty list",
2269 V);
2271 "Attribute 'initializes' does not support unordered ranges", V);
2272 }
2273
2274 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
2275 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2276 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
2277 V);
2278 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
2279 "Invalid value for 'nofpclass' test mask", V);
2280 }
2281 if (Attrs.hasAttribute(Attribute::Range)) {
2282 const ConstantRange &CR =
2283 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2285 "Range bit width must match type bit width!", V);
2286 }
2287}
2288
2289void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2290 const Value *V) {
2291 if (Attrs.hasFnAttr(Attr)) {
2292 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
2293 unsigned N;
2294 if (S.getAsInteger(10, N))
2295 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
2296 }
2297}
2298
2299// Check parameter attributes against a function type.
2300// The value V is printed in error messages.
2301void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2302 const Value *V, bool IsIntrinsic,
2303 bool IsInlineAsm) {
2304 if (Attrs.isEmpty())
2305 return;
2306
2307 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
2308 Check(Attrs.hasParentContext(Context),
2309 "Attribute list does not match Module context!", &Attrs, V);
2310 for (const auto &AttrSet : Attrs) {
2311 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2312 "Attribute set does not match Module context!", &AttrSet, V);
2313 for (const auto &A : AttrSet) {
2314 Check(A.hasParentContext(Context),
2315 "Attribute does not match Module context!", &A, V);
2316 }
2317 }
2318 }
2319
2320 bool SawNest = false;
2321 bool SawReturned = false;
2322 bool SawSRet = false;
2323 bool SawSwiftSelf = false;
2324 bool SawSwiftAsync = false;
2325 bool SawSwiftError = false;
2326
2327 // Verify return value attributes.
2328 AttributeSet RetAttrs = Attrs.getRetAttrs();
2329 for (Attribute RetAttr : RetAttrs)
2330 Check(RetAttr.isStringAttribute() ||
2331 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2332 "Attribute '" + RetAttr.getAsString() +
2333 "' does not apply to function return values",
2334 V);
2335
2336 unsigned MaxParameterWidth = 0;
2337 auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
2338 if (Ty->isVectorTy()) {
2339 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2340 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2341 if (Size > MaxParameterWidth)
2342 MaxParameterWidth = Size;
2343 }
2344 }
2345 };
2346 GetMaxParameterWidth(FT->getReturnType());
2347 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2348
2349 // Verify parameter attributes.
2350 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2351 Type *Ty = FT->getParamType(i);
2352 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2353
2354 if (!IsIntrinsic) {
2355 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2356 "immarg attribute only applies to intrinsics", V);
2357 if (!IsInlineAsm)
2358 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2359 "Attribute 'elementtype' can only be applied to intrinsics"
2360 " and inline asm.",
2361 V);
2362 }
2363
2364 verifyParameterAttrs(ArgAttrs, Ty, V);
2365 GetMaxParameterWidth(Ty);
2366
2367 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2368 Check(!SawNest, "More than one parameter has attribute nest!", V);
2369 SawNest = true;
2370 }
2371
2372 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2373 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2374 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2375 "Incompatible argument and return types for 'returned' attribute",
2376 V);
2377 SawReturned = true;
2378 }
2379
2380 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2381 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2382 Check(i == 0 || i == 1,
2383 "Attribute 'sret' is not on first or second parameter!", V);
2384 SawSRet = true;
2385 }
2386
2387 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2388 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2389 SawSwiftSelf = true;
2390 }
2391
2392 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2393 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2394 SawSwiftAsync = true;
2395 }
2396
2397 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2398 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2399 SawSwiftError = true;
2400 }
2401
2402 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2403 Check(i == FT->getNumParams() - 1,
2404 "inalloca isn't on the last parameter!", V);
2405 }
2406 }
2407
2408 if (!Attrs.hasFnAttrs())
2409 return;
2410
2411 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2412 for (Attribute FnAttr : Attrs.getFnAttrs())
2413 Check(FnAttr.isStringAttribute() ||
2414 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2415 "Attribute '" + FnAttr.getAsString() +
2416 "' does not apply to functions!",
2417 V);
2418
2419 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2420 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2421 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2422
2423 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2424 Check(Attrs.hasFnAttr(Attribute::NoInline),
2425 "Attribute 'optnone' requires 'noinline'!", V);
2426
2427 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2428 "Attributes 'optsize and optnone' are incompatible!", V);
2429
2430 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2431 "Attributes 'minsize and optnone' are incompatible!", V);
2432
2433 Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2434 "Attributes 'optdebug and optnone' are incompatible!", V);
2435 }
2436
2437 Check(!(Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2438 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2439 "Attributes "
2440 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2441 V);
2442
2443 if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2444 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2445 "Attributes 'optsize and optdebug' are incompatible!", V);
2446
2447 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2448 "Attributes 'minsize and optdebug' are incompatible!", V);
2449 }
2450
2451 Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
2452 isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2453 "Attribute writable and memory without argmem: write are incompatible!",
2454 V);
2455
2456 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2457 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2458 "Attributes 'aarch64_pstate_sm_enabled and "
2459 "aarch64_pstate_sm_compatible' are incompatible!",
2460 V);
2461 }
2462
2463 Check((Attrs.hasFnAttr("aarch64_new_za") + Attrs.hasFnAttr("aarch64_in_za") +
2464 Attrs.hasFnAttr("aarch64_inout_za") +
2465 Attrs.hasFnAttr("aarch64_out_za") +
2466 Attrs.hasFnAttr("aarch64_preserves_za") +
2467 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2468 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2469 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2470 "'aarch64_za_state_agnostic' are mutually exclusive",
2471 V);
2472
2473 Check((Attrs.hasFnAttr("aarch64_new_zt0") +
2474 Attrs.hasFnAttr("aarch64_in_zt0") +
2475 Attrs.hasFnAttr("aarch64_inout_zt0") +
2476 Attrs.hasFnAttr("aarch64_out_zt0") +
2477 Attrs.hasFnAttr("aarch64_preserves_zt0") +
2478 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2479 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2480 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2481 "'aarch64_za_state_agnostic' are mutually exclusive",
2482 V);
2483
2484 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2485 const GlobalValue *GV = cast<GlobalValue>(V);
2487 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2488 }
2489
2490 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2491 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2492 if (ParamNo >= FT->getNumParams()) {
2493 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2494 return false;
2495 }
2496
2497 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2498 CheckFailed("'allocsize' " + Name +
2499 " argument must refer to an integer parameter",
2500 V);
2501 return false;
2502 }
2503
2504 return true;
2505 };
2506
2507 if (!CheckParam("element size", Args->first))
2508 return;
2509
2510 if (Args->second && !CheckParam("number of elements", *Args->second))
2511 return;
2512 }
2513
2514 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2515 AllocFnKind K = Attrs.getAllocKind();
2517 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2518 if (!is_contained(
2519 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2520 Type))
2521 CheckFailed(
2522 "'allockind()' requires exactly one of alloc, realloc, and free");
2523 if ((Type == AllocFnKind::Free) &&
2524 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2525 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2526 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2527 "or aligned modifiers.");
2528 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2529 if ((K & ZeroedUninit) == ZeroedUninit)
2530 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2531 }
2532
2533 if (Attribute A = Attrs.getFnAttr("alloc-variant-zeroed"); A.isValid()) {
2534 StringRef S = A.getValueAsString();
2535 Check(!S.empty(), "'alloc-variant-zeroed' must not be empty");
2536 Function *Variant = M.getFunction(S);
2537 if (Variant) {
2538 Attribute Family = Attrs.getFnAttr("alloc-family");
2539 Attribute VariantFamily = Variant->getFnAttribute("alloc-family");
2540 if (Family.isValid())
2541 Check(VariantFamily.isValid() &&
2542 VariantFamily.getValueAsString() == Family.getValueAsString(),
2543 "'alloc-variant-zeroed' must name a function belonging to the "
2544 "same 'alloc-family'");
2545
2546 Check(Variant->hasFnAttribute(Attribute::AllocKind) &&
2547 (Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2548 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2549 "'alloc-variant-zeroed' must name a function with "
2550 "'allockind(\"zeroed\")'");
2551
2552 Check(FT == Variant->getFunctionType(),
2553 "'alloc-variant-zeroed' must name a function with the same "
2554 "signature");
2555
2556 if (const Function *F = dyn_cast<Function>(V))
2557 Check(F->getCallingConv() == Variant->getCallingConv(),
2558 "'alloc-variant-zeroed' must name a function with the same "
2559 "calling convention");
2560 }
2561 }
2562
2563 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2564 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2565 if (VScaleMin == 0)
2566 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2567 else if (!isPowerOf2_32(VScaleMin))
2568 CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2569 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2570 if (VScaleMax && VScaleMin > VScaleMax)
2571 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2572 else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
2573 CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2574 }
2575
2576 if (Attribute FPAttr = Attrs.getFnAttr("frame-pointer"); FPAttr.isValid()) {
2577 StringRef FP = FPAttr.getValueAsString();
2578 if (FP != "all" && FP != "non-leaf" && FP != "none" && FP != "reserved" &&
2579 FP != "non-leaf-no-reserve")
2580 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2581 }
2582
2583 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2584 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2585 if (Attrs.hasFnAttr("patchable-function-entry-section"))
2586 Check(!Attrs.getFnAttr("patchable-function-entry-section")
2587 .getValueAsString()
2588 .empty(),
2589 "\"patchable-function-entry-section\" must not be empty");
2590 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2591
2592 if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
2593 StringRef S = A.getValueAsString();
2594 if (S != "none" && S != "all" && S != "non-leaf")
2595 CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
2596 }
2597
2598 if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
2599 StringRef S = A.getValueAsString();
2600 if (S != "a_key" && S != "b_key")
2601 CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
2602 V);
2603 if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
2604 CheckFailed(
2605 "'sign-return-address-key' present without `sign-return-address`");
2606 }
2607 }
2608
2609 if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
2610 StringRef S = A.getValueAsString();
2611 if (S != "" && S != "true" && S != "false")
2612 CheckFailed(
2613 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2614 }
2615
2616 if (auto A = Attrs.getFnAttr("branch-protection-pauth-lr"); A.isValid()) {
2617 StringRef S = A.getValueAsString();
2618 if (S != "" && S != "true" && S != "false")
2619 CheckFailed(
2620 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2621 }
2622
2623 if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
2624 StringRef S = A.getValueAsString();
2625 if (S != "" && S != "true" && S != "false")
2626 CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
2627 V);
2628 }
2629
2630 if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
2631 StringRef S = A.getValueAsString();
2632 const std::optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, FT);
2633 if (!Info)
2634 CheckFailed("invalid name for a VFABI variant: " + S, V);
2635 }
2636
2637 if (auto A = Attrs.getFnAttr("modular-format"); A.isValid()) {
2638 StringRef S = A.getValueAsString();
2640 S.split(Args, ',');
2641 Check(Args.size() >= 5,
2642 "modular-format attribute requires at least 5 arguments", V);
2643 unsigned FirstArgIdx;
2644 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2645 "modular-format attribute first arg index is not an integer", V);
2646 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2647 Check(FirstArgIdx > 0 && FirstArgIdx <= UpperBound,
2648 "modular-format attribute first arg index is out of bounds", V);
2649 }
2650
2651 if (auto A = Attrs.getFnAttr("target-features"); A.isValid()) {
2652 StringRef S = A.getValueAsString();
2653 if (!S.empty()) {
2654 for (auto FeatureFlag : split(S, ',')) {
2655 if (FeatureFlag.empty())
2656 CheckFailed(
2657 "target-features attribute should not contain an empty string");
2658 else
2659 Check(FeatureFlag[0] == '+' || FeatureFlag[0] == '-',
2660 "target feature '" + FeatureFlag +
2661 "' must start with a '+' or '-'",
2662 V);
2663 }
2664 }
2665 }
2666}
2667void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2668 Check(MD->getNumOperands() == 2,
2669 "'unknown' !prof should have a single additional operand", MD);
2670 auto *PassName = dyn_cast<MDString>(MD->getOperand(1));
2671 Check(PassName != nullptr,
2672 "'unknown' !prof should have an additional operand of type "
2673 "string");
2674 Check(!PassName->getString().empty(),
2675 "the 'unknown' !prof operand should not be an empty string");
2676}
2677
2678void Verifier::verifyFunctionMetadata(
2679 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2680 for (const auto &Pair : MDs) {
2681 if (Pair.first == LLVMContext::MD_prof) {
2682 MDNode *MD = Pair.second;
2683 Check(MD->getNumOperands() >= 2,
2684 "!prof annotations should have no less than 2 operands", MD);
2685 // We may have functions that are synthesized by the compiler, e.g. in
2686 // WPD, that we can't currently determine the entry count.
2687 if (MD->getOperand(0).equalsStr(
2689 verifyUnknownProfileMetadata(MD);
2690 continue;
2691 }
2692
2693 // Check first operand.
2694 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
2695 MD);
2697 "expected string with name of the !prof annotation", MD);
2698 MDString *MDS = cast<MDString>(MD->getOperand(0));
2699 StringRef ProfName = MDS->getString();
2702 "first operand should be 'function_entry_count'"
2703 " or 'synthetic_function_entry_count'",
2704 MD);
2705
2706 // Check second operand.
2707 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
2708 MD);
2710 "expected integer argument to function_entry_count", MD);
2711 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2712 MDNode *MD = Pair.second;
2713 Check(MD->getNumOperands() == 1,
2714 "!kcfi_type must have exactly one operand", MD);
2715 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2716 MD);
2718 "expected a constant operand for !kcfi_type", MD);
2719 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2720 Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2721 "expected a constant integer operand for !kcfi_type", MD);
2723 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2724 }
2725 }
2726}
2727
2728void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2729 if (EntryC->getNumOperands() == 0)
2730 return;
2731
2732 if (!ConstantExprVisited.insert(EntryC).second)
2733 return;
2734
2736 Stack.push_back(EntryC);
2737
2738 while (!Stack.empty()) {
2739 const Constant *C = Stack.pop_back_val();
2740
2741 // Check this constant expression.
2742 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2743 visitConstantExpr(CE);
2744
2745 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
2746 visitConstantPtrAuth(CPA);
2747
2748 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2749 // Global Values get visited separately, but we do need to make sure
2750 // that the global value is in the correct module
2751 Check(GV->getParent() == &M, "Referencing global in another module!",
2752 EntryC, &M, GV, GV->getParent());
2753 continue;
2754 }
2755
2756 // Visit all sub-expressions.
2757 for (const Use &U : C->operands()) {
2758 const auto *OpC = dyn_cast<Constant>(U);
2759 if (!OpC)
2760 continue;
2761 if (!ConstantExprVisited.insert(OpC).second)
2762 continue;
2763 Stack.push_back(OpC);
2764 }
2765 }
2766}
2767
2768void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2769 if (CE->getOpcode() == Instruction::BitCast)
2770 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2771 CE->getType()),
2772 "Invalid bitcast", CE);
2773 else if (CE->getOpcode() == Instruction::PtrToAddr)
2774 checkPtrToAddr(CE->getOperand(0)->getType(), CE->getType(), *CE);
2775}
2776
2777void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
2778 Check(CPA->getPointer()->getType()->isPointerTy(),
2779 "signed ptrauth constant base pointer must have pointer type");
2780
2781 Check(CPA->getType() == CPA->getPointer()->getType(),
2782 "signed ptrauth constant must have same type as its base pointer");
2783
2784 Check(CPA->getKey()->getBitWidth() == 32,
2785 "signed ptrauth constant key must be i32 constant integer");
2786
2788 "signed ptrauth constant address discriminator must be a pointer");
2789
2790 Check(CPA->getDiscriminator()->getBitWidth() == 64,
2791 "signed ptrauth constant discriminator must be i64 constant integer");
2792
2794 "signed ptrauth constant deactivation symbol must be a pointer");
2795
2798 "signed ptrauth constant deactivation symbol must be a global value "
2799 "or null");
2800}
2801
2802bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2803 // There shouldn't be more attribute sets than there are parameters plus the
2804 // function and return value.
2805 return Attrs.getNumAttrSets() <= Params + 2;
2806}
2807
2808void Verifier::verifyInlineAsmCall(const CallBase &Call) {
2809 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
2810 unsigned ArgNo = 0;
2811 unsigned LabelNo = 0;
2812 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2813 if (CI.Type == InlineAsm::isLabel) {
2814 ++LabelNo;
2815 continue;
2816 }
2817
2818 // Only deal with constraints that correspond to call arguments.
2819 if (!CI.hasArg())
2820 continue;
2821
2822 if (CI.isIndirect) {
2823 const Value *Arg = Call.getArgOperand(ArgNo);
2824 Check(Arg->getType()->isPointerTy(),
2825 "Operand for indirect constraint must have pointer type", &Call);
2826
2828 "Operand for indirect constraint must have elementtype attribute",
2829 &Call);
2830 } else {
2831 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
2832 "Elementtype attribute can only be applied for indirect "
2833 "constraints",
2834 &Call);
2835 }
2836
2837 ArgNo++;
2838 }
2839
2840 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2841 Check(LabelNo == CallBr->getNumIndirectDests(),
2842 "Number of label constraints does not match number of callbr dests",
2843 &Call);
2844 } else {
2845 Check(LabelNo == 0, "Label constraints can only be used with callbr",
2846 &Call);
2847 }
2848}
2849
2850/// Verify that statepoint intrinsic is well formed.
2851void Verifier::verifyStatepoint(const CallBase &Call) {
2852 assert(Call.getIntrinsicID() == Intrinsic::experimental_gc_statepoint);
2853
2856 "gc.statepoint must read and write all memory to preserve "
2857 "reordering restrictions required by safepoint semantics",
2858 Call);
2859
2860 const int64_t NumPatchBytes =
2861 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2862 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2863 Check(NumPatchBytes >= 0,
2864 "gc.statepoint number of patchable bytes must be "
2865 "positive",
2866 Call);
2867
2868 Type *TargetElemType = Call.getParamElementType(2);
2869 Check(TargetElemType,
2870 "gc.statepoint callee argument must have elementtype attribute", Call);
2871 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2872 Check(TargetFuncType,
2873 "gc.statepoint callee elementtype must be function type", Call);
2874
2875 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2876 Check(NumCallArgs >= 0,
2877 "gc.statepoint number of arguments to underlying call "
2878 "must be positive",
2879 Call);
2880 const int NumParams = (int)TargetFuncType->getNumParams();
2881 if (TargetFuncType->isVarArg()) {
2882 Check(NumCallArgs >= NumParams,
2883 "gc.statepoint mismatch in number of vararg call args", Call);
2884
2885 // TODO: Remove this limitation
2886 Check(TargetFuncType->getReturnType()->isVoidTy(),
2887 "gc.statepoint doesn't support wrapping non-void "
2888 "vararg functions yet",
2889 Call);
2890 } else
2891 Check(NumCallArgs == NumParams,
2892 "gc.statepoint mismatch in number of call args", Call);
2893
2894 const uint64_t Flags
2895 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2896 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2897 "unknown flag used in gc.statepoint flags argument", Call);
2898
2899 // Verify that the types of the call parameter arguments match
2900 // the type of the wrapped callee.
2901 AttributeList Attrs = Call.getAttributes();
2902 for (int i = 0; i < NumParams; i++) {
2903 Type *ParamType = TargetFuncType->getParamType(i);
2904 Type *ArgType = Call.getArgOperand(5 + i)->getType();
2905 Check(ArgType == ParamType,
2906 "gc.statepoint call argument does not match wrapped "
2907 "function type",
2908 Call);
2909
2910 if (TargetFuncType->isVarArg()) {
2911 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2912 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
2913 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2914 }
2915 }
2916
2917 const int EndCallArgsInx = 4 + NumCallArgs;
2918
2919 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2920 Check(isa<ConstantInt>(NumTransitionArgsV),
2921 "gc.statepoint number of transition arguments "
2922 "must be constant integer",
2923 Call);
2924 const int NumTransitionArgs =
2925 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2926 Check(NumTransitionArgs == 0,
2927 "gc.statepoint w/inline transition bundle is deprecated", Call);
2928 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2929
2930 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2931 Check(isa<ConstantInt>(NumDeoptArgsV),
2932 "gc.statepoint number of deoptimization arguments "
2933 "must be constant integer",
2934 Call);
2935 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2936 Check(NumDeoptArgs == 0,
2937 "gc.statepoint w/inline deopt operands is deprecated", Call);
2938
2939 const int ExpectedNumArgs = 7 + NumCallArgs;
2940 Check(ExpectedNumArgs == (int)Call.arg_size(),
2941 "gc.statepoint too many arguments", Call);
2942
2943 // Check that the only uses of this gc.statepoint are gc.result or
2944 // gc.relocate calls which are tied to this statepoint and thus part
2945 // of the same statepoint sequence
2946 for (const User *U : Call.users()) {
2947 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2948 Check(UserCall, "illegal use of statepoint token", Call, U);
2949 if (!UserCall)
2950 continue;
2951 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2952 "gc.result or gc.relocate are the only value uses "
2953 "of a gc.statepoint",
2954 Call, U);
2955 if (isa<GCResultInst>(UserCall)) {
2956 Check(UserCall->getArgOperand(0) == &Call,
2957 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2958 } else if (isa<GCRelocateInst>(Call)) {
2959 Check(UserCall->getArgOperand(0) == &Call,
2960 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2961 }
2962 }
2963
2964 // Note: It is legal for a single derived pointer to be listed multiple
2965 // times. It's non-optimal, but it is legal. It can also happen after
2966 // insertion if we strip a bitcast away.
2967 // Note: It is really tempting to check that each base is relocated and
2968 // that a derived pointer is never reused as a base pointer. This turns
2969 // out to be problematic since optimizations run after safepoint insertion
2970 // can recognize equality properties that the insertion logic doesn't know
2971 // about. See example statepoint.ll in the verifier subdirectory
2972}
2973
2974void Verifier::verifyFrameRecoverIndices() {
2975 for (auto &Counts : FrameEscapeInfo) {
2976 Function *F = Counts.first;
2977 unsigned EscapedObjectCount = Counts.second.first;
2978 unsigned MaxRecoveredIndex = Counts.second.second;
2979 Check(MaxRecoveredIndex <= EscapedObjectCount,
2980 "all indices passed to llvm.localrecover must be less than the "
2981 "number of arguments passed to llvm.localescape in the parent "
2982 "function",
2983 F);
2984 }
2985}
2986
2987static Instruction *getSuccPad(Instruction *Terminator) {
2988 BasicBlock *UnwindDest;
2989 if (auto *II = dyn_cast<InvokeInst>(Terminator))
2990 UnwindDest = II->getUnwindDest();
2991 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2992 UnwindDest = CSI->getUnwindDest();
2993 else
2994 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2995 return &*UnwindDest->getFirstNonPHIIt();
2996}
2997
2998void Verifier::verifySiblingFuncletUnwinds() {
2999 llvm::TimeTraceScope timeScope("Verifier verify sibling funclet unwinds");
3000 SmallPtrSet<Instruction *, 8> Visited;
3001 SmallPtrSet<Instruction *, 8> Active;
3002 for (const auto &Pair : SiblingFuncletInfo) {
3003 Instruction *PredPad = Pair.first;
3004 if (Visited.count(PredPad))
3005 continue;
3006 Active.insert(PredPad);
3007 Instruction *Terminator = Pair.second;
3008 do {
3009 Instruction *SuccPad = getSuccPad(Terminator);
3010 if (Active.count(SuccPad)) {
3011 // Found a cycle; report error
3012 Instruction *CyclePad = SuccPad;
3013 SmallVector<Instruction *, 8> CycleNodes;
3014 do {
3015 CycleNodes.push_back(CyclePad);
3016 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3017 if (CycleTerminator != CyclePad)
3018 CycleNodes.push_back(CycleTerminator);
3019 CyclePad = getSuccPad(CycleTerminator);
3020 } while (CyclePad != SuccPad);
3021 Check(false, "EH pads can't handle each other's exceptions",
3022 ArrayRef<Instruction *>(CycleNodes));
3023 }
3024 // Don't re-walk a node we've already checked
3025 if (!Visited.insert(SuccPad).second)
3026 break;
3027 // Walk to this successor if it has a map entry.
3028 PredPad = SuccPad;
3029 auto TermI = SiblingFuncletInfo.find(PredPad);
3030 if (TermI == SiblingFuncletInfo.end())
3031 break;
3032 Terminator = TermI->second;
3033 Active.insert(PredPad);
3034 } while (true);
3035 // Each node only has one successor, so we've walked all the active
3036 // nodes' successors.
3037 Active.clear();
3038 }
3039}
3040
3041// visitFunction - Verify that a function is ok.
3042//
3043void Verifier::visitFunction(const Function &F) {
3044 visitGlobalValue(F);
3045
3046 // Check function arguments.
3047 FunctionType *FT = F.getFunctionType();
3048 unsigned NumArgs = F.arg_size();
3049
3050 Check(&Context == &F.getContext(),
3051 "Function context does not match Module context!", &F);
3052
3053 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
3054 Check(FT->getNumParams() == NumArgs,
3055 "# formal arguments must match # of arguments for function type!", &F,
3056 FT);
3057 Check(F.getReturnType()->isFirstClassType() ||
3058 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
3059 "Functions cannot return aggregate values!", &F);
3060
3061 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
3062 "Invalid struct return type!", &F);
3063
3064 if (MaybeAlign A = F.getAlign()) {
3065 Check(A->value() <= Value::MaximumAlignment,
3066 "huge alignment values are unsupported", &F);
3067 }
3068
3069 AttributeList Attrs = F.getAttributes();
3070
3071 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3072 "Attribute after last parameter!", &F);
3073
3074 bool IsIntrinsic = F.isIntrinsic();
3075
3076 // Check function attributes.
3077 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
3078
3079 // On function declarations/definitions, we do not support the builtin
3080 // attribute. We do not check this in VerifyFunctionAttrs since that is
3081 // checking for Attributes that can/can not ever be on functions.
3082 Check(!Attrs.hasFnAttr(Attribute::Builtin),
3083 "Attribute 'builtin' can only be applied to a callsite.", &F);
3084
3085 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
3086 "Attribute 'elementtype' can only be applied to a callsite.", &F);
3087
3088 Check(!Attrs.hasFnAttr("aarch64_zt0_undef"),
3089 "Attribute 'aarch64_zt0_undef' can only be applied to a callsite.");
3090
3091 if (Attrs.hasFnAttr(Attribute::Naked))
3092 for (const Argument &Arg : F.args())
3093 Check(Arg.use_empty(), "cannot use argument of naked function", &Arg);
3094
3095 // Check that this function meets the restrictions on this calling convention.
3096 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
3097 // restrictions can be lifted.
3098 switch (F.getCallingConv()) {
3099 default:
3100 case CallingConv::C:
3101 break;
3102 case CallingConv::X86_INTR: {
3103 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
3104 "Calling convention parameter requires byval", &F);
3105 break;
3106 }
3107 case CallingConv::AMDGPU_KERNEL:
3108 case CallingConv::SPIR_KERNEL:
3109 case CallingConv::AMDGPU_CS_Chain:
3110 case CallingConv::AMDGPU_CS_ChainPreserve:
3111 Check(F.getReturnType()->isVoidTy(),
3112 "Calling convention requires void return type", &F);
3113 [[fallthrough]];
3114 case CallingConv::AMDGPU_VS:
3115 case CallingConv::AMDGPU_HS:
3116 case CallingConv::AMDGPU_GS:
3117 case CallingConv::AMDGPU_PS:
3118 case CallingConv::AMDGPU_CS:
3119 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
3120 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3121 const unsigned StackAS = DL.getAllocaAddrSpace();
3122 unsigned i = 0;
3123 for (const Argument &Arg : F.args()) {
3124 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
3125 "Calling convention disallows byval", &F);
3126 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
3127 "Calling convention disallows preallocated", &F);
3128 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
3129 "Calling convention disallows inalloca", &F);
3130
3131 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
3132 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
3133 // value here.
3134 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3135 "Calling convention disallows stack byref", &F);
3136 }
3137
3138 ++i;
3139 }
3140 }
3141
3142 [[fallthrough]];
3143 case CallingConv::Fast:
3144 case CallingConv::Cold:
3145 case CallingConv::Intel_OCL_BI:
3146 case CallingConv::PTX_Kernel:
3147 case CallingConv::PTX_Device:
3148 Check(!F.isVarArg(),
3149 "Calling convention does not support varargs or "
3150 "perfect forwarding!",
3151 &F);
3152 break;
3153 case CallingConv::AMDGPU_Gfx_WholeWave:
3154 Check(!F.arg_empty() && F.arg_begin()->getType()->isIntegerTy(1),
3155 "Calling convention requires first argument to be i1", &F);
3156 Check(!F.arg_begin()->hasInRegAttr(),
3157 "Calling convention requires first argument to not be inreg", &F);
3158 Check(!F.isVarArg(),
3159 "Calling convention does not support varargs or "
3160 "perfect forwarding!",
3161 &F);
3162 break;
3163 }
3164
3165 // Check that the argument values match the function type for this function...
3166 unsigned i = 0;
3167 for (const Argument &Arg : F.args()) {
3168 Check(Arg.getType() == FT->getParamType(i),
3169 "Argument value does not match function argument type!", &Arg,
3170 FT->getParamType(i));
3171 Check(Arg.getType()->isFirstClassType(),
3172 "Function arguments must have first-class types!", &Arg);
3173 if (!IsIntrinsic) {
3174 Check(!Arg.getType()->isMetadataTy(),
3175 "Function takes metadata but isn't an intrinsic", &Arg, &F);
3176 Check(!Arg.getType()->isTokenLikeTy(),
3177 "Function takes token but isn't an intrinsic", &Arg, &F);
3178 Check(!Arg.getType()->isX86_AMXTy(),
3179 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
3180 }
3181
3182 // Check that swifterror argument is only used by loads and stores.
3183 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3184 verifySwiftErrorValue(&Arg);
3185 }
3186 ++i;
3187 }
3188
3189 if (!IsIntrinsic) {
3190 Check(!F.getReturnType()->isTokenLikeTy(),
3191 "Function returns a token but isn't an intrinsic", &F);
3192 Check(!F.getReturnType()->isX86_AMXTy(),
3193 "Function returns a x86_amx but isn't an intrinsic", &F);
3194 }
3195
3196 // Get the function metadata attachments.
3198 F.getAllMetadata(MDs);
3199 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
3200 verifyFunctionMetadata(MDs);
3201
3202 // Check validity of the personality function
3203 if (F.hasPersonalityFn()) {
3204 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
3205 if (Per)
3206 Check(Per->getParent() == F.getParent(),
3207 "Referencing personality function in another module!", &F,
3208 F.getParent(), Per, Per->getParent());
3209 }
3210
3211 // EH funclet coloring can be expensive, recompute on-demand
3212 BlockEHFuncletColors.clear();
3213
3214 if (F.isMaterializable()) {
3215 // Function has a body somewhere we can't see.
3216 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
3217 MDs.empty() ? nullptr : MDs.front().second);
3218 } else if (F.isDeclaration()) {
3219 for (const auto &I : MDs) {
3220 // This is used for call site debug information.
3221 CheckDI(I.first != LLVMContext::MD_dbg ||
3222 !cast<DISubprogram>(I.second)->isDistinct(),
3223 "function declaration may only have a unique !dbg attachment",
3224 &F);
3225 Check(I.first != LLVMContext::MD_prof,
3226 "function declaration may not have a !prof attachment", &F);
3227
3228 // Verify the metadata itself.
3229 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
3230 }
3231 Check(!F.hasPersonalityFn(),
3232 "Function declaration shouldn't have a personality routine", &F);
3233 } else {
3234 // Verify that this function (which has a body) is not named "llvm.*". It
3235 // is not legal to define intrinsics.
3236 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
3237
3238 // Check the entry node
3239 const BasicBlock *Entry = &F.getEntryBlock();
3240 Check(pred_empty(Entry),
3241 "Entry block to function must not have predecessors!", Entry);
3242
3243 // The address of the entry block cannot be taken, unless it is dead.
3244 if (Entry->hasAddressTaken()) {
3245 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
3246 "blockaddress may not be used with the entry block!", Entry);
3247 }
3248
3249 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3250 NumKCFIAttachments = 0;
3251 // Visit metadata attachments.
3252 for (const auto &I : MDs) {
3253 // Verify that the attachment is legal.
3254 auto AllowLocs = AreDebugLocsAllowed::No;
3255 switch (I.first) {
3256 default:
3257 break;
3258 case LLVMContext::MD_dbg: {
3259 ++NumDebugAttachments;
3260 CheckDI(NumDebugAttachments == 1,
3261 "function must have a single !dbg attachment", &F, I.second);
3262 CheckDI(isa<DISubprogram>(I.second),
3263 "function !dbg attachment must be a subprogram", &F, I.second);
3264 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
3265 "function definition may only have a distinct !dbg attachment",
3266 &F);
3267
3268 auto *SP = cast<DISubprogram>(I.second);
3269 const Function *&AttachedTo = DISubprogramAttachments[SP];
3270 CheckDI(!AttachedTo || AttachedTo == &F,
3271 "DISubprogram attached to more than one function", SP, &F);
3272 AttachedTo = &F;
3273 AllowLocs = AreDebugLocsAllowed::Yes;
3274 break;
3275 }
3276 case LLVMContext::MD_prof:
3277 ++NumProfAttachments;
3278 Check(NumProfAttachments == 1,
3279 "function must have a single !prof attachment", &F, I.second);
3280 break;
3281 case LLVMContext::MD_kcfi_type:
3282 ++NumKCFIAttachments;
3283 Check(NumKCFIAttachments == 1,
3284 "function must have a single !kcfi_type attachment", &F,
3285 I.second);
3286 break;
3287 }
3288
3289 // Verify the metadata itself.
3290 visitMDNode(*I.second, AllowLocs);
3291 }
3292 }
3293
3294 // If this function is actually an intrinsic, verify that it is only used in
3295 // direct call/invokes, never having its "address taken".
3296 // Only do this if the module is materialized, otherwise we don't have all the
3297 // uses.
3298 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
3299 const User *U;
3300 if (F.hasAddressTaken(&U, false, true, false,
3301 /*IgnoreARCAttachedCall=*/true))
3302 Check(false, "Invalid user of intrinsic instruction!", U);
3303 }
3304
3305 // Check intrinsics' signatures.
3306 switch (F.getIntrinsicID()) {
3307 case Intrinsic::experimental_gc_get_pointer_base: {
3308 FunctionType *FT = F.getFunctionType();
3309 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3310 Check(isa<PointerType>(F.getReturnType()),
3311 "gc.get.pointer.base must return a pointer", F);
3312 Check(FT->getParamType(0) == F.getReturnType(),
3313 "gc.get.pointer.base operand and result must be of the same type", F);
3314 break;
3315 }
3316 case Intrinsic::experimental_gc_get_pointer_offset: {
3317 FunctionType *FT = F.getFunctionType();
3318 Check(FT->getNumParams() == 1, "wrong number of parameters", F);
3319 Check(isa<PointerType>(FT->getParamType(0)),
3320 "gc.get.pointer.offset operand must be a pointer", F);
3321 Check(F.getReturnType()->isIntegerTy(),
3322 "gc.get.pointer.offset must return integer", F);
3323 break;
3324 }
3325 }
3326
3327 auto *N = F.getSubprogram();
3328 HasDebugInfo = (N != nullptr);
3329 if (!HasDebugInfo)
3330 return;
3331
3332 // Check that all !dbg attachments lead to back to N.
3333 //
3334 // FIXME: Check this incrementally while visiting !dbg attachments.
3335 // FIXME: Only check when N is the canonical subprogram for F.
3336 SmallPtrSet<const MDNode *, 32> Seen;
3337 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
3338 // Be careful about using DILocation here since we might be dealing with
3339 // broken code (this is the Verifier after all).
3340 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
3341 if (!DL)
3342 return;
3343 if (!Seen.insert(DL).second)
3344 return;
3345
3346 Metadata *Parent = DL->getRawScope();
3347 CheckDI(Parent && isa<DILocalScope>(Parent),
3348 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
3349
3350 DILocalScope *Scope = DL->getInlinedAtScope();
3351 Check(Scope, "Failed to find DILocalScope", DL);
3352
3353 if (!Seen.insert(Scope).second)
3354 return;
3355
3356 DISubprogram *SP = Scope->getSubprogram();
3357
3358 // Scope and SP could be the same MDNode and we don't want to skip
3359 // validation in that case
3360 if ((Scope != SP) && !Seen.insert(SP).second)
3361 return;
3362
3363 CheckDI(SP->describes(&F),
3364 "!dbg attachment points at wrong subprogram for function", N, &F,
3365 &I, DL, Scope, SP);
3366 };
3367 for (auto &BB : F)
3368 for (auto &I : BB) {
3369 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
3370 // The llvm.loop annotations also contain two DILocations.
3371 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
3372 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
3373 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
3374 if (BrokenDebugInfo)
3375 return;
3376 }
3377}
3378
3379// verifyBasicBlock - Verify that a basic block is well formed...
3380//
3381void Verifier::visitBasicBlock(BasicBlock &BB) {
3382 InstsInThisBlock.clear();
3383 ConvergenceVerifyHelper.visit(BB);
3384
3385 // Ensure that basic blocks have terminators!
3386 Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
3387
3388 // Check constraints that this basic block imposes on all of the PHI nodes in
3389 // it.
3390 if (isa<PHINode>(BB.front())) {
3391 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
3393 llvm::sort(Preds);
3394 for (const PHINode &PN : BB.phis()) {
3395 Check(PN.getNumIncomingValues() == Preds.size(),
3396 "PHINode should have one entry for each predecessor of its "
3397 "parent basic block!",
3398 &PN);
3399
3400 // Get and sort all incoming values in the PHI node...
3401 Values.clear();
3402 Values.reserve(PN.getNumIncomingValues());
3403 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3404 Values.push_back(
3405 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3406 llvm::sort(Values);
3407
3408 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
3409 // Check to make sure that if there is more than one entry for a
3410 // particular basic block in this PHI node, that the incoming values are
3411 // all identical.
3412 //
3413 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3414 Values[i].second == Values[i - 1].second,
3415 "PHI node has multiple entries for the same basic block with "
3416 "different incoming values!",
3417 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3418
3419 // Check to make sure that the predecessors and PHI node entries are
3420 // matched up.
3421 Check(Values[i].first == Preds[i],
3422 "PHI node entries do not match predecessors!", &PN,
3423 Values[i].first, Preds[i]);
3424 }
3425 }
3426 }
3427
3428 // Check that all instructions have their parent pointers set up correctly.
3429 for (auto &I : BB)
3430 {
3431 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
3432 }
3433
3434 // Confirm that no issues arise from the debug program.
3435 CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3436 &BB);
3437}
3438
3439void Verifier::visitTerminator(Instruction &I) {
3440 // Ensure that terminators only exist at the end of the basic block.
3441 Check(&I == I.getParent()->getTerminator(),
3442 "Terminator found in the middle of a basic block!", I.getParent());
3443 visitInstruction(I);
3444}
3445
3446void Verifier::visitBranchInst(BranchInst &BI) {
3447 if (BI.isConditional()) {
3449 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
3450 }
3451 visitTerminator(BI);
3452}
3453
3454void Verifier::visitReturnInst(ReturnInst &RI) {
3455 Function *F = RI.getParent()->getParent();
3456 unsigned N = RI.getNumOperands();
3457 if (F->getReturnType()->isVoidTy())
3458 Check(N == 0,
3459 "Found return instr that returns non-void in Function of void "
3460 "return type!",
3461 &RI, F->getReturnType());
3462 else
3463 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
3464 "Function return type does not match operand "
3465 "type of return inst!",
3466 &RI, F->getReturnType());
3467
3468 // Check to make sure that the return value has necessary properties for
3469 // terminators...
3470 visitTerminator(RI);
3471}
3472
3473void Verifier::visitSwitchInst(SwitchInst &SI) {
3474 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
3475 // Check to make sure that all of the constants in the switch instruction
3476 // have the same type as the switched-on value.
3477 Type *SwitchTy = SI.getCondition()->getType();
3478 SmallPtrSet<ConstantInt*, 32> Constants;
3479 for (auto &Case : SI.cases()) {
3480 Check(isa<ConstantInt>(Case.getCaseValue()),
3481 "Case value is not a constant integer.", &SI);
3482 Check(Case.getCaseValue()->getType() == SwitchTy,
3483 "Switch constants must all be same type as switch value!", &SI);
3484 Check(Constants.insert(Case.getCaseValue()).second,
3485 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3486 }
3487
3488 visitTerminator(SI);
3489}
3490
3491void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3493 "Indirectbr operand must have pointer type!", &BI);
3494 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
3496 "Indirectbr destinations must all have pointer type!", &BI);
3497
3498 visitTerminator(BI);
3499}
3500
3501void Verifier::visitCallBrInst(CallBrInst &CBI) {
3502 if (!CBI.isInlineAsm()) {
3504 "Callbr: indirect function / invalid signature");
3505 Check(!CBI.hasOperandBundles(),
3506 "Callbr for intrinsics currently doesn't support operand bundles");
3507
3508 switch (CBI.getIntrinsicID()) {
3509 case Intrinsic::amdgcn_kill: {
3510 Check(CBI.getNumIndirectDests() == 1,
3511 "Callbr amdgcn_kill only supports one indirect dest");
3512 bool Unreachable = isa<UnreachableInst>(CBI.getIndirectDest(0)->begin());
3513 CallInst *Call = dyn_cast<CallInst>(CBI.getIndirectDest(0)->begin());
3514 Check(Unreachable || (Call && Call->getIntrinsicID() ==
3515 Intrinsic::amdgcn_unreachable),
3516 "Callbr amdgcn_kill indirect dest needs to be unreachable");
3517 break;
3518 }
3519 default:
3520 CheckFailed(
3521 "Callbr currently only supports asm-goto and selected intrinsics");
3522 }
3523 visitIntrinsicCall(CBI.getIntrinsicID(), CBI);
3524 } else {
3525 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
3526 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
3527
3528 verifyInlineAsmCall(CBI);
3529 }
3530 visitTerminator(CBI);
3531}
3532
3533void Verifier::visitSelectInst(SelectInst &SI) {
3534 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
3535 SI.getOperand(2)),
3536 "Invalid operands for select instruction!", &SI);
3537
3538 Check(SI.getTrueValue()->getType() == SI.getType(),
3539 "Select values must have same type as select instruction!", &SI);
3540 visitInstruction(SI);
3541}
3542
3543/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3544/// a pass, if any exist, it's an error.
3545///
3546void Verifier::visitUserOp1(Instruction &I) {
3547 Check(false, "User-defined operators should not live outside of a pass!", &I);
3548}
3549
3550void Verifier::visitTruncInst(TruncInst &I) {
3551 // Get the source and destination types
3552 Type *SrcTy = I.getOperand(0)->getType();
3553 Type *DestTy = I.getType();
3554
3555 // Get the size of the types in bits, we'll need this later
3556 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3557 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3558
3559 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
3560 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
3561 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3562 "trunc source and destination must both be a vector or neither", &I);
3563 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
3564
3565 visitInstruction(I);
3566}
3567
3568void Verifier::visitZExtInst(ZExtInst &I) {
3569 // Get the source and destination types
3570 Type *SrcTy = I.getOperand(0)->getType();
3571 Type *DestTy = I.getType();
3572
3573 // Get the size of the types in bits, we'll need this later
3574 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
3575 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
3576 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3577 "zext source and destination must both be a vector or neither", &I);
3578 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3579 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3580
3581 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
3582
3583 visitInstruction(I);
3584}
3585
3586void Verifier::visitSExtInst(SExtInst &I) {
3587 // Get the source and destination types
3588 Type *SrcTy = I.getOperand(0)->getType();
3589 Type *DestTy = I.getType();
3590
3591 // Get the size of the types in bits, we'll need this later
3592 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3593 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3594
3595 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
3596 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
3597 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3598 "sext source and destination must both be a vector or neither", &I);
3599 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
3600
3601 visitInstruction(I);
3602}
3603
3604void Verifier::visitFPTruncInst(FPTruncInst &I) {
3605 // Get the source and destination types
3606 Type *SrcTy = I.getOperand(0)->getType();
3607 Type *DestTy = I.getType();
3608 // Get the size of the types in bits, we'll need this later
3609 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3610 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3611
3612 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
3613 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
3614 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3615 "fptrunc source and destination must both be a vector or neither", &I);
3616 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
3617
3618 visitInstruction(I);
3619}
3620
3621void Verifier::visitFPExtInst(FPExtInst &I) {
3622 // Get the source and destination types
3623 Type *SrcTy = I.getOperand(0)->getType();
3624 Type *DestTy = I.getType();
3625
3626 // Get the size of the types in bits, we'll need this later
3627 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3628 unsigned DestBitSize = DestTy->getScalarSizeInBits();
3629
3630 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
3631 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
3632 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
3633 "fpext source and destination must both be a vector or neither", &I);
3634 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
3635
3636 visitInstruction(I);
3637}
3638
3639void Verifier::visitUIToFPInst(UIToFPInst &I) {
3640 // Get the source and destination types
3641 Type *SrcTy = I.getOperand(0)->getType();
3642 Type *DestTy = I.getType();
3643
3644 bool SrcVec = SrcTy->isVectorTy();
3645 bool DstVec = DestTy->isVectorTy();
3646
3647 Check(SrcVec == DstVec,
3648 "UIToFP source and dest must both be vector or scalar", &I);
3649 Check(SrcTy->isIntOrIntVectorTy(),
3650 "UIToFP source must be integer or integer vector", &I);
3651 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
3652 &I);
3653
3654 if (SrcVec && DstVec)
3655 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3656 cast<VectorType>(DestTy)->getElementCount(),
3657 "UIToFP source and dest vector length mismatch", &I);
3658
3659 visitInstruction(I);
3660}
3661
3662void Verifier::visitSIToFPInst(SIToFPInst &I) {
3663 // Get the source and destination types
3664 Type *SrcTy = I.getOperand(0)->getType();
3665 Type *DestTy = I.getType();
3666
3667 bool SrcVec = SrcTy->isVectorTy();
3668 bool DstVec = DestTy->isVectorTy();
3669
3670 Check(SrcVec == DstVec,
3671 "SIToFP source and dest must both be vector or scalar", &I);
3672 Check(SrcTy->isIntOrIntVectorTy(),
3673 "SIToFP source must be integer or integer vector", &I);
3674 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
3675 &I);
3676
3677 if (SrcVec && DstVec)
3678 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3679 cast<VectorType>(DestTy)->getElementCount(),
3680 "SIToFP source and dest vector length mismatch", &I);
3681
3682 visitInstruction(I);
3683}
3684
3685void Verifier::visitFPToUIInst(FPToUIInst &I) {
3686 // Get the source and destination types
3687 Type *SrcTy = I.getOperand(0)->getType();
3688 Type *DestTy = I.getType();
3689
3690 bool SrcVec = SrcTy->isVectorTy();
3691 bool DstVec = DestTy->isVectorTy();
3692
3693 Check(SrcVec == DstVec,
3694 "FPToUI source and dest must both be vector or scalar", &I);
3695 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
3696 Check(DestTy->isIntOrIntVectorTy(),
3697 "FPToUI result must be integer or integer vector", &I);
3698
3699 if (SrcVec && DstVec)
3700 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3701 cast<VectorType>(DestTy)->getElementCount(),
3702 "FPToUI source and dest vector length mismatch", &I);
3703
3704 visitInstruction(I);
3705}
3706
3707void Verifier::visitFPToSIInst(FPToSIInst &I) {
3708 // Get the source and destination types
3709 Type *SrcTy = I.getOperand(0)->getType();
3710 Type *DestTy = I.getType();
3711
3712 bool SrcVec = SrcTy->isVectorTy();
3713 bool DstVec = DestTy->isVectorTy();
3714
3715 Check(SrcVec == DstVec,
3716 "FPToSI source and dest must both be vector or scalar", &I);
3717 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
3718 Check(DestTy->isIntOrIntVectorTy(),
3719 "FPToSI result must be integer or integer vector", &I);
3720
3721 if (SrcVec && DstVec)
3722 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3723 cast<VectorType>(DestTy)->getElementCount(),
3724 "FPToSI source and dest vector length mismatch", &I);
3725
3726 visitInstruction(I);
3727}
3728
3729void Verifier::checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V) {
3730 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToAddr source must be pointer", V);
3731 Check(DestTy->isIntOrIntVectorTy(), "PtrToAddr result must be integral", V);
3732 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToAddr type mismatch",
3733 V);
3734
3735 if (SrcTy->isVectorTy()) {
3736 auto *VSrc = cast<VectorType>(SrcTy);
3737 auto *VDest = cast<VectorType>(DestTy);
3738 Check(VSrc->getElementCount() == VDest->getElementCount(),
3739 "PtrToAddr vector length mismatch", V);
3740 }
3741
3742 Type *AddrTy = DL.getAddressType(SrcTy);
3743 Check(AddrTy == DestTy, "PtrToAddr result must be address width", V);
3744}
3745
3746void Verifier::visitPtrToAddrInst(PtrToAddrInst &I) {
3747 checkPtrToAddr(I.getOperand(0)->getType(), I.getType(), I);
3748 visitInstruction(I);
3749}
3750
3751void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
3752 // Get the source and destination types
3753 Type *SrcTy = I.getOperand(0)->getType();
3754 Type *DestTy = I.getType();
3755
3756 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3757
3758 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3759 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3760 &I);
3761
3762 if (SrcTy->isVectorTy()) {
3763 auto *VSrc = cast<VectorType>(SrcTy);
3764 auto *VDest = cast<VectorType>(DestTy);
3765 Check(VSrc->getElementCount() == VDest->getElementCount(),
3766 "PtrToInt Vector length mismatch", &I);
3767 }
3768
3769 visitInstruction(I);
3770}
3771
3772void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3773 // Get the source and destination types
3774 Type *SrcTy = I.getOperand(0)->getType();
3775 Type *DestTy = I.getType();
3776
3777 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
3778 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3779
3780 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3781 &I);
3782 if (SrcTy->isVectorTy()) {
3783 auto *VSrc = cast<VectorType>(SrcTy);
3784 auto *VDest = cast<VectorType>(DestTy);
3785 Check(VSrc->getElementCount() == VDest->getElementCount(),
3786 "IntToPtr Vector length mismatch", &I);
3787 }
3788 visitInstruction(I);
3789}
3790
3791void Verifier::visitBitCastInst(BitCastInst &I) {
3792 Check(
3793 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3794 "Invalid bitcast", &I);
3795 visitInstruction(I);
3796}
3797
3798void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3799 Type *SrcTy = I.getOperand(0)->getType();
3800 Type *DestTy = I.getType();
3801
3802 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3803 &I);
3804 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3805 &I);
3807 "AddrSpaceCast must be between different address spaces", &I);
3808 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3809 Check(SrcVTy->getElementCount() ==
3810 cast<VectorType>(DestTy)->getElementCount(),
3811 "AddrSpaceCast vector pointer number of elements mismatch", &I);
3812 visitInstruction(I);
3813}
3814
3815/// visitPHINode - Ensure that a PHI node is well formed.
3816///
3817void Verifier::visitPHINode(PHINode &PN) {
3818 // Ensure that the PHI nodes are all grouped together at the top of the block.
3819 // This can be tested by checking whether the instruction before this is
3820 // either nonexistent (because this is begin()) or is a PHI node. If not,
3821 // then there is some other instruction before a PHI.
3822 Check(&PN == &PN.getParent()->front() ||
3824 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3825
3826 // Check that a PHI doesn't yield a Token.
3827 Check(!PN.getType()->isTokenLikeTy(), "PHI nodes cannot have token type!");
3828
3829 // Check that all of the values of the PHI node have the same type as the
3830 // result.
3831 for (Value *IncValue : PN.incoming_values()) {
3832 Check(PN.getType() == IncValue->getType(),
3833 "PHI node operands are not the same type as the result!", &PN);
3834 }
3835
3836 // All other PHI node constraints are checked in the visitBasicBlock method.
3837
3838 visitInstruction(PN);
3839}
3840
3841void Verifier::visitCallBase(CallBase &Call) {
3843 "Called function must be a pointer!", Call);
3844 FunctionType *FTy = Call.getFunctionType();
3845
3846 // Verify that the correct number of arguments are being passed
3847 if (FTy->isVarArg())
3848 Check(Call.arg_size() >= FTy->getNumParams(),
3849 "Called function requires more parameters than were provided!", Call);
3850 else
3851 Check(Call.arg_size() == FTy->getNumParams(),
3852 "Incorrect number of arguments passed to called function!", Call);
3853
3854 // Verify that all arguments to the call match the function type.
3855 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3856 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3857 "Call parameter type does not match function signature!",
3858 Call.getArgOperand(i), FTy->getParamType(i), Call);
3859
3860 AttributeList Attrs = Call.getAttributes();
3861
3862 Check(verifyAttributeCount(Attrs, Call.arg_size()),
3863 "Attribute after last parameter!", Call);
3864
3865 Function *Callee =
3867 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3868 if (IsIntrinsic)
3869 Check(Callee->getFunctionType() == FTy,
3870 "Intrinsic called with incompatible signature", Call);
3871
3872 // Verify if the calling convention of the callee is callable.
3874 "calling convention does not permit calls", Call);
3875
3876 // Disallow passing/returning values with alignment higher than we can
3877 // represent.
3878 // FIXME: Consider making DataLayout cap the alignment, so this isn't
3879 // necessary.
3880 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
3881 if (!Ty->isSized())
3882 return;
3883 Align ABIAlign = DL.getABITypeAlign(Ty);
3884 Check(ABIAlign.value() <= Value::MaximumAlignment,
3885 "Incorrect alignment of " + Message + " to called function!", Call);
3886 };
3887
3888 if (!IsIntrinsic) {
3889 VerifyTypeAlign(FTy->getReturnType(), "return type");
3890 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3891 Type *Ty = FTy->getParamType(i);
3892 VerifyTypeAlign(Ty, "argument passed");
3893 }
3894 }
3895
3896 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3897 // Don't allow speculatable on call sites, unless the underlying function
3898 // declaration is also speculatable.
3899 Check(Callee && Callee->isSpeculatable(),
3900 "speculatable attribute may not apply to call sites", Call);
3901 }
3902
3903 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3904 Check(Call.getIntrinsicID() == Intrinsic::call_preallocated_arg,
3905 "preallocated as a call site attribute can only be on "
3906 "llvm.call.preallocated.arg");
3907 }
3908
3909 Check(!Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3910 "denormal_fpenv attribute may not apply to call sites", Call);
3911
3912 // Verify call attributes.
3913 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
3914
3915 // Conservatively check the inalloca argument.
3916 // We have a bug if we can find that there is an underlying alloca without
3917 // inalloca.
3918 if (Call.hasInAllocaArgument()) {
3919 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3920 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3921 Check(AI->isUsedWithInAlloca(),
3922 "inalloca argument for call has mismatched alloca", AI, Call);
3923 }
3924
3925 // For each argument of the callsite, if it has the swifterror argument,
3926 // make sure the underlying alloca/parameter it comes from has a swifterror as
3927 // well.
3928 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3929 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3930 Value *SwiftErrorArg = Call.getArgOperand(i);
3931 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3932 Check(AI->isSwiftError(),
3933 "swifterror argument for call has mismatched alloca", AI, Call);
3934 continue;
3935 }
3936 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3937 Check(ArgI, "swifterror argument should come from an alloca or parameter",
3938 SwiftErrorArg, Call);
3939 Check(ArgI->hasSwiftErrorAttr(),
3940 "swifterror argument for call has mismatched parameter", ArgI,
3941 Call);
3942 }
3943
3944 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3945 // Don't allow immarg on call sites, unless the underlying declaration
3946 // also has the matching immarg.
3947 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3948 "immarg may not apply only to call sites", Call.getArgOperand(i),
3949 Call);
3950 }
3951
3952 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3953 Value *ArgVal = Call.getArgOperand(i);
3954 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3955 "immarg operand has non-immediate parameter", ArgVal, Call);
3956
3957 // If the imm-arg is an integer and also has a range attached,
3958 // check if the given value is within the range.
3959 if (Call.paramHasAttr(i, Attribute::Range)) {
3960 if (auto *CI = dyn_cast<ConstantInt>(ArgVal)) {
3961 const ConstantRange &CR =
3962 Call.getParamAttr(i, Attribute::Range).getValueAsConstantRange();
3963 Check(CR.contains(CI->getValue()),
3964 "immarg value " + Twine(CI->getValue().getSExtValue()) +
3965 " out of range [" + Twine(CR.getLower().getSExtValue()) +
3966 ", " + Twine(CR.getUpper().getSExtValue()) + ")",
3967 Call);
3968 }
3969 }
3970 }
3971
3972 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3973 Value *ArgVal = Call.getArgOperand(i);
3974 bool hasOB =
3976 bool isMustTail = Call.isMustTailCall();
3977 Check(hasOB != isMustTail,
3978 "preallocated operand either requires a preallocated bundle or "
3979 "the call to be musttail (but not both)",
3980 ArgVal, Call);
3981 }
3982 }
3983
3984 if (FTy->isVarArg()) {
3985 // FIXME? is 'nest' even legal here?
3986 bool SawNest = false;
3987 bool SawReturned = false;
3988
3989 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3990 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3991 SawNest = true;
3992 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3993 SawReturned = true;
3994 }
3995
3996 // Check attributes on the varargs part.
3997 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3998 Type *Ty = Call.getArgOperand(Idx)->getType();
3999 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
4000 verifyParameterAttrs(ArgAttrs, Ty, &Call);
4001
4002 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
4003 Check(!SawNest, "More than one parameter has attribute nest!", Call);
4004 SawNest = true;
4005 }
4006
4007 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
4008 Check(!SawReturned, "More than one parameter has attribute returned!",
4009 Call);
4010 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
4011 "Incompatible argument and return types for 'returned' "
4012 "attribute",
4013 Call);
4014 SawReturned = true;
4015 }
4016
4017 // Statepoint intrinsic is vararg but the wrapped function may be not.
4018 // Allow sret here and check the wrapped function in verifyStatepoint.
4019 if (Call.getIntrinsicID() != Intrinsic::experimental_gc_statepoint)
4020 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
4021 "Attribute 'sret' cannot be used for vararg call arguments!",
4022 Call);
4023
4024 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
4025 Check(Idx == Call.arg_size() - 1,
4026 "inalloca isn't on the last argument!", Call);
4027 }
4028 }
4029
4030 // Verify that there's no metadata unless it's a direct call to an intrinsic.
4031 if (!IsIntrinsic) {
4032 for (Type *ParamTy : FTy->params()) {
4033 Check(!ParamTy->isMetadataTy(),
4034 "Function has metadata parameter but isn't an intrinsic", Call);
4035 Check(!ParamTy->isTokenLikeTy(),
4036 "Function has token parameter but isn't an intrinsic", Call);
4037 }
4038 }
4039
4040 // Verify that indirect calls don't return tokens.
4041 if (!Call.getCalledFunction()) {
4042 Check(!FTy->getReturnType()->isTokenLikeTy(),
4043 "Return type cannot be token for indirect call!");
4044 Check(!FTy->getReturnType()->isX86_AMXTy(),
4045 "Return type cannot be x86_amx for indirect call!");
4046 }
4047
4049 visitIntrinsicCall(ID, Call);
4050
4051 // Verify that a callsite has at most one "deopt", at most one "funclet", at
4052 // most one "gc-transition", at most one "cfguardtarget", at most one
4053 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
4054 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
4055 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
4056 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
4057 FoundPtrauthBundle = false, FoundKCFIBundle = false,
4058 FoundAttachedCallBundle = false;
4059 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
4060 OperandBundleUse BU = Call.getOperandBundleAt(i);
4061 uint32_t Tag = BU.getTagID();
4062 if (Tag == LLVMContext::OB_deopt) {
4063 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
4064 FoundDeoptBundle = true;
4065 } else if (Tag == LLVMContext::OB_gc_transition) {
4066 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
4067 Call);
4068 FoundGCTransitionBundle = true;
4069 } else if (Tag == LLVMContext::OB_funclet) {
4070 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
4071 FoundFuncletBundle = true;
4072 Check(BU.Inputs.size() == 1,
4073 "Expected exactly one funclet bundle operand", Call);
4074 Check(isa<FuncletPadInst>(BU.Inputs.front()),
4075 "Funclet bundle operands should correspond to a FuncletPadInst",
4076 Call);
4077 } else if (Tag == LLVMContext::OB_cfguardtarget) {
4078 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
4079 Call);
4080 FoundCFGuardTargetBundle = true;
4081 Check(BU.Inputs.size() == 1,
4082 "Expected exactly one cfguardtarget bundle operand", Call);
4083 } else if (Tag == LLVMContext::OB_ptrauth) {
4084 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
4085 FoundPtrauthBundle = true;
4086 Check(BU.Inputs.size() == 2,
4087 "Expected exactly two ptrauth bundle operands", Call);
4088 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4089 BU.Inputs[0]->getType()->isIntegerTy(32),
4090 "Ptrauth bundle key operand must be an i32 constant", Call);
4091 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
4092 "Ptrauth bundle discriminator operand must be an i64", Call);
4093 } else if (Tag == LLVMContext::OB_kcfi) {
4094 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
4095 FoundKCFIBundle = true;
4096 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
4097 Call);
4098 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4099 BU.Inputs[0]->getType()->isIntegerTy(32),
4100 "Kcfi bundle operand must be an i32 constant", Call);
4101 } else if (Tag == LLVMContext::OB_preallocated) {
4102 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
4103 Call);
4104 FoundPreallocatedBundle = true;
4105 Check(BU.Inputs.size() == 1,
4106 "Expected exactly one preallocated bundle operand", Call);
4107 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
4108 Check(Input &&
4109 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4110 "\"preallocated\" argument must be a token from "
4111 "llvm.call.preallocated.setup",
4112 Call);
4113 } else if (Tag == LLVMContext::OB_gc_live) {
4114 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
4115 FoundGCLiveBundle = true;
4117 Check(!FoundAttachedCallBundle,
4118 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
4119 FoundAttachedCallBundle = true;
4120 verifyAttachedCallBundle(Call, BU);
4121 }
4122 }
4123
4124 // Verify that callee and callsite agree on whether to use pointer auth.
4125 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
4126 "Direct call cannot have a ptrauth bundle", Call);
4127
4128 // Verify that each inlinable callsite of a debug-info-bearing function in a
4129 // debug-info-bearing function has a debug location attached to it. Failure to
4130 // do so causes assertion failures when the inliner sets up inline scope info
4131 // (Interposable functions are not inlinable, neither are functions without
4132 // definitions.)
4138 "inlinable function call in a function with "
4139 "debug info must have a !dbg location",
4140 Call);
4141
4142 if (Call.isInlineAsm())
4143 verifyInlineAsmCall(Call);
4144
4145 ConvergenceVerifyHelper.visit(Call);
4146
4147 visitInstruction(Call);
4148}
4149
4150void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
4151 StringRef Context) {
4152 Check(!Attrs.contains(Attribute::InAlloca),
4153 Twine("inalloca attribute not allowed in ") + Context);
4154 Check(!Attrs.contains(Attribute::InReg),
4155 Twine("inreg attribute not allowed in ") + Context);
4156 Check(!Attrs.contains(Attribute::SwiftError),
4157 Twine("swifterror attribute not allowed in ") + Context);
4158 Check(!Attrs.contains(Attribute::Preallocated),
4159 Twine("preallocated attribute not allowed in ") + Context);
4160 Check(!Attrs.contains(Attribute::ByRef),
4161 Twine("byref attribute not allowed in ") + Context);
4162}
4163
4164/// Two types are "congruent" if they are identical, or if they are both pointer
4165/// types with different pointee types and the same address space.
4166static bool isTypeCongruent(Type *L, Type *R) {
4167 if (L == R)
4168 return true;
4171 if (!PL || !PR)
4172 return false;
4173 return PL->getAddressSpace() == PR->getAddressSpace();
4174}
4175
4176static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
4177 static const Attribute::AttrKind ABIAttrs[] = {
4178 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4179 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4180 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4181 Attribute::ByRef};
4182 AttrBuilder Copy(C);
4183 for (auto AK : ABIAttrs) {
4184 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
4185 if (Attr.isValid())
4186 Copy.addAttribute(Attr);
4187 }
4188
4189 // `align` is ABI-affecting only in combination with `byval` or `byref`.
4190 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
4191 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
4192 Attrs.hasParamAttr(I, Attribute::ByRef)))
4193 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
4194 return Copy;
4195}
4196
4197void Verifier::verifyMustTailCall(CallInst &CI) {
4198 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
4199
4200 Function *F = CI.getParent()->getParent();
4201 FunctionType *CallerTy = F->getFunctionType();
4202 FunctionType *CalleeTy = CI.getFunctionType();
4203 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4204 "cannot guarantee tail call due to mismatched varargs", &CI);
4205 Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
4206 "cannot guarantee tail call due to mismatched return types", &CI);
4207
4208 // - The calling conventions of the caller and callee must match.
4209 Check(F->getCallingConv() == CI.getCallingConv(),
4210 "cannot guarantee tail call due to mismatched calling conv", &CI);
4211
4212 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
4213 // or a pointer bitcast followed by a ret instruction.
4214 // - The ret instruction must return the (possibly bitcasted) value
4215 // produced by the call or void.
4216 Value *RetVal = &CI;
4218
4219 // Handle the optional bitcast.
4220 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
4221 Check(BI->getOperand(0) == RetVal,
4222 "bitcast following musttail call must use the call", BI);
4223 RetVal = BI;
4224 Next = BI->getNextNode();
4225 }
4226
4227 // Check the return.
4228 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
4229 Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
4230 Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
4232 "musttail call result must be returned", Ret);
4233
4234 AttributeList CallerAttrs = F->getAttributes();
4235 AttributeList CalleeAttrs = CI.getAttributes();
4236 if (CI.getCallingConv() == CallingConv::SwiftTail ||
4237 CI.getCallingConv() == CallingConv::Tail) {
4238 StringRef CCName =
4239 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
4240
4241 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
4242 // are allowed in swifttailcc call
4243 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4244 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4245 SmallString<32> Context{CCName, StringRef(" musttail caller")};
4246 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4247 }
4248 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
4249 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4250 SmallString<32> Context{CCName, StringRef(" musttail callee")};
4251 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4252 }
4253 // - Varargs functions are not allowed
4254 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
4255 " tail call for varargs function");
4256 return;
4257 }
4258
4259 // - The caller and callee prototypes must match. Pointer types of
4260 // parameters or return types may differ in pointee type, but not
4261 // address space.
4262 if (!CI.getIntrinsicID()) {
4263 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4264 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4265 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4266 Check(
4267 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
4268 "cannot guarantee tail call due to mismatched parameter types", &CI);
4269 }
4270 }
4271
4272 // - All ABI-impacting function attributes, such as sret, byval, inreg,
4273 // returned, preallocated, and inalloca, must match.
4274 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4275 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4276 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4277 Check(CallerABIAttrs == CalleeABIAttrs,
4278 "cannot guarantee tail call due to mismatched ABI impacting "
4279 "function attributes",
4280 &CI, CI.getOperand(I));
4281 }
4282}
4283
4284void Verifier::visitCallInst(CallInst &CI) {
4285 visitCallBase(CI);
4286
4287 if (CI.isMustTailCall())
4288 verifyMustTailCall(CI);
4289}
4290
4291void Verifier::visitInvokeInst(InvokeInst &II) {
4292 visitCallBase(II);
4293
4294 // Verify that the first non-PHI instruction of the unwind destination is an
4295 // exception handling instruction.
4296 Check(
4297 II.getUnwindDest()->isEHPad(),
4298 "The unwind destination does not have an exception handling instruction!",
4299 &II);
4300
4301 visitTerminator(II);
4302}
4303
4304/// visitUnaryOperator - Check the argument to the unary operator.
4305///
4306void Verifier::visitUnaryOperator(UnaryOperator &U) {
4307 Check(U.getType() == U.getOperand(0)->getType(),
4308 "Unary operators must have same type for"
4309 "operands and result!",
4310 &U);
4311
4312 switch (U.getOpcode()) {
4313 // Check that floating-point arithmetic operators are only used with
4314 // floating-point operands.
4315 case Instruction::FNeg:
4316 Check(U.getType()->isFPOrFPVectorTy(),
4317 "FNeg operator only works with float types!", &U);
4318 break;
4319 default:
4320 llvm_unreachable("Unknown UnaryOperator opcode!");
4321 }
4322
4323 visitInstruction(U);
4324}
4325
4326/// visitBinaryOperator - Check that both arguments to the binary operator are
4327/// of the same type!
4328///
4329void Verifier::visitBinaryOperator(BinaryOperator &B) {
4330 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
4331 "Both operands to a binary operator are not of the same type!", &B);
4332
4333 switch (B.getOpcode()) {
4334 // Check that integer arithmetic operators are only used with
4335 // integral operands.
4336 case Instruction::Add:
4337 case Instruction::Sub:
4338 case Instruction::Mul:
4339 case Instruction::SDiv:
4340 case Instruction::UDiv:
4341 case Instruction::SRem:
4342 case Instruction::URem:
4343 Check(B.getType()->isIntOrIntVectorTy(),
4344 "Integer arithmetic operators only work with integral types!", &B);
4345 Check(B.getType() == B.getOperand(0)->getType(),
4346 "Integer arithmetic operators must have same type "
4347 "for operands and result!",
4348 &B);
4349 break;
4350 // Check that floating-point arithmetic operators are only used with
4351 // floating-point operands.
4352 case Instruction::FAdd:
4353 case Instruction::FSub:
4354 case Instruction::FMul:
4355 case Instruction::FDiv:
4356 case Instruction::FRem:
4357 Check(B.getType()->isFPOrFPVectorTy(),
4358 "Floating-point arithmetic operators only work with "
4359 "floating-point types!",
4360 &B);
4361 Check(B.getType() == B.getOperand(0)->getType(),
4362 "Floating-point arithmetic operators must have same type "
4363 "for operands and result!",
4364 &B);
4365 break;
4366 // Check that logical operators are only used with integral operands.
4367 case Instruction::And:
4368 case Instruction::Or:
4369 case Instruction::Xor:
4370 Check(B.getType()->isIntOrIntVectorTy(),
4371 "Logical operators only work with integral types!", &B);
4372 Check(B.getType() == B.getOperand(0)->getType(),
4373 "Logical operators must have same type for operands and result!", &B);
4374 break;
4375 case Instruction::Shl:
4376 case Instruction::LShr:
4377 case Instruction::AShr:
4378 Check(B.getType()->isIntOrIntVectorTy(),
4379 "Shifts only work with integral types!", &B);
4380 Check(B.getType() == B.getOperand(0)->getType(),
4381 "Shift return type must be same as operands!", &B);
4382 break;
4383 default:
4384 llvm_unreachable("Unknown BinaryOperator opcode!");
4385 }
4386
4387 visitInstruction(B);
4388}
4389
4390void Verifier::visitICmpInst(ICmpInst &IC) {
4391 // Check that the operands are the same type
4392 Type *Op0Ty = IC.getOperand(0)->getType();
4393 Type *Op1Ty = IC.getOperand(1)->getType();
4394 Check(Op0Ty == Op1Ty,
4395 "Both operands to ICmp instruction are not of the same type!", &IC);
4396 // Check that the operands are the right type
4397 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
4398 "Invalid operand types for ICmp instruction", &IC);
4399 // Check that the predicate is valid.
4400 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
4401
4402 visitInstruction(IC);
4403}
4404
4405void Verifier::visitFCmpInst(FCmpInst &FC) {
4406 // Check that the operands are the same type
4407 Type *Op0Ty = FC.getOperand(0)->getType();
4408 Type *Op1Ty = FC.getOperand(1)->getType();
4409 Check(Op0Ty == Op1Ty,
4410 "Both operands to FCmp instruction are not of the same type!", &FC);
4411 // Check that the operands are the right type
4412 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
4413 &FC);
4414 // Check that the predicate is valid.
4415 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
4416
4417 visitInstruction(FC);
4418}
4419
4420void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4422 "Invalid extractelement operands!", &EI);
4423 visitInstruction(EI);
4424}
4425
4426void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4427 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
4428 IE.getOperand(2)),
4429 "Invalid insertelement operands!", &IE);
4430 visitInstruction(IE);
4431}
4432
4433void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4435 SV.getShuffleMask()),
4436 "Invalid shufflevector operands!", &SV);
4437 visitInstruction(SV);
4438}
4439
4440void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4441 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
4442
4443 Check(isa<PointerType>(TargetTy),
4444 "GEP base pointer is not a vector or a vector of pointers", &GEP);
4445 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
4446
4447 if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
4448 Check(!STy->isScalableTy(),
4449 "getelementptr cannot target structure that contains scalable vector"
4450 "type",
4451 &GEP);
4452 }
4453
4454 SmallVector<Value *, 16> Idxs(GEP.indices());
4455 Check(
4456 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
4457 "GEP indexes must be integers", &GEP);
4458 Type *ElTy =
4459 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
4460 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
4461
4462 PointerType *PtrTy = dyn_cast<PointerType>(GEP.getType()->getScalarType());
4463
4464 Check(PtrTy && GEP.getResultElementType() == ElTy,
4465 "GEP is not of right type for indices!", &GEP, ElTy);
4466
4467 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
4468 // Additional checks for vector GEPs.
4469 ElementCount GEPWidth = GEPVTy->getElementCount();
4470 if (GEP.getPointerOperandType()->isVectorTy())
4471 Check(
4472 GEPWidth ==
4473 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
4474 "Vector GEP result width doesn't match operand's", &GEP);
4475 for (Value *Idx : Idxs) {
4476 Type *IndexTy = Idx->getType();
4477 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4478 ElementCount IndexWidth = IndexVTy->getElementCount();
4479 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
4480 }
4481 Check(IndexTy->isIntOrIntVectorTy(),
4482 "All GEP indices should be of integer type");
4483 }
4484 }
4485
4486 // Check that GEP does not index into a vector with non-byte-addressable
4487 // elements.
4489 GTI != GTE; ++GTI) {
4490 if (GTI.isVector()) {
4491 Type *ElemTy = GTI.getIndexedType();
4492 Check(DL.typeSizeEqualsStoreSize(ElemTy),
4493 "GEP into vector with non-byte-addressable element type", &GEP);
4494 }
4495 }
4496
4497 Check(GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4498 "GEP address space doesn't match type", &GEP);
4499
4500 visitInstruction(GEP);
4501}
4502
4503static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
4504 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
4505}
4506
4507/// Verify !range and !absolute_symbol metadata. These have the same
4508/// restrictions, except !absolute_symbol allows the full set.
4509void Verifier::verifyRangeLikeMetadata(const Value &I, const MDNode *Range,
4510 Type *Ty, RangeLikeMetadataKind Kind) {
4511 unsigned NumOperands = Range->getNumOperands();
4512 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
4513 unsigned NumRanges = NumOperands / 2;
4514 Check(NumRanges >= 1, "It should have at least one range!", Range);
4515
4516 ConstantRange LastRange(1, true); // Dummy initial value
4517 for (unsigned i = 0; i < NumRanges; ++i) {
4518 ConstantInt *Low =
4519 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
4520 Check(Low, "The lower limit must be an integer!", Low);
4521 ConstantInt *High =
4522 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
4523 Check(High, "The upper limit must be an integer!", High);
4524
4525 Check(High->getType() == Low->getType(), "Range pair types must match!",
4526 &I);
4527
4528 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4529 Check(High->getType()->isIntegerTy(32),
4530 "noalias.addrspace type must be i32!", &I);
4531 } else {
4532 Check(High->getType() == Ty->getScalarType(),
4533 "Range types must match instruction type!", &I);
4534 }
4535
4536 APInt HighV = High->getValue();
4537 APInt LowV = Low->getValue();
4538
4539 // ConstantRange asserts if the ranges are the same except for the min/max
4540 // value. Leave the cases it tolerates for the empty range error below.
4541 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
4542 "The upper and lower limits cannot be the same value", &I);
4543
4544 ConstantRange CurRange(LowV, HighV);
4545 Check(!CurRange.isEmptySet() &&
4546 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4547 !CurRange.isFullSet()),
4548 "Range must not be empty!", Range);
4549 if (i != 0) {
4550 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4551 "Intervals are overlapping", Range);
4552 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
4553 Range);
4554 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
4555 Range);
4556 }
4557 LastRange = ConstantRange(LowV, HighV);
4558 }
4559 if (NumRanges > 2) {
4560 APInt FirstLow =
4561 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
4562 APInt FirstHigh =
4563 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
4564 ConstantRange FirstRange(FirstLow, FirstHigh);
4565 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4566 "Intervals are overlapping", Range);
4567 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
4568 Range);
4569 }
4570}
4571
4572void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
4573 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
4574 "precondition violation");
4575 verifyRangeLikeMetadata(I, Range, Ty, RangeLikeMetadataKind::Range);
4576}
4577
4578void Verifier::visitNoFPClassMetadata(Instruction &I, MDNode *NoFPClass,
4579 Type *Ty) {
4580 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4581 "nofpclass only applies to floating-point typed loads", I);
4582
4583 Check(NoFPClass->getNumOperands() == 1,
4584 "nofpclass must have exactly one entry", NoFPClass);
4585 ConstantInt *MaskVal =
4587 Check(MaskVal && MaskVal->getType()->isIntegerTy(32),
4588 "nofpclass entry must be a constant i32", NoFPClass);
4589 uint32_t Val = MaskVal->getZExtValue();
4590 Check(Val != 0, "'nofpclass' must have at least one test bit set", NoFPClass,
4591 I);
4592
4593 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
4594 "Invalid value for 'nofpclass' test mask", NoFPClass, I);
4595}
4596
4597void Verifier::visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range,
4598 Type *Ty) {
4599 assert(Range && Range == I.getMetadata(LLVMContext::MD_noalias_addrspace) &&
4600 "precondition violation");
4601 verifyRangeLikeMetadata(I, Range, Ty,
4602 RangeLikeMetadataKind::NoaliasAddrspace);
4603}
4604
4605void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
4606 unsigned Size = DL.getTypeSizeInBits(Ty).getFixedValue();
4607 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
4608 Check(!(Size & (Size - 1)),
4609 "atomic memory access' operand must have a power-of-two size", Ty, I);
4610}
4611
4612void Verifier::visitLoadInst(LoadInst &LI) {
4614 Check(PTy, "Load operand must be a pointer.", &LI);
4615 Type *ElTy = LI.getType();
4616 if (MaybeAlign A = LI.getAlign()) {
4617 Check(A->value() <= Value::MaximumAlignment,
4618 "huge alignment values are unsupported", &LI);
4619 }
4620 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
4621 if (LI.isAtomic()) {
4622 Check(LI.getOrdering() != AtomicOrdering::Release &&
4623 LI.getOrdering() != AtomicOrdering::AcquireRelease,
4624 "Load cannot have Release ordering", &LI);
4625 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4627 "atomic load operand must have integer, pointer, floating point, "
4628 "or vector type!",
4629 ElTy, &LI);
4630
4631 checkAtomicMemAccessSize(ElTy, &LI);
4632 } else {
4634 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4635 }
4636
4637 visitInstruction(LI);
4638}
4639
4640void Verifier::visitStoreInst(StoreInst &SI) {
4641 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
4642 Check(PTy, "Store operand must be a pointer.", &SI);
4643 Type *ElTy = SI.getOperand(0)->getType();
4644 if (MaybeAlign A = SI.getAlign()) {
4645 Check(A->value() <= Value::MaximumAlignment,
4646 "huge alignment values are unsupported", &SI);
4647 }
4648 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
4649 if (SI.isAtomic()) {
4650 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
4651 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4652 "Store cannot have Acquire ordering", &SI);
4653 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
4655 "atomic store operand must have integer, pointer, floating point, "
4656 "or vector type!",
4657 ElTy, &SI);
4658 checkAtomicMemAccessSize(ElTy, &SI);
4659 } else {
4660 Check(SI.getSyncScopeID() == SyncScope::System,
4661 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4662 }
4663 visitInstruction(SI);
4664}
4665
4666/// Check that SwiftErrorVal is used as a swifterror argument in CS.
4667void Verifier::verifySwiftErrorCall(CallBase &Call,
4668 const Value *SwiftErrorVal) {
4669 for (const auto &I : llvm::enumerate(Call.args())) {
4670 if (I.value() == SwiftErrorVal) {
4671 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
4672 "swifterror value when used in a callsite should be marked "
4673 "with swifterror attribute",
4674 SwiftErrorVal, Call);
4675 }
4676 }
4677}
4678
4679void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
4680 // Check that swifterror value is only used by loads, stores, or as
4681 // a swifterror argument.
4682 for (const User *U : SwiftErrorVal->users()) {
4684 isa<InvokeInst>(U),
4685 "swifterror value can only be loaded and stored from, or "
4686 "as a swifterror argument!",
4687 SwiftErrorVal, U);
4688 // If it is used by a store, check it is the second operand.
4689 if (auto StoreI = dyn_cast<StoreInst>(U))
4690 Check(StoreI->getOperand(1) == SwiftErrorVal,
4691 "swifterror value should be the second operand when used "
4692 "by stores",
4693 SwiftErrorVal, U);
4694 if (auto *Call = dyn_cast<CallBase>(U))
4695 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
4696 }
4697}
4698
4699void Verifier::visitAllocaInst(AllocaInst &AI) {
4700 Type *Ty = AI.getAllocatedType();
4701 SmallPtrSet<Type*, 4> Visited;
4702 Check(Ty->isSized(&Visited), "Cannot allocate unsized type", &AI);
4703 // Check if it's a target extension type that disallows being used on the
4704 // stack.
4706 "Alloca has illegal target extension type", &AI);
4708 "Alloca array size must have integer type", &AI);
4709 if (MaybeAlign A = AI.getAlign()) {
4710 Check(A->value() <= Value::MaximumAlignment,
4711 "huge alignment values are unsupported", &AI);
4712 }
4713
4714 if (AI.isSwiftError()) {
4715 Check(Ty->isPointerTy(), "swifterror alloca must have pointer type", &AI);
4717 "swifterror alloca must not be array allocation", &AI);
4718 verifySwiftErrorValue(&AI);
4719 }
4720
4721 if (TT.isAMDGPU()) {
4723 "alloca on amdgpu must be in addrspace(5)", &AI);
4724 }
4725
4726 visitInstruction(AI);
4727}
4728
4729void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4730 Type *ElTy = CXI.getOperand(1)->getType();
4731 Check(ElTy->isIntOrPtrTy(),
4732 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4733 checkAtomicMemAccessSize(ElTy, &CXI);
4734 visitInstruction(CXI);
4735}
4736
4737void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4738 Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
4739 "atomicrmw instructions cannot be unordered.", &RMWI);
4740 auto Op = RMWI.getOperation();
4741 Type *ElTy = RMWI.getOperand(1)->getType();
4742 if (Op == AtomicRMWInst::Xchg) {
4743 Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
4744 ElTy->isPointerTy(),
4745 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4746 " operand must have integer or floating point type!",
4747 &RMWI, ElTy);
4748 } else if (AtomicRMWInst::isFPOperation(Op)) {
4750 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4751 " operand must have floating-point or fixed vector of floating-point "
4752 "type!",
4753 &RMWI, ElTy);
4754 } else {
4755 Check(ElTy->isIntegerTy(),
4756 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4757 " operand must have integer type!",
4758 &RMWI, ElTy);
4759 }
4760 checkAtomicMemAccessSize(ElTy, &RMWI);
4762 "Invalid binary operation!", &RMWI);
4763 visitInstruction(RMWI);
4764}
4765
4766void Verifier::visitFenceInst(FenceInst &FI) {
4767 const AtomicOrdering Ordering = FI.getOrdering();
4768 Check(Ordering == AtomicOrdering::Acquire ||
4769 Ordering == AtomicOrdering::Release ||
4770 Ordering == AtomicOrdering::AcquireRelease ||
4771 Ordering == AtomicOrdering::SequentiallyConsistent,
4772 "fence instructions may only have acquire, release, acq_rel, or "
4773 "seq_cst ordering.",
4774 &FI);
4775 visitInstruction(FI);
4776}
4777
4778void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4780 EVI.getIndices()) == EVI.getType(),
4781 "Invalid ExtractValueInst operands!", &EVI);
4782
4783 visitInstruction(EVI);
4784}
4785
4786void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4788 IVI.getIndices()) ==
4789 IVI.getOperand(1)->getType(),
4790 "Invalid InsertValueInst operands!", &IVI);
4791
4792 visitInstruction(IVI);
4793}
4794
4795static Value *getParentPad(Value *EHPad) {
4796 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4797 return FPI->getParentPad();
4798
4799 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4800}
4801
4802void Verifier::visitEHPadPredecessors(Instruction &I) {
4803 assert(I.isEHPad());
4804
4805 BasicBlock *BB = I.getParent();
4806 Function *F = BB->getParent();
4807
4808 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
4809
4810 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
4811 // The landingpad instruction defines its parent as a landing pad block. The
4812 // landing pad block may be branched to only by the unwind edge of an
4813 // invoke.
4814 for (BasicBlock *PredBB : predecessors(BB)) {
4815 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4816 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4817 "Block containing LandingPadInst must be jumped to "
4818 "only by the unwind edge of an invoke.",
4819 LPI);
4820 }
4821 return;
4822 }
4823 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
4824 if (!pred_empty(BB))
4825 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
4826 "Block containg CatchPadInst must be jumped to "
4827 "only by its catchswitch.",
4828 CPI);
4829 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4830 "Catchswitch cannot unwind to one of its catchpads",
4831 CPI->getCatchSwitch(), CPI);
4832 return;
4833 }
4834
4835 // Verify that each pred has a legal terminator with a legal to/from EH
4836 // pad relationship.
4837 Instruction *ToPad = &I;
4838 Value *ToPadParent = getParentPad(ToPad);
4839 for (BasicBlock *PredBB : predecessors(BB)) {
4840 Instruction *TI = PredBB->getTerminator();
4841 Value *FromPad;
4842 if (auto *II = dyn_cast<InvokeInst>(TI)) {
4843 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4844 "EH pad must be jumped to via an unwind edge", ToPad, II);
4845 auto *CalledFn =
4846 dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
4847 if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
4848 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
4849 continue;
4850 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
4851 FromPad = Bundle->Inputs[0];
4852 else
4853 FromPad = ConstantTokenNone::get(II->getContext());
4854 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4855 FromPad = CRI->getOperand(0);
4856 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
4857 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4858 FromPad = CSI;
4859 } else {
4860 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
4861 }
4862
4863 // The edge may exit from zero or more nested pads.
4864 SmallPtrSet<Value *, 8> Seen;
4865 for (;; FromPad = getParentPad(FromPad)) {
4866 Check(FromPad != ToPad,
4867 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4868 if (FromPad == ToPadParent) {
4869 // This is a legal unwind edge.
4870 break;
4871 }
4872 Check(!isa<ConstantTokenNone>(FromPad),
4873 "A single unwind edge may only enter one EH pad", TI);
4874 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
4875 FromPad);
4876
4877 // This will be diagnosed on the corresponding instruction already. We
4878 // need the extra check here to make sure getParentPad() works.
4879 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4880 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4881 }
4882 }
4883}
4884
4885void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4886 // The landingpad instruction is ill-formed if it doesn't have any clauses and
4887 // isn't a cleanup.
4888 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
4889 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4890
4891 visitEHPadPredecessors(LPI);
4892
4893 if (!LandingPadResultTy)
4894 LandingPadResultTy = LPI.getType();
4895 else
4896 Check(LandingPadResultTy == LPI.getType(),
4897 "The landingpad instruction should have a consistent result type "
4898 "inside a function.",
4899 &LPI);
4900
4901 Function *F = LPI.getParent()->getParent();
4902 Check(F->hasPersonalityFn(),
4903 "LandingPadInst needs to be in a function with a personality.", &LPI);
4904
4905 // The landingpad instruction must be the first non-PHI instruction in the
4906 // block.
4907 Check(LPI.getParent()->getLandingPadInst() == &LPI,
4908 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4909
4910 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4911 Constant *Clause = LPI.getClause(i);
4912 if (LPI.isCatch(i)) {
4913 Check(isa<PointerType>(Clause->getType()),
4914 "Catch operand does not have pointer type!", &LPI);
4915 } else {
4916 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4918 "Filter operand is not an array of constants!", &LPI);
4919 }
4920 }
4921
4922 visitInstruction(LPI);
4923}
4924
4925void Verifier::visitResumeInst(ResumeInst &RI) {
4927 "ResumeInst needs to be in a function with a personality.", &RI);
4928
4929 if (!LandingPadResultTy)
4930 LandingPadResultTy = RI.getValue()->getType();
4931 else
4932 Check(LandingPadResultTy == RI.getValue()->getType(),
4933 "The resume instruction should have a consistent result type "
4934 "inside a function.",
4935 &RI);
4936
4937 visitTerminator(RI);
4938}
4939
4940void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4941 BasicBlock *BB = CPI.getParent();
4942
4943 Function *F = BB->getParent();
4944 Check(F->hasPersonalityFn(),
4945 "CatchPadInst needs to be in a function with a personality.", &CPI);
4946
4948 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4949 CPI.getParentPad());
4950
4951 // The catchpad instruction must be the first non-PHI instruction in the
4952 // block.
4953 Check(&*BB->getFirstNonPHIIt() == &CPI,
4954 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4955
4956 visitEHPadPredecessors(CPI);
4957 visitFuncletPadInst(CPI);
4958}
4959
4960void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4961 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4962 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4963 CatchReturn.getOperand(0));
4964
4965 visitTerminator(CatchReturn);
4966}
4967
4968void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4969 BasicBlock *BB = CPI.getParent();
4970
4971 Function *F = BB->getParent();
4972 Check(F->hasPersonalityFn(),
4973 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4974
4975 // The cleanuppad instruction must be the first non-PHI instruction in the
4976 // block.
4977 Check(&*BB->getFirstNonPHIIt() == &CPI,
4978 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4979
4980 auto *ParentPad = CPI.getParentPad();
4981 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4982 "CleanupPadInst has an invalid parent.", &CPI);
4983
4984 visitEHPadPredecessors(CPI);
4985 visitFuncletPadInst(CPI);
4986}
4987
4988void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4989 User *FirstUser = nullptr;
4990 Value *FirstUnwindPad = nullptr;
4991 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4992 SmallPtrSet<FuncletPadInst *, 8> Seen;
4993
4994 while (!Worklist.empty()) {
4995 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4996 Check(Seen.insert(CurrentPad).second,
4997 "FuncletPadInst must not be nested within itself", CurrentPad);
4998 Value *UnresolvedAncestorPad = nullptr;
4999 for (User *U : CurrentPad->users()) {
5000 BasicBlock *UnwindDest;
5001 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
5002 UnwindDest = CRI->getUnwindDest();
5003 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
5004 // We allow catchswitch unwind to caller to nest
5005 // within an outer pad that unwinds somewhere else,
5006 // because catchswitch doesn't have a nounwind variant.
5007 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
5008 if (CSI->unwindsToCaller())
5009 continue;
5010 UnwindDest = CSI->getUnwindDest();
5011 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
5012 UnwindDest = II->getUnwindDest();
5013 } else if (isa<CallInst>(U)) {
5014 // Calls which don't unwind may be found inside funclet
5015 // pads that unwind somewhere else. We don't *require*
5016 // such calls to be annotated nounwind.
5017 continue;
5018 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
5019 // The unwind dest for a cleanup can only be found by
5020 // recursive search. Add it to the worklist, and we'll
5021 // search for its first use that determines where it unwinds.
5022 Worklist.push_back(CPI);
5023 continue;
5024 } else {
5025 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
5026 continue;
5027 }
5028
5029 Value *UnwindPad;
5030 bool ExitsFPI;
5031 if (UnwindDest) {
5032 UnwindPad = &*UnwindDest->getFirstNonPHIIt();
5033 if (!cast<Instruction>(UnwindPad)->isEHPad())
5034 continue;
5035 Value *UnwindParent = getParentPad(UnwindPad);
5036 // Ignore unwind edges that don't exit CurrentPad.
5037 if (UnwindParent == CurrentPad)
5038 continue;
5039 // Determine whether the original funclet pad is exited,
5040 // and if we are scanning nested pads determine how many
5041 // of them are exited so we can stop searching their
5042 // children.
5043 Value *ExitedPad = CurrentPad;
5044 ExitsFPI = false;
5045 do {
5046 if (ExitedPad == &FPI) {
5047 ExitsFPI = true;
5048 // Now we can resolve any ancestors of CurrentPad up to
5049 // FPI, but not including FPI since we need to make sure
5050 // to check all direct users of FPI for consistency.
5051 UnresolvedAncestorPad = &FPI;
5052 break;
5053 }
5054 Value *ExitedParent = getParentPad(ExitedPad);
5055 if (ExitedParent == UnwindParent) {
5056 // ExitedPad is the ancestor-most pad which this unwind
5057 // edge exits, so we can resolve up to it, meaning that
5058 // ExitedParent is the first ancestor still unresolved.
5059 UnresolvedAncestorPad = ExitedParent;
5060 break;
5061 }
5062 ExitedPad = ExitedParent;
5063 } while (!isa<ConstantTokenNone>(ExitedPad));
5064 } else {
5065 // Unwinding to caller exits all pads.
5066 UnwindPad = ConstantTokenNone::get(FPI.getContext());
5067 ExitsFPI = true;
5068 UnresolvedAncestorPad = &FPI;
5069 }
5070
5071 if (ExitsFPI) {
5072 // This unwind edge exits FPI. Make sure it agrees with other
5073 // such edges.
5074 if (FirstUser) {
5075 Check(UnwindPad == FirstUnwindPad,
5076 "Unwind edges out of a funclet "
5077 "pad must have the same unwind "
5078 "dest",
5079 &FPI, U, FirstUser);
5080 } else {
5081 FirstUser = U;
5082 FirstUnwindPad = UnwindPad;
5083 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
5084 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
5085 getParentPad(UnwindPad) == getParentPad(&FPI))
5086 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
5087 }
5088 }
5089 // Make sure we visit all uses of FPI, but for nested pads stop as
5090 // soon as we know where they unwind to.
5091 if (CurrentPad != &FPI)
5092 break;
5093 }
5094 if (UnresolvedAncestorPad) {
5095 if (CurrentPad == UnresolvedAncestorPad) {
5096 // When CurrentPad is FPI itself, we don't mark it as resolved even if
5097 // we've found an unwind edge that exits it, because we need to verify
5098 // all direct uses of FPI.
5099 assert(CurrentPad == &FPI);
5100 continue;
5101 }
5102 // Pop off the worklist any nested pads that we've found an unwind
5103 // destination for. The pads on the worklist are the uncles,
5104 // great-uncles, etc. of CurrentPad. We've found an unwind destination
5105 // for all ancestors of CurrentPad up to but not including
5106 // UnresolvedAncestorPad.
5107 Value *ResolvedPad = CurrentPad;
5108 while (!Worklist.empty()) {
5109 Value *UnclePad = Worklist.back();
5110 Value *AncestorPad = getParentPad(UnclePad);
5111 // Walk ResolvedPad up the ancestor list until we either find the
5112 // uncle's parent or the last resolved ancestor.
5113 while (ResolvedPad != AncestorPad) {
5114 Value *ResolvedParent = getParentPad(ResolvedPad);
5115 if (ResolvedParent == UnresolvedAncestorPad) {
5116 break;
5117 }
5118 ResolvedPad = ResolvedParent;
5119 }
5120 // If the resolved ancestor search didn't find the uncle's parent,
5121 // then the uncle is not yet resolved.
5122 if (ResolvedPad != AncestorPad)
5123 break;
5124 // This uncle is resolved, so pop it from the worklist.
5125 Worklist.pop_back();
5126 }
5127 }
5128 }
5129
5130 if (FirstUnwindPad) {
5131 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
5132 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5133 Value *SwitchUnwindPad;
5134 if (SwitchUnwindDest)
5135 SwitchUnwindPad = &*SwitchUnwindDest->getFirstNonPHIIt();
5136 else
5137 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
5138 Check(SwitchUnwindPad == FirstUnwindPad,
5139 "Unwind edges out of a catch must have the same unwind dest as "
5140 "the parent catchswitch",
5141 &FPI, FirstUser, CatchSwitch);
5142 }
5143 }
5144
5145 visitInstruction(FPI);
5146}
5147
5148void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5149 BasicBlock *BB = CatchSwitch.getParent();
5150
5151 Function *F = BB->getParent();
5152 Check(F->hasPersonalityFn(),
5153 "CatchSwitchInst needs to be in a function with a personality.",
5154 &CatchSwitch);
5155
5156 // The catchswitch instruction must be the first non-PHI instruction in the
5157 // block.
5158 Check(&*BB->getFirstNonPHIIt() == &CatchSwitch,
5159 "CatchSwitchInst not the first non-PHI instruction in the block.",
5160 &CatchSwitch);
5161
5162 auto *ParentPad = CatchSwitch.getParentPad();
5163 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5164 "CatchSwitchInst has an invalid parent.", ParentPad);
5165
5166 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
5167 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5168 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5169 "CatchSwitchInst must unwind to an EH block which is not a "
5170 "landingpad.",
5171 &CatchSwitch);
5172
5173 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
5174 if (getParentPad(&*I) == ParentPad)
5175 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5176 }
5177
5178 Check(CatchSwitch.getNumHandlers() != 0,
5179 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5180
5181 for (BasicBlock *Handler : CatchSwitch.handlers()) {
5182 Check(isa<CatchPadInst>(Handler->getFirstNonPHIIt()),
5183 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5184 }
5185
5186 visitEHPadPredecessors(CatchSwitch);
5187 visitTerminator(CatchSwitch);
5188}
5189
5190void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5192 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5193 CRI.getOperand(0));
5194
5195 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
5196 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5197 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5198 "CleanupReturnInst must unwind to an EH block which is not a "
5199 "landingpad.",
5200 &CRI);
5201 }
5202
5203 visitTerminator(CRI);
5204}
5205
5206void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
5207 Instruction *Op = cast<Instruction>(I.getOperand(i));
5208 // If the we have an invalid invoke, don't try to compute the dominance.
5209 // We already reject it in the invoke specific checks and the dominance
5210 // computation doesn't handle multiple edges.
5211 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
5212 if (II->getNormalDest() == II->getUnwindDest())
5213 return;
5214 }
5215
5216 // Quick check whether the def has already been encountered in the same block.
5217 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
5218 // uses are defined to happen on the incoming edge, not at the instruction.
5219 //
5220 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
5221 // wrapping an SSA value, assert that we've already encountered it. See
5222 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
5223 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
5224 return;
5225
5226 const Use &U = I.getOperandUse(i);
5227 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
5228}
5229
5230void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
5231 Check(I.getType()->isPointerTy(),
5232 "dereferenceable, dereferenceable_or_null "
5233 "apply only to pointer types",
5234 &I);
5236 "dereferenceable, dereferenceable_or_null apply only to load"
5237 " and inttoptr instructions, use attributes for calls or invokes",
5238 &I);
5239 Check(MD->getNumOperands() == 1,
5240 "dereferenceable, dereferenceable_or_null "
5241 "take one operand!",
5242 &I);
5243 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
5244 Check(CI && CI->getType()->isIntegerTy(64),
5245 "dereferenceable, "
5246 "dereferenceable_or_null metadata value must be an i64!",
5247 &I);
5248}
5249
5250void Verifier::visitNofreeMetadata(Instruction &I, MDNode *MD) {
5251 Check(I.getType()->isPointerTy(), "nofree applies only to pointer types", &I);
5252 Check((isa<IntToPtrInst>(I)), "nofree applies only to inttoptr instruction",
5253 &I);
5254 Check(MD->getNumOperands() == 0, "nofree metadata must be empty", &I);
5255}
5256
5257void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
5258 auto GetBranchingTerminatorNumOperands = [&]() {
5259 unsigned ExpectedNumOperands = 0;
5260 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5261 ExpectedNumOperands = BI->getNumSuccessors();
5262 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5263 ExpectedNumOperands = SI->getNumSuccessors();
5264 else if (isa<CallInst>(&I))
5265 ExpectedNumOperands = 1;
5266 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5267 ExpectedNumOperands = IBI->getNumDestinations();
5268 else if (isa<SelectInst>(&I))
5269 ExpectedNumOperands = 2;
5270 else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
5271 ExpectedNumOperands = CI->getNumSuccessors();
5272 return ExpectedNumOperands;
5273 };
5274 Check(MD->getNumOperands() >= 1,
5275 "!prof annotations should have at least 1 operand", MD);
5276 // Check first operand.
5277 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
5279 "expected string with name of the !prof annotation", MD);
5280 MDString *MDS = cast<MDString>(MD->getOperand(0));
5281 StringRef ProfName = MDS->getString();
5282
5284 Check(GetBranchingTerminatorNumOperands() != 0 || isa<InvokeInst>(I),
5285 "'unknown' !prof should only appear on instructions on which "
5286 "'branch_weights' would",
5287 MD);
5288 verifyUnknownProfileMetadata(MD);
5289 return;
5290 }
5291
5292 Check(MD->getNumOperands() >= 2,
5293 "!prof annotations should have no less than 2 operands", MD);
5294
5295 // Check consistency of !prof branch_weights metadata.
5296 if (ProfName == MDProfLabels::BranchWeights) {
5297 unsigned NumBranchWeights = getNumBranchWeights(*MD);
5298 if (isa<InvokeInst>(&I)) {
5299 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5300 "Wrong number of InvokeInst branch_weights operands", MD);
5301 } else {
5302 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5303 if (ExpectedNumOperands == 0)
5304 CheckFailed("!prof branch_weights are not allowed for this instruction",
5305 MD);
5306
5307 Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
5308 MD);
5309 }
5310 for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
5311 ++i) {
5312 auto &MDO = MD->getOperand(i);
5313 Check(MDO, "second operand should not be null", MD);
5315 "!prof brunch_weights operand is not a const int");
5316 }
5317 } else if (ProfName == MDProfLabels::ValueProfile) {
5318 Check(isValueProfileMD(MD), "invalid value profiling metadata", MD);
5319 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
5320 Check(KindInt, "VP !prof missing kind argument", MD);
5321
5322 auto Kind = KindInt->getZExtValue();
5323 Check(Kind >= InstrProfValueKind::IPVK_First &&
5324 Kind <= InstrProfValueKind::IPVK_Last,
5325 "Invalid VP !prof kind", MD);
5326 Check(MD->getNumOperands() % 2 == 1,
5327 "VP !prof should have an even number "
5328 "of arguments after 'VP'",
5329 MD);
5330 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5331 Kind == InstrProfValueKind::IPVK_MemOPSize)
5333 "VP !prof indirect call or memop size expected to be applied to "
5334 "CallBase instructions only",
5335 MD);
5336 } else {
5337 CheckFailed("expected either branch_weights or VP profile name", MD);
5338 }
5339}
5340
5341void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
5342 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
5343 // DIAssignID metadata must be attached to either an alloca or some form of
5344 // store/memory-writing instruction.
5345 // FIXME: We allow all intrinsic insts here to avoid trying to enumerate all
5346 // possible store intrinsics.
5347 bool ExpectedInstTy =
5349 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
5350 I, MD);
5351 // Iterate over the MetadataAsValue uses of the DIAssignID - these should
5352 // only be found as DbgAssignIntrinsic operands.
5353 if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
5354 for (auto *User : AsValue->users()) {
5356 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5357 MD, User);
5358 // All of the dbg.assign intrinsics should be in the same function as I.
5359 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
5360 CheckDI(DAI->getFunction() == I.getFunction(),
5361 "dbg.assign not in same function as inst", DAI, &I);
5362 }
5363 }
5364 for (DbgVariableRecord *DVR :
5365 cast<DIAssignID>(MD)->getAllDbgVariableRecordUsers()) {
5366 CheckDI(DVR->isDbgAssign(),
5367 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5368 CheckDI(DVR->getFunction() == I.getFunction(),
5369 "DVRAssign not in same function as inst", DVR, &I);
5370 }
5371}
5372
5373void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
5375 "!mmra metadata attached to unexpected instruction kind", I, MD);
5376
5377 // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
5378 // list of tags such as !2 in the following example:
5379 // !0 = !{!"a", !"b"}
5380 // !1 = !{!"c", !"d"}
5381 // !2 = !{!0, !1}
5382 if (MMRAMetadata::isTagMD(MD))
5383 return;
5384
5385 Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
5386 for (const MDOperand &MDOp : MD->operands())
5387 Check(MMRAMetadata::isTagMD(MDOp.get()),
5388 "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
5389}
5390
5391void Verifier::visitCallStackMetadata(MDNode *MD) {
5392 // Call stack metadata should consist of a list of at least 1 constant int
5393 // (representing a hash of the location).
5394 Check(MD->getNumOperands() >= 1,
5395 "call stack metadata should have at least 1 operand", MD);
5396
5397 for (const auto &Op : MD->operands())
5399 "call stack metadata operand should be constant integer", Op);
5400}
5401
5402void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
5403 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
5404 Check(MD->getNumOperands() >= 1,
5405 "!memprof annotations should have at least 1 metadata operand "
5406 "(MemInfoBlock)",
5407 MD);
5408
5409 // Check each MIB
5410 for (auto &MIBOp : MD->operands()) {
5411 MDNode *MIB = dyn_cast<MDNode>(MIBOp);
5412 // The first operand of an MIB should be the call stack metadata.
5413 // There rest of the operands should be MDString tags, and there should be
5414 // at least one.
5415 Check(MIB->getNumOperands() >= 2,
5416 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5417
5418 // Check call stack metadata (first operand).
5419 Check(MIB->getOperand(0) != nullptr,
5420 "!memprof MemInfoBlock first operand should not be null", MIB);
5421 Check(isa<MDNode>(MIB->getOperand(0)),
5422 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5423 MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
5424 visitCallStackMetadata(StackMD);
5425
5426 // The second MIB operand should be MDString.
5428 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5429
5430 // Any remaining should be MDNode that are pairs of integers
5431 for (unsigned I = 2; I < MIB->getNumOperands(); ++I) {
5432 MDNode *OpNode = dyn_cast<MDNode>(MIB->getOperand(I));
5433 Check(OpNode, "Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5434 MIB);
5435 Check(OpNode->getNumOperands() == 2,
5436 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5437 "operands",
5438 MIB);
5439 // Check that all of Op's operands are ConstantInt.
5440 Check(llvm::all_of(OpNode->operands(),
5441 [](const MDOperand &Op) {
5442 return mdconst::hasa<ConstantInt>(Op);
5443 }),
5444 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5445 "ConstantInt operands",
5446 MIB);
5447 }
5448 }
5449}
5450
5451void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
5452 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
5453 // Verify the partial callstack annotated from memprof profiles. This callsite
5454 // is a part of a profiled allocation callstack.
5455 visitCallStackMetadata(MD);
5456}
5457
5458static inline bool isConstantIntMetadataOperand(const Metadata *MD) {
5459 if (auto *VAL = dyn_cast<ValueAsMetadata>(MD))
5460 return isa<ConstantInt>(VAL->getValue());
5461 return false;
5462}
5463
5464void Verifier::visitCalleeTypeMetadata(Instruction &I, MDNode *MD) {
5465 Check(isa<CallBase>(I), "!callee_type metadata should only exist on calls",
5466 &I);
5467 for (Metadata *Op : MD->operands()) {
5469 "The callee_type metadata must be a list of type metadata nodes", Op);
5470 auto *TypeMD = cast<MDNode>(Op);
5471 Check(TypeMD->getNumOperands() == 2,
5472 "Well-formed generalized type metadata must contain exactly two "
5473 "operands",
5474 Op);
5475 Check(isConstantIntMetadataOperand(TypeMD->getOperand(0)) &&
5476 mdconst::extract<ConstantInt>(TypeMD->getOperand(0))->isZero(),
5477 "The first operand of type metadata for functions must be zero", Op);
5478 Check(TypeMD->hasGeneralizedMDString(),
5479 "Only generalized type metadata can be part of the callee_type "
5480 "metadata list",
5481 Op);
5482 }
5483}
5484
5485void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5486 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
5487 Check(Annotation->getNumOperands() >= 1,
5488 "annotation must have at least one operand");
5489 for (const MDOperand &Op : Annotation->operands()) {
5490 bool TupleOfStrings =
5491 isa<MDTuple>(Op.get()) &&
5492 all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
5493 return isa<MDString>(Annotation.get());
5494 });
5495 Check(isa<MDString>(Op.get()) || TupleOfStrings,
5496 "operands must be a string or a tuple of strings");
5497 }
5498}
5499
5500void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
5501 unsigned NumOps = MD->getNumOperands();
5502 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
5503 MD);
5504 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
5505 "first scope operand must be self-referential or string", MD);
5506 if (NumOps == 3)
5508 "third scope operand must be string (if used)", MD);
5509
5510 MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
5511 Check(Domain != nullptr, "second scope operand must be MDNode", MD);
5512
5513 unsigned NumDomainOps = Domain->getNumOperands();
5514 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5515 "domain must have one or two operands", Domain);
5516 Check(Domain->getOperand(0).get() == Domain ||
5517 isa<MDString>(Domain->getOperand(0)),
5518 "first domain operand must be self-referential or string", Domain);
5519 if (NumDomainOps == 2)
5520 Check(isa<MDString>(Domain->getOperand(1)),
5521 "second domain operand must be string (if used)", Domain);
5522}
5523
5524void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
5525 for (const MDOperand &Op : MD->operands()) {
5526 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5527 Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
5528 visitAliasScopeMetadata(OpMD);
5529 }
5530}
5531
5532void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
5533 auto IsValidAccessScope = [](const MDNode *MD) {
5534 return MD->getNumOperands() == 0 && MD->isDistinct();
5535 };
5536
5537 // It must be either an access scope itself...
5538 if (IsValidAccessScope(MD))
5539 return;
5540
5541 // ...or a list of access scopes.
5542 for (const MDOperand &Op : MD->operands()) {
5543 const MDNode *OpMD = dyn_cast<MDNode>(Op);
5544 Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
5545 Check(IsValidAccessScope(OpMD),
5546 "Access scope list contains invalid access scope", MD);
5547 }
5548}
5549
5550void Verifier::visitCapturesMetadata(Instruction &I, const MDNode *Captures) {
5551 static const char *ValidArgs[] = {"address_is_null", "address",
5552 "read_provenance", "provenance"};
5553
5554 auto *SI = dyn_cast<StoreInst>(&I);
5555 Check(SI, "!captures metadata can only be applied to store instructions", &I);
5556 Check(SI->getValueOperand()->getType()->isPointerTy(),
5557 "!captures metadata can only be applied to store with value operand of "
5558 "pointer type",
5559 &I);
5560 Check(Captures->getNumOperands() != 0, "!captures metadata cannot be empty",
5561 &I);
5562
5563 for (Metadata *Op : Captures->operands()) {
5564 auto *Str = dyn_cast<MDString>(Op);
5565 Check(Str, "!captures metadata must be a list of strings", &I);
5566 Check(is_contained(ValidArgs, Str->getString()),
5567 "invalid entry in !captures metadata", &I, Str);
5568 }
5569}
5570
5571void Verifier::visitAllocTokenMetadata(Instruction &I, MDNode *MD) {
5572 Check(isa<CallBase>(I), "!alloc_token should only exist on calls", &I);
5573 Check(MD->getNumOperands() == 2, "!alloc_token must have 2 operands", MD);
5574 Check(isa<MDString>(MD->getOperand(0)), "expected string", MD);
5576 "expected integer constant", MD);
5577}
5578
5579/// verifyInstruction - Verify that an instruction is well formed.
5580///
5581void Verifier::visitInstruction(Instruction &I) {
5582 BasicBlock *BB = I.getParent();
5583 Check(BB, "Instruction not embedded in basic block!", &I);
5584
5585 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
5586 for (User *U : I.users()) {
5587 Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
5588 "Only PHI nodes may reference their own value!", &I);
5589 }
5590 }
5591
5592 // Check that void typed values don't have names
5593 Check(!I.getType()->isVoidTy() || !I.hasName(),
5594 "Instruction has a name, but provides a void value!", &I);
5595
5596 // Check that the return value of the instruction is either void or a legal
5597 // value type.
5598 Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
5599 "Instruction returns a non-scalar type!", &I);
5600
5601 // Check that the instruction doesn't produce metadata. Calls are already
5602 // checked against the callee type.
5603 Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
5604 "Invalid use of metadata!", &I);
5605
5606 // Check that all uses of the instruction, if they are instructions
5607 // themselves, actually have parent basic blocks. If the use is not an
5608 // instruction, it is an error!
5609 for (Use &U : I.uses()) {
5610 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
5611 Check(Used->getParent() != nullptr,
5612 "Instruction referencing"
5613 " instruction not embedded in a basic block!",
5614 &I, Used);
5615 else {
5616 CheckFailed("Use of instruction is not an instruction!", U);
5617 return;
5618 }
5619 }
5620
5621 // Get a pointer to the call base of the instruction if it is some form of
5622 // call.
5623 const CallBase *CBI = dyn_cast<CallBase>(&I);
5624
5625 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
5626 Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
5627
5628 // Check to make sure that only first-class-values are operands to
5629 // instructions.
5630 if (!I.getOperand(i)->getType()->isFirstClassType()) {
5631 Check(false, "Instruction operands must be first-class values!", &I);
5632 }
5633
5634 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
5635 // This code checks whether the function is used as the operand of a
5636 // clang_arc_attachedcall operand bundle.
5637 auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
5638 int Idx) {
5639 return CBI && CBI->isOperandBundleOfType(
5641 };
5642
5643 // Check to make sure that the "address of" an intrinsic function is never
5644 // taken. Ignore cases where the address of the intrinsic function is used
5645 // as the argument of operand bundle "clang.arc.attachedcall" as those
5646 // cases are handled in verifyAttachedCallBundle.
5647 Check((!F->isIntrinsic() ||
5648 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
5649 IsAttachedCallOperand(F, CBI, i)),
5650 "Cannot take the address of an intrinsic!", &I);
5651 Check(!F->isIntrinsic() || isa<CallInst>(I) || isa<CallBrInst>(I) ||
5652 F->getIntrinsicID() == Intrinsic::donothing ||
5653 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5654 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5655 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5656 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5657 F->getIntrinsicID() == Intrinsic::coro_resume ||
5658 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5659 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5660 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5661 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5662 F->getIntrinsicID() ==
5663 Intrinsic::experimental_patchpoint_void ||
5664 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5665 F->getIntrinsicID() == Intrinsic::fake_use ||
5666 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5667 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5668 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5669 IsAttachedCallOperand(F, CBI, i),
5670 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5671 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5672 "wasm.(re)throw",
5673 &I);
5674 Check(F->getParent() == &M, "Referencing function in another module!", &I,
5675 &M, F, F->getParent());
5676 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
5677 Check(OpBB->getParent() == BB->getParent(),
5678 "Referring to a basic block in another function!", &I);
5679 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
5680 Check(OpArg->getParent() == BB->getParent(),
5681 "Referring to an argument in another function!", &I);
5682 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
5683 Check(GV->getParent() == &M, "Referencing global in another module!", &I,
5684 &M, GV, GV->getParent());
5685 } else if (Instruction *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
5686 Check(OpInst->getFunction() == BB->getParent(),
5687 "Referring to an instruction in another function!", &I);
5688 verifyDominatesUse(I, i);
5689 } else if (isa<InlineAsm>(I.getOperand(i))) {
5690 Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
5691 "Cannot take the address of an inline asm!", &I);
5692 } else if (auto *C = dyn_cast<Constant>(I.getOperand(i))) {
5693 visitConstantExprsRecursively(C);
5694 }
5695 }
5696
5697 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
5698 Check(I.getType()->isFPOrFPVectorTy(),
5699 "fpmath requires a floating point result!", &I);
5700 Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
5701 if (ConstantFP *CFP0 =
5703 const APFloat &Accuracy = CFP0->getValueAPF();
5704 Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
5705 "fpmath accuracy must have float type", &I);
5706 Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
5707 "fpmath accuracy not a positive number!", &I);
5708 } else {
5709 Check(false, "invalid fpmath accuracy!", &I);
5710 }
5711 }
5712
5713 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
5715 "Ranges are only for loads, calls and invokes!", &I);
5716 visitRangeMetadata(I, Range, I.getType());
5717 }
5718
5719 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofpclass)) {
5720 Check(isa<LoadInst>(I), "nofpclass is only for loads", &I);
5721 visitNoFPClassMetadata(I, MD, I.getType());
5722 }
5723
5724 if (MDNode *Range = I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5727 "noalias.addrspace are only for memory operations!", &I);
5728 visitNoaliasAddrspaceMetadata(I, Range, I.getType());
5729 }
5730
5731 if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
5733 "invariant.group metadata is only for loads and stores", &I);
5734 }
5735
5736 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
5737 Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
5738 &I);
5740 "nonnull applies only to load instructions, use attributes"
5741 " for calls or invokes",
5742 &I);
5743 Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
5744 }
5745
5746 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
5747 visitDereferenceableMetadata(I, MD);
5748
5749 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5750 visitDereferenceableMetadata(I, MD);
5751
5752 if (MDNode *MD = I.getMetadata(LLVMContext::MD_nofree))
5753 visitNofreeMetadata(I, MD);
5754
5755 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
5756 TBAAVerifyHelper.visitTBAAMetadata(&I, TBAA);
5757
5758 if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5759 visitAliasScopeListMetadata(MD);
5760 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5761 visitAliasScopeListMetadata(MD);
5762
5763 if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
5764 visitAccessGroupMetadata(MD);
5765
5766 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
5767 Check(I.getType()->isPointerTy(), "align applies only to pointer types",
5768 &I);
5770 "align applies only to load instructions, "
5771 "use attributes for calls or invokes",
5772 &I);
5773 Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
5774 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
5775 Check(CI && CI->getType()->isIntegerTy(64),
5776 "align metadata value must be an i64!", &I);
5777 uint64_t Align = CI->getZExtValue();
5778 Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
5779 &I);
5780 Check(Align <= Value::MaximumAlignment,
5781 "alignment is larger that implementation defined limit", &I);
5782 }
5783
5784 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
5785 visitProfMetadata(I, MD);
5786
5787 if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
5788 visitMemProfMetadata(I, MD);
5789
5790 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
5791 visitCallsiteMetadata(I, MD);
5792
5793 if (MDNode *MD = I.getMetadata(LLVMContext::MD_callee_type))
5794 visitCalleeTypeMetadata(I, MD);
5795
5796 if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
5797 visitDIAssignIDMetadata(I, MD);
5798
5799 if (MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra))
5800 visitMMRAMetadata(I, MMRA);
5801
5802 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
5803 visitAnnotationMetadata(Annotation);
5804
5805 if (MDNode *Captures = I.getMetadata(LLVMContext::MD_captures))
5806 visitCapturesMetadata(I, Captures);
5807
5808 if (MDNode *MD = I.getMetadata(LLVMContext::MD_alloc_token))
5809 visitAllocTokenMetadata(I, MD);
5810
5811 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
5812 CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
5813 visitMDNode(*N, AreDebugLocsAllowed::Yes);
5814
5815 if (auto *DL = dyn_cast<DILocation>(N)) {
5816 if (DL->getAtomGroup()) {
5817 CheckDI(DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5818 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5819 "Instructions enabled",
5820 DL, DL->getScope()->getSubprogram());
5821 }
5822 }
5823 }
5824
5826 I.getAllMetadata(MDs);
5827 for (auto Attachment : MDs) {
5828 unsigned Kind = Attachment.first;
5829 auto AllowLocs =
5830 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
5831 ? AreDebugLocsAllowed::Yes
5832 : AreDebugLocsAllowed::No;
5833 visitMDNode(*Attachment.second, AllowLocs);
5834 }
5835
5836 InstsInThisBlock.insert(&I);
5837}
5838
5839/// Allow intrinsics to be verified in different ways.
5840void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
5842 Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
5843 IF);
5844
5845 // Verify that the intrinsic prototype lines up with what the .td files
5846 // describe.
5847 FunctionType *IFTy = IF->getFunctionType();
5848 bool IsVarArg = IFTy->isVarArg();
5849
5853
5854 // Walk the descriptors to extract overloaded types.
5859 "Intrinsic has incorrect return type!", IF);
5861 "Intrinsic has incorrect argument type!", IF);
5862
5863 // Verify if the intrinsic call matches the vararg property.
5864 if (IsVarArg)
5866 "Intrinsic was not defined with variable arguments!", IF);
5867 else
5869 "Callsite was not defined with variable arguments!", IF);
5870
5871 // All descriptors should be absorbed by now.
5872 Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
5873
5874 // Now that we have the intrinsic ID and the actual argument types (and we
5875 // know they are legal for the intrinsic!) get the intrinsic name through the
5876 // usual means. This allows us to verify the mangling of argument types into
5877 // the name.
5878 const std::string ExpectedName =
5879 Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
5880 Check(ExpectedName == IF->getName(),
5881 "Intrinsic name not mangled correctly for type arguments! "
5882 "Should be: " +
5883 ExpectedName,
5884 IF);
5885
5886 // If the intrinsic takes MDNode arguments, verify that they are either global
5887 // or are local to *this* function.
5888 for (Value *V : Call.args()) {
5889 if (auto *MD = dyn_cast<MetadataAsValue>(V))
5890 visitMetadataAsValue(*MD, Call.getCaller());
5891 if (auto *Const = dyn_cast<Constant>(V))
5892 Check(!Const->getType()->isX86_AMXTy(),
5893 "const x86_amx is not allowed in argument!");
5894 }
5895
5896 switch (ID) {
5897 default:
5898 break;
5899 case Intrinsic::assume: {
5900 if (Call.hasOperandBundles()) {
5902 Check(Cond && Cond->isOne(),
5903 "assume with operand bundles must have i1 true condition", Call);
5904 }
5905 for (auto &Elem : Call.bundle_op_infos()) {
5906 unsigned ArgCount = Elem.End - Elem.Begin;
5907 // Separate storage assumptions are special insofar as they're the only
5908 // operand bundles allowed on assumes that aren't parameter attributes.
5909 if (Elem.Tag->getKey() == "separate_storage") {
5910 Check(ArgCount == 2,
5911 "separate_storage assumptions should have 2 arguments", Call);
5912 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
5913 Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
5914 "arguments to separate_storage assumptions should be pointers",
5915 Call);
5916 continue;
5917 }
5918 Check(Elem.Tag->getKey() == "ignore" ||
5919 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5920 "tags must be valid attribute names", Call);
5921 Attribute::AttrKind Kind =
5922 Attribute::getAttrKindFromName(Elem.Tag->getKey());
5923 if (Kind == Attribute::Alignment) {
5924 Check(ArgCount <= 3 && ArgCount >= 2,
5925 "alignment assumptions should have 2 or 3 arguments", Call);
5926 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5927 "first argument should be a pointer", Call);
5928 Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5929 "second argument should be an integer", Call);
5930 if (ArgCount == 3)
5931 Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
5932 "third argument should be an integer if present", Call);
5933 continue;
5934 }
5935 if (Kind == Attribute::Dereferenceable) {
5936 Check(ArgCount == 2,
5937 "dereferenceable assumptions should have 2 arguments", Call);
5938 Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5939 "first argument should be a pointer", Call);
5940 Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5941 "second argument should be an integer", Call);
5942 continue;
5943 }
5944 Check(ArgCount <= 2, "too many arguments", Call);
5945 if (Kind == Attribute::None)
5946 break;
5947 if (Attribute::isIntAttrKind(Kind)) {
5948 Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
5949 Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
5950 "the second argument should be a constant integral value", Call);
5951 } else if (Attribute::canUseAsParamAttr(Kind)) {
5952 Check((ArgCount) == 1, "this attribute should have one argument", Call);
5953 } else if (Attribute::canUseAsFnAttr(Kind)) {
5954 Check((ArgCount) == 0, "this attribute has no argument", Call);
5955 }
5956 }
5957 break;
5958 }
5959 case Intrinsic::ucmp:
5960 case Intrinsic::scmp: {
5961 Type *SrcTy = Call.getOperand(0)->getType();
5962 Type *DestTy = Call.getType();
5963
5964 Check(DestTy->getScalarSizeInBits() >= 2,
5965 "result type must be at least 2 bits wide", Call);
5966
5967 bool IsDestTypeVector = DestTy->isVectorTy();
5968 Check(SrcTy->isVectorTy() == IsDestTypeVector,
5969 "ucmp/scmp argument and result types must both be either vector or "
5970 "scalar types",
5971 Call);
5972 if (IsDestTypeVector) {
5973 auto SrcVecLen = cast<VectorType>(SrcTy)->getElementCount();
5974 auto DestVecLen = cast<VectorType>(DestTy)->getElementCount();
5975 Check(SrcVecLen == DestVecLen,
5976 "return type and arguments must have the same number of "
5977 "elements",
5978 Call);
5979 }
5980 break;
5981 }
5982 case Intrinsic::coro_id: {
5983 auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
5984 if (isa<ConstantPointerNull>(InfoArg))
5985 break;
5986 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
5987 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
5988 "info argument of llvm.coro.id must refer to an initialized "
5989 "constant");
5990 Constant *Init = GV->getInitializer();
5992 "info argument of llvm.coro.id must refer to either a struct or "
5993 "an array");
5994 break;
5995 }
5996 case Intrinsic::is_fpclass: {
5997 const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
5998 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
5999 "unsupported bits for llvm.is.fpclass test mask");
6000 break;
6001 }
6002 case Intrinsic::fptrunc_round: {
6003 // Check the rounding mode
6004 Metadata *MD = nullptr;
6006 if (MAV)
6007 MD = MAV->getMetadata();
6008
6009 Check(MD != nullptr, "missing rounding mode argument", Call);
6010
6011 Check(isa<MDString>(MD),
6012 ("invalid value for llvm.fptrunc.round metadata operand"
6013 " (the operand should be a string)"),
6014 MD);
6015
6016 std::optional<RoundingMode> RoundMode =
6017 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6018 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6019 "unsupported rounding mode argument", Call);
6020 break;
6021 }
6022 case Intrinsic::convert_to_arbitrary_fp: {
6023 // Check that vector element counts are consistent.
6024 Type *ValueTy = Call.getArgOperand(0)->getType();
6025 Type *IntTy = Call.getType();
6026
6027 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6028 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6029 Check(IntVecTy,
6030 "if floating-point operand is a vector, integer operand must also "
6031 "be a vector",
6032 Call);
6033 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6034 "floating-point and integer vector operands must have the same "
6035 "element count",
6036 Call);
6037 }
6038
6039 // Check interpretation metadata (argoperand 1).
6040 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6041 Check(InterpMAV, "missing interpretation metadata operand", Call);
6042 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6043 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6044 StringRef Interp = InterpStr->getString();
6045
6046 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6047 Call);
6048
6049 // Valid interpretation strings: mini-float format names.
6051 "unsupported interpretation metadata string", Call);
6052
6053 // Check rounding mode metadata (argoperand 2).
6054 auto *RoundingMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(2));
6055 Check(RoundingMAV, "missing rounding mode metadata operand", Call);
6056 auto *RoundingStr = dyn_cast<MDString>(RoundingMAV->getMetadata());
6057 Check(RoundingStr, "rounding mode metadata operand must be a string", Call);
6058
6059 std::optional<RoundingMode> RM =
6060 convertStrToRoundingMode(RoundingStr->getString());
6061 Check(RM && *RM != RoundingMode::Dynamic,
6062 "unsupported rounding mode argument", Call);
6063 break;
6064 }
6065 case Intrinsic::convert_from_arbitrary_fp: {
6066 // Check that vector element counts are consistent.
6067 Type *IntTy = Call.getArgOperand(0)->getType();
6068 Type *ValueTy = Call.getType();
6069
6070 if (auto *ValueVecTy = dyn_cast<VectorType>(ValueTy)) {
6071 auto *IntVecTy = dyn_cast<VectorType>(IntTy);
6072 Check(IntVecTy,
6073 "if floating-point operand is a vector, integer operand must also "
6074 "be a vector",
6075 Call);
6076 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6077 "floating-point and integer vector operands must have the same "
6078 "element count",
6079 Call);
6080 }
6081
6082 // Check interpretation metadata (argoperand 1).
6083 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6084 Check(InterpMAV, "missing interpretation metadata operand", Call);
6085 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6086 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6087 StringRef Interp = InterpStr->getString();
6088
6089 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6090 Call);
6091
6092 // Valid interpretation strings: mini-float format names.
6094 "unsupported interpretation metadata string", Call);
6095 break;
6096 }
6097#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6098#include "llvm/IR/VPIntrinsics.def"
6099#undef BEGIN_REGISTER_VP_INTRINSIC
6100 visitVPIntrinsic(cast<VPIntrinsic>(Call));
6101 break;
6102#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6103 case Intrinsic::INTRINSIC:
6104#include "llvm/IR/ConstrainedOps.def"
6105#undef INSTRUCTION
6106 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
6107 break;
6108 case Intrinsic::dbg_declare: // llvm.dbg.declare
6109 case Intrinsic::dbg_value: // llvm.dbg.value
6110 case Intrinsic::dbg_assign: // llvm.dbg.assign
6111 case Intrinsic::dbg_label: // llvm.dbg.label
6112 // We no longer interpret debug intrinsics (the old variable-location
6113 // design). They're meaningless as far as LLVM is concerned we could make
6114 // it an error for them to appear, but it's possible we'll have users
6115 // converting back to intrinsics for the forseeable future (such as DXIL),
6116 // so tolerate their existance.
6117 break;
6118 case Intrinsic::memcpy:
6119 case Intrinsic::memcpy_inline:
6120 case Intrinsic::memmove:
6121 case Intrinsic::memset:
6122 case Intrinsic::memset_inline:
6123 break;
6124 case Intrinsic::experimental_memset_pattern: {
6125 const auto Memset = cast<MemSetPatternInst>(&Call);
6126 Check(Memset->getValue()->getType()->isSized(),
6127 "unsized types cannot be used as memset patterns", Call);
6128 break;
6129 }
6130 case Intrinsic::memcpy_element_unordered_atomic:
6131 case Intrinsic::memmove_element_unordered_atomic:
6132 case Intrinsic::memset_element_unordered_atomic: {
6133 const auto *AMI = cast<AnyMemIntrinsic>(&Call);
6134
6135 ConstantInt *ElementSizeCI =
6136 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
6137 const APInt &ElementSizeVal = ElementSizeCI->getValue();
6138 Check(ElementSizeVal.isPowerOf2(),
6139 "element size of the element-wise atomic memory intrinsic "
6140 "must be a power of 2",
6141 Call);
6142
6143 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6144 return Alignment && ElementSizeVal.ule(Alignment->value());
6145 };
6146 Check(IsValidAlignment(AMI->getDestAlign()),
6147 "incorrect alignment of the destination argument", Call);
6148 if (const auto *AMT = dyn_cast<AnyMemTransferInst>(AMI)) {
6149 Check(IsValidAlignment(AMT->getSourceAlign()),
6150 "incorrect alignment of the source argument", Call);
6151 }
6152 break;
6153 }
6154 case Intrinsic::call_preallocated_setup: {
6155 auto *NumArgs = cast<ConstantInt>(Call.getArgOperand(0));
6156 bool FoundCall = false;
6157 for (User *U : Call.users()) {
6158 auto *UseCall = dyn_cast<CallBase>(U);
6159 Check(UseCall != nullptr,
6160 "Uses of llvm.call.preallocated.setup must be calls");
6161 Intrinsic::ID IID = UseCall->getIntrinsicID();
6162 if (IID == Intrinsic::call_preallocated_arg) {
6163 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
6164 Check(AllocArgIndex != nullptr,
6165 "llvm.call.preallocated.alloc arg index must be a constant");
6166 auto AllocArgIndexInt = AllocArgIndex->getValue();
6167 Check(AllocArgIndexInt.sge(0) &&
6168 AllocArgIndexInt.slt(NumArgs->getValue()),
6169 "llvm.call.preallocated.alloc arg index must be between 0 and "
6170 "corresponding "
6171 "llvm.call.preallocated.setup's argument count");
6172 } else if (IID == Intrinsic::call_preallocated_teardown) {
6173 // nothing to do
6174 } else {
6175 Check(!FoundCall, "Can have at most one call corresponding to a "
6176 "llvm.call.preallocated.setup");
6177 FoundCall = true;
6178 size_t NumPreallocatedArgs = 0;
6179 for (unsigned i = 0; i < UseCall->arg_size(); i++) {
6180 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6181 ++NumPreallocatedArgs;
6182 }
6183 }
6184 Check(NumPreallocatedArgs != 0,
6185 "cannot use preallocated intrinsics on a call without "
6186 "preallocated arguments");
6187 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6188 "llvm.call.preallocated.setup arg size must be equal to number "
6189 "of preallocated arguments "
6190 "at call site",
6191 Call, *UseCall);
6192 // getOperandBundle() cannot be called if more than one of the operand
6193 // bundle exists. There is already a check elsewhere for this, so skip
6194 // here if we see more than one.
6195 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
6196 1) {
6197 return;
6198 }
6199 auto PreallocatedBundle =
6200 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
6201 Check(PreallocatedBundle,
6202 "Use of llvm.call.preallocated.setup outside intrinsics "
6203 "must be in \"preallocated\" operand bundle");
6204 Check(PreallocatedBundle->Inputs.front().get() == &Call,
6205 "preallocated bundle must have token from corresponding "
6206 "llvm.call.preallocated.setup");
6207 }
6208 }
6209 break;
6210 }
6211 case Intrinsic::call_preallocated_arg: {
6212 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6213 Check(Token &&
6214 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6215 "llvm.call.preallocated.arg token argument must be a "
6216 "llvm.call.preallocated.setup");
6217 Check(Call.hasFnAttr(Attribute::Preallocated),
6218 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6219 "call site attribute");
6220 break;
6221 }
6222 case Intrinsic::call_preallocated_teardown: {
6223 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6224 Check(Token &&
6225 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6226 "llvm.call.preallocated.teardown token argument must be a "
6227 "llvm.call.preallocated.setup");
6228 break;
6229 }
6230 case Intrinsic::gcroot:
6231 case Intrinsic::gcwrite:
6232 case Intrinsic::gcread:
6233 if (ID == Intrinsic::gcroot) {
6234 AllocaInst *AI =
6236 Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
6238 "llvm.gcroot parameter #2 must be a constant.", Call);
6239 if (!AI->getAllocatedType()->isPointerTy()) {
6241 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6242 "or argument #2 must be a non-null constant.",
6243 Call);
6244 }
6245 }
6246
6247 Check(Call.getParent()->getParent()->hasGC(),
6248 "Enclosing function does not use GC.", Call);
6249 break;
6250 case Intrinsic::init_trampoline:
6252 "llvm.init_trampoline parameter #2 must resolve to a function.",
6253 Call);
6254 break;
6255 case Intrinsic::prefetch:
6256 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6257 "rw argument to llvm.prefetch must be 0-1", Call);
6258 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
6259 "locality argument to llvm.prefetch must be 0-3", Call);
6260 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
6261 "cache type argument to llvm.prefetch must be 0-1", Call);
6262 break;
6263 case Intrinsic::reloc_none: {
6265 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata()),
6266 "llvm.reloc.none argument must be a metadata string", &Call);
6267 break;
6268 }
6269 case Intrinsic::stackprotector:
6271 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
6272 break;
6273 case Intrinsic::localescape: {
6274 BasicBlock *BB = Call.getParent();
6275 Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
6276 Call);
6277 Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
6278 Call);
6279 for (Value *Arg : Call.args()) {
6280 if (isa<ConstantPointerNull>(Arg))
6281 continue; // Null values are allowed as placeholders.
6282 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
6283 Check(AI && AI->isStaticAlloca(),
6284 "llvm.localescape only accepts static allocas", Call);
6285 }
6286 FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
6287 SawFrameEscape = true;
6288 break;
6289 }
6290 case Intrinsic::localrecover: {
6292 Function *Fn = dyn_cast<Function>(FnArg);
6293 Check(Fn && !Fn->isDeclaration(),
6294 "llvm.localrecover first "
6295 "argument must be function defined in this module",
6296 Call);
6297 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
6298 auto &Entry = FrameEscapeInfo[Fn];
6299 Entry.second = unsigned(
6300 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6301 break;
6302 }
6303
6304 case Intrinsic::experimental_gc_statepoint:
6305 if (auto *CI = dyn_cast<CallInst>(&Call))
6306 Check(!CI->isInlineAsm(),
6307 "gc.statepoint support for inline assembly unimplemented", CI);
6308 Check(Call.getParent()->getParent()->hasGC(),
6309 "Enclosing function does not use GC.", Call);
6310
6311 verifyStatepoint(Call);
6312 break;
6313 case Intrinsic::experimental_gc_result: {
6314 Check(Call.getParent()->getParent()->hasGC(),
6315 "Enclosing function does not use GC.", Call);
6316
6317 auto *Statepoint = Call.getArgOperand(0);
6318 if (isa<UndefValue>(Statepoint))
6319 break;
6320
6321 // Are we tied to a statepoint properly?
6322 const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
6323 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6324 Intrinsic::experimental_gc_statepoint,
6325 "gc.result operand #1 must be from a statepoint", Call,
6326 Call.getArgOperand(0));
6327
6328 // Check that result type matches wrapped callee.
6329 auto *TargetFuncType =
6330 cast<FunctionType>(StatepointCall->getParamElementType(2));
6331 Check(Call.getType() == TargetFuncType->getReturnType(),
6332 "gc.result result type does not match wrapped callee", Call);
6333 break;
6334 }
6335 case Intrinsic::experimental_gc_relocate: {
6336 Check(Call.arg_size() == 3, "wrong number of arguments", Call);
6337
6339 "gc.relocate must return a pointer or a vector of pointers", Call);
6340
6341 // Check that this relocate is correctly tied to the statepoint
6342
6343 // This is case for relocate on the unwinding path of an invoke statepoint
6344 if (LandingPadInst *LandingPad =
6346
6347 const BasicBlock *InvokeBB =
6348 LandingPad->getParent()->getUniquePredecessor();
6349
6350 // Landingpad relocates should have only one predecessor with invoke
6351 // statepoint terminator
6352 Check(InvokeBB, "safepoints should have unique landingpads",
6353 LandingPad->getParent());
6354 Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
6355 InvokeBB);
6357 "gc relocate should be linked to a statepoint", InvokeBB);
6358 } else {
6359 // In all other cases relocate should be tied to the statepoint directly.
6360 // This covers relocates on a normal return path of invoke statepoint and
6361 // relocates of a call statepoint.
6362 auto *Token = Call.getArgOperand(0);
6364 "gc relocate is incorrectly tied to the statepoint", Call, Token);
6365 }
6366
6367 // Verify rest of the relocate arguments.
6368 const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
6369
6370 // Both the base and derived must be piped through the safepoint.
6373 "gc.relocate operand #2 must be integer offset", Call);
6374
6375 Value *Derived = Call.getArgOperand(2);
6376 Check(isa<ConstantInt>(Derived),
6377 "gc.relocate operand #3 must be integer offset", Call);
6378
6379 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
6380 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
6381
6382 // Check the bounds
6383 if (isa<UndefValue>(StatepointCall))
6384 break;
6385 if (auto Opt = cast<GCStatepointInst>(StatepointCall)
6386 .getOperandBundle(LLVMContext::OB_gc_live)) {
6387 Check(BaseIndex < Opt->Inputs.size(),
6388 "gc.relocate: statepoint base index out of bounds", Call);
6389 Check(DerivedIndex < Opt->Inputs.size(),
6390 "gc.relocate: statepoint derived index out of bounds", Call);
6391 }
6392
6393 // Relocated value must be either a pointer type or vector-of-pointer type,
6394 // but gc_relocate does not need to return the same pointer type as the
6395 // relocated pointer. It can be casted to the correct type later if it's
6396 // desired. However, they must have the same address space and 'vectorness'
6397 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
6398 auto *ResultType = Call.getType();
6399 auto *DerivedType = Relocate.getDerivedPtr()->getType();
6400 auto *BaseType = Relocate.getBasePtr()->getType();
6401
6402 Check(BaseType->isPtrOrPtrVectorTy(),
6403 "gc.relocate: relocated value must be a pointer", Call);
6404 Check(DerivedType->isPtrOrPtrVectorTy(),
6405 "gc.relocate: relocated value must be a pointer", Call);
6406
6407 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6408 "gc.relocate: vector relocates to vector and pointer to pointer",
6409 Call);
6410 Check(
6411 ResultType->getPointerAddressSpace() ==
6412 DerivedType->getPointerAddressSpace(),
6413 "gc.relocate: relocating a pointer shouldn't change its address space",
6414 Call);
6415
6416 auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
6417 Check(GC, "gc.relocate: calling function must have GCStrategy",
6418 Call.getFunction());
6419 if (GC) {
6420 auto isGCPtr = [&GC](Type *PTy) {
6421 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
6422 };
6423 Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
6424 Check(isGCPtr(BaseType),
6425 "gc.relocate: relocated value must be a gc pointer", Call);
6426 Check(isGCPtr(DerivedType),
6427 "gc.relocate: relocated value must be a gc pointer", Call);
6428 }
6429 break;
6430 }
6431 case Intrinsic::experimental_patchpoint: {
6432 if (Call.getCallingConv() == CallingConv::AnyReg) {
6434 "patchpoint: invalid return type used with anyregcc", Call);
6435 }
6436 break;
6437 }
6438 case Intrinsic::eh_exceptioncode:
6439 case Intrinsic::eh_exceptionpointer: {
6441 "eh.exceptionpointer argument must be a catchpad", Call);
6442 break;
6443 }
6444 case Intrinsic::get_active_lane_mask: {
6446 "get_active_lane_mask: must return a "
6447 "vector",
6448 Call);
6449 auto *ElemTy = Call.getType()->getScalarType();
6450 Check(ElemTy->isIntegerTy(1),
6451 "get_active_lane_mask: element type is not "
6452 "i1",
6453 Call);
6454 break;
6455 }
6456 case Intrinsic::experimental_get_vector_length: {
6457 ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
6458 Check(!VF->isNegative() && !VF->isZero(),
6459 "get_vector_length: VF must be positive", Call);
6460 break;
6461 }
6462 case Intrinsic::masked_load: {
6463 Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
6464 Call);
6465
6467 Value *PassThru = Call.getArgOperand(2);
6468 Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
6469 Call);
6470 Check(PassThru->getType() == Call.getType(),
6471 "masked_load: pass through and return type must match", Call);
6472 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6473 cast<VectorType>(Call.getType())->getElementCount(),
6474 "masked_load: vector mask must be same length as return", Call);
6475 break;
6476 }
6477 case Intrinsic::masked_store: {
6478 Value *Val = Call.getArgOperand(0);
6480 Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
6481 Call);
6482 Check(cast<VectorType>(Mask->getType())->getElementCount() ==
6483 cast<VectorType>(Val->getType())->getElementCount(),
6484 "masked_store: vector mask must be same length as value", Call);
6485 break;
6486 }
6487
6488 case Intrinsic::experimental_guard: {
6489 Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
6491 "experimental_guard must have exactly one "
6492 "\"deopt\" operand bundle");
6493 break;
6494 }
6495
6496 case Intrinsic::experimental_deoptimize: {
6497 Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
6498 Call);
6500 "experimental_deoptimize must have exactly one "
6501 "\"deopt\" operand bundle");
6503 "experimental_deoptimize return type must match caller return type");
6504
6505 if (isa<CallInst>(Call)) {
6507 Check(RI,
6508 "calls to experimental_deoptimize must be followed by a return");
6509
6510 if (!Call.getType()->isVoidTy() && RI)
6511 Check(RI->getReturnValue() == &Call,
6512 "calls to experimental_deoptimize must be followed by a return "
6513 "of the value computed by experimental_deoptimize");
6514 }
6515
6516 break;
6517 }
6518 case Intrinsic::vastart: {
6520 "va_start called in a non-varargs function");
6521 break;
6522 }
6523 case Intrinsic::get_dynamic_area_offset: {
6524 auto *IntTy = dyn_cast<IntegerType>(Call.getType());
6525 Check(IntTy && DL.getPointerSizeInBits(DL.getAllocaAddrSpace()) ==
6526 IntTy->getBitWidth(),
6527 "get_dynamic_area_offset result type must be scalar integer matching "
6528 "alloca address space width",
6529 Call);
6530 break;
6531 }
6532 case Intrinsic::vector_reduce_and:
6533 case Intrinsic::vector_reduce_or:
6534 case Intrinsic::vector_reduce_xor:
6535 case Intrinsic::vector_reduce_add:
6536 case Intrinsic::vector_reduce_mul:
6537 case Intrinsic::vector_reduce_smax:
6538 case Intrinsic::vector_reduce_smin:
6539 case Intrinsic::vector_reduce_umax:
6540 case Intrinsic::vector_reduce_umin: {
6541 Type *ArgTy = Call.getArgOperand(0)->getType();
6542 Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
6543 "Intrinsic has incorrect argument type!");
6544 break;
6545 }
6546 case Intrinsic::vector_reduce_fmax:
6547 case Intrinsic::vector_reduce_fmin: {
6548 Type *ArgTy = Call.getArgOperand(0)->getType();
6549 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6550 "Intrinsic has incorrect argument type!");
6551 break;
6552 }
6553 case Intrinsic::vector_reduce_fadd:
6554 case Intrinsic::vector_reduce_fmul: {
6555 // Unlike the other reductions, the first argument is a start value. The
6556 // second argument is the vector to be reduced.
6557 Type *ArgTy = Call.getArgOperand(1)->getType();
6558 Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
6559 "Intrinsic has incorrect argument type!");
6560 break;
6561 }
6562 case Intrinsic::smul_fix:
6563 case Intrinsic::smul_fix_sat:
6564 case Intrinsic::umul_fix:
6565 case Intrinsic::umul_fix_sat:
6566 case Intrinsic::sdiv_fix:
6567 case Intrinsic::sdiv_fix_sat:
6568 case Intrinsic::udiv_fix:
6569 case Intrinsic::udiv_fix_sat: {
6570 Value *Op1 = Call.getArgOperand(0);
6571 Value *Op2 = Call.getArgOperand(1);
6573 "first operand of [us][mul|div]_fix[_sat] must be an int type or "
6574 "vector of ints");
6576 "second operand of [us][mul|div]_fix[_sat] must be an int type or "
6577 "vector of ints");
6578
6579 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
6580 Check(Op3->getType()->isIntegerTy(),
6581 "third operand of [us][mul|div]_fix[_sat] must be an int type");
6582 Check(Op3->getBitWidth() <= 32,
6583 "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
6584
6585 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6586 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6587 Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
6588 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6589 "the operands");
6590 } else {
6591 Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
6592 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6593 "to the width of the operands");
6594 }
6595 break;
6596 }
6597 case Intrinsic::lrint:
6598 case Intrinsic::llrint:
6599 case Intrinsic::lround:
6600 case Intrinsic::llround: {
6601 Type *ValTy = Call.getArgOperand(0)->getType();
6602 Type *ResultTy = Call.getType();
6603 auto *VTy = dyn_cast<VectorType>(ValTy);
6604 auto *RTy = dyn_cast<VectorType>(ResultTy);
6605 Check(ValTy->isFPOrFPVectorTy() && ResultTy->isIntOrIntVectorTy(),
6606 ExpectedName + ": argument must be floating-point or vector "
6607 "of floating-points, and result must be integer or "
6608 "vector of integers",
6609 &Call);
6610 Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
6611 ExpectedName + ": argument and result disagree on vector use", &Call);
6612 if (VTy) {
6613 Check(VTy->getElementCount() == RTy->getElementCount(),
6614 ExpectedName + ": argument must be same length as result", &Call);
6615 }
6616 break;
6617 }
6618 case Intrinsic::bswap: {
6619 Type *Ty = Call.getType();
6620 unsigned Size = Ty->getScalarSizeInBits();
6621 Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
6622 break;
6623 }
6624 case Intrinsic::invariant_start: {
6625 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
6626 Check(InvariantSize &&
6627 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6628 "invariant_start parameter must be -1, 0 or a positive number",
6629 &Call);
6630 break;
6631 }
6632 case Intrinsic::matrix_multiply:
6633 case Intrinsic::matrix_transpose:
6634 case Intrinsic::matrix_column_major_load:
6635 case Intrinsic::matrix_column_major_store: {
6637 ConstantInt *Stride = nullptr;
6638 ConstantInt *NumRows;
6639 ConstantInt *NumColumns;
6640 VectorType *ResultTy;
6641 Type *Op0ElemTy = nullptr;
6642 Type *Op1ElemTy = nullptr;
6643 switch (ID) {
6644 case Intrinsic::matrix_multiply: {
6645 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
6646 ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
6647 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6649 ->getNumElements() ==
6650 NumRows->getZExtValue() * N->getZExtValue(),
6651 "First argument of a matrix operation does not match specified "
6652 "shape!");
6654 ->getNumElements() ==
6655 N->getZExtValue() * NumColumns->getZExtValue(),
6656 "Second argument of a matrix operation does not match specified "
6657 "shape!");
6658
6659 ResultTy = cast<VectorType>(Call.getType());
6660 Op0ElemTy =
6661 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6662 Op1ElemTy =
6663 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
6664 break;
6665 }
6666 case Intrinsic::matrix_transpose:
6667 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
6668 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
6669 ResultTy = cast<VectorType>(Call.getType());
6670 Op0ElemTy =
6671 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6672 break;
6673 case Intrinsic::matrix_column_major_load: {
6675 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
6676 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
6677 ResultTy = cast<VectorType>(Call.getType());
6678 break;
6679 }
6680 case Intrinsic::matrix_column_major_store: {
6682 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
6683 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
6684 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
6685 Op0ElemTy =
6686 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
6687 break;
6688 }
6689 default:
6690 llvm_unreachable("unexpected intrinsic");
6691 }
6692
6693 Check(ResultTy->getElementType()->isIntegerTy() ||
6694 ResultTy->getElementType()->isFloatingPointTy(),
6695 "Result type must be an integer or floating-point type!", IF);
6696
6697 if (Op0ElemTy)
6698 Check(ResultTy->getElementType() == Op0ElemTy,
6699 "Vector element type mismatch of the result and first operand "
6700 "vector!",
6701 IF);
6702
6703 if (Op1ElemTy)
6704 Check(ResultTy->getElementType() == Op1ElemTy,
6705 "Vector element type mismatch of the result and second operand "
6706 "vector!",
6707 IF);
6708
6710 NumRows->getZExtValue() * NumColumns->getZExtValue(),
6711 "Result of a matrix operation does not fit in the returned vector!");
6712
6713 if (Stride) {
6714 Check(Stride->getBitWidth() <= 64, "Stride bitwidth cannot exceed 64!",
6715 IF);
6716 Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
6717 "Stride must be greater or equal than the number of rows!", IF);
6718 }
6719
6720 break;
6721 }
6722 case Intrinsic::stepvector: {
6724 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6725 VecTy->getScalarSizeInBits() >= 8,
6726 "stepvector only supported for vectors of integers "
6727 "with a bitwidth of at least 8.",
6728 &Call);
6729 break;
6730 }
6731 case Intrinsic::experimental_vector_match: {
6732 Value *Op1 = Call.getArgOperand(0);
6733 Value *Op2 = Call.getArgOperand(1);
6735
6736 VectorType *Op1Ty = dyn_cast<VectorType>(Op1->getType());
6737 VectorType *Op2Ty = dyn_cast<VectorType>(Op2->getType());
6738 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
6739
6740 Check(Op1Ty && Op2Ty && MaskTy, "Operands must be vectors.", &Call);
6742 "Second operand must be a fixed length vector.", &Call);
6743 Check(Op1Ty->getElementType()->isIntegerTy(),
6744 "First operand must be a vector of integers.", &Call);
6745 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6746 "First two operands must have the same element type.", &Call);
6747 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6748 "First operand and mask must have the same number of elements.",
6749 &Call);
6750 Check(MaskTy->getElementType()->isIntegerTy(1),
6751 "Mask must be a vector of i1's.", &Call);
6752 Check(Call.getType() == MaskTy, "Return type must match the mask type.",
6753 &Call);
6754 break;
6755 }
6756 case Intrinsic::vector_insert: {
6757 Value *Vec = Call.getArgOperand(0);
6758 Value *SubVec = Call.getArgOperand(1);
6759 Value *Idx = Call.getArgOperand(2);
6760 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6761
6762 VectorType *VecTy = cast<VectorType>(Vec->getType());
6763 VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
6764
6765 ElementCount VecEC = VecTy->getElementCount();
6766 ElementCount SubVecEC = SubVecTy->getElementCount();
6767 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6768 "vector_insert parameters must have the same element "
6769 "type.",
6770 &Call);
6771 Check(IdxN % SubVecEC.getKnownMinValue() == 0,
6772 "vector_insert index must be a constant multiple of "
6773 "the subvector's known minimum vector length.");
6774
6775 // If this insertion is not the 'mixed' case where a fixed vector is
6776 // inserted into a scalable vector, ensure that the insertion of the
6777 // subvector does not overrun the parent vector.
6778 if (VecEC.isScalable() == SubVecEC.isScalable()) {
6779 Check(IdxN < VecEC.getKnownMinValue() &&
6780 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
6781 "subvector operand of vector_insert would overrun the "
6782 "vector being inserted into.");
6783 }
6784 break;
6785 }
6786 case Intrinsic::vector_extract: {
6787 Value *Vec = Call.getArgOperand(0);
6788 Value *Idx = Call.getArgOperand(1);
6789 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6790
6791 VectorType *ResultTy = cast<VectorType>(Call.getType());
6792 VectorType *VecTy = cast<VectorType>(Vec->getType());
6793
6794 ElementCount VecEC = VecTy->getElementCount();
6795 ElementCount ResultEC = ResultTy->getElementCount();
6796
6797 Check(ResultTy->getElementType() == VecTy->getElementType(),
6798 "vector_extract result must have the same element "
6799 "type as the input vector.",
6800 &Call);
6801 Check(IdxN % ResultEC.getKnownMinValue() == 0,
6802 "vector_extract index must be a constant multiple of "
6803 "the result type's known minimum vector length.");
6804
6805 // If this extraction is not the 'mixed' case where a fixed vector is
6806 // extracted from a scalable vector, ensure that the extraction does not
6807 // overrun the parent vector.
6808 if (VecEC.isScalable() == ResultEC.isScalable()) {
6809 Check(IdxN < VecEC.getKnownMinValue() &&
6810 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
6811 "vector_extract would overrun.");
6812 }
6813 break;
6814 }
6815 case Intrinsic::vector_partial_reduce_fadd:
6816 case Intrinsic::vector_partial_reduce_add: {
6819
6820 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6821 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6822
6823 Check((VecWidth % AccWidth) == 0,
6824 "Invalid vector widths for partial "
6825 "reduction. The width of the input vector "
6826 "must be a positive integer multiple of "
6827 "the width of the accumulator vector.");
6828 break;
6829 }
6830 case Intrinsic::experimental_noalias_scope_decl: {
6831 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
6832 break;
6833 }
6834 case Intrinsic::preserve_array_access_index:
6835 case Intrinsic::preserve_struct_access_index:
6836 case Intrinsic::aarch64_ldaxr:
6837 case Intrinsic::aarch64_ldxr:
6838 case Intrinsic::arm_ldaex:
6839 case Intrinsic::arm_ldrex: {
6840 Type *ElemTy = Call.getParamElementType(0);
6841 Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
6842 &Call);
6843 break;
6844 }
6845 case Intrinsic::aarch64_stlxr:
6846 case Intrinsic::aarch64_stxr:
6847 case Intrinsic::arm_stlex:
6848 case Intrinsic::arm_strex: {
6849 Type *ElemTy = Call.getAttributes().getParamElementType(1);
6850 Check(ElemTy,
6851 "Intrinsic requires elementtype attribute on second argument.",
6852 &Call);
6853 break;
6854 }
6855 case Intrinsic::aarch64_prefetch: {
6856 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6857 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6858 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
6859 "target argument to llvm.aarch64.prefetch must be 0-3", Call);
6860 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
6861 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6862 Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
6863 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6864 break;
6865 }
6866 case Intrinsic::aarch64_range_prefetch: {
6867 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6868 "write argument to llvm.aarch64.range.prefetch must be 0 or 1", Call);
6869 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 2,
6870 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6871 Call);
6872 break;
6873 }
6874 case Intrinsic::callbr_landingpad: {
6875 const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
6876 Check(CBR, "intrinstic requires callbr operand", &Call);
6877 if (!CBR)
6878 break;
6879
6880 const BasicBlock *LandingPadBB = Call.getParent();
6881 const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
6882 if (!PredBB) {
6883 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
6884 break;
6885 }
6886 if (!isa<CallBrInst>(PredBB->getTerminator())) {
6887 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
6888 &Call);
6889 break;
6890 }
6891 Check(llvm::is_contained(CBR->getIndirectDests(), LandingPadBB),
6892 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6893 "block in indirect destination list",
6894 &Call);
6895 const Instruction &First = *LandingPadBB->begin();
6896 Check(&First == &Call, "No other instructions may proceed intrinsic",
6897 &Call);
6898 break;
6899 }
6900 case Intrinsic::structured_gep: {
6901 // Parser should refuse those 2 cases.
6902 assert(Call.arg_size() >= 1);
6904
6905 Check(Call.paramHasAttr(0, Attribute::ElementType),
6906 "Intrinsic first parameter is missing an ElementType attribute",
6907 &Call);
6908
6909 Type *T = Call.getParamAttr(0, Attribute::ElementType).getValueAsType();
6910 for (unsigned I = 1; I < Call.arg_size(); ++I) {
6912 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
6913 Check(Index->getType()->isIntegerTy(),
6914 "Index operand type must be an integer", &Call);
6915
6916 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
6917 T = AT->getElementType();
6918 } else if (StructType *ST = dyn_cast<StructType>(T)) {
6919 Check(CI, "Indexing into a struct requires a constant int", &Call);
6920 Check(CI->getZExtValue() < ST->getNumElements(),
6921 "Indexing in a struct should be inbounds", &Call);
6922 T = ST->getElementType(CI->getZExtValue());
6923 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
6924 T = VT->getElementType();
6925 } else {
6926 CheckFailed("Reached a non-composite type with more indices to process",
6927 &Call);
6928 }
6929 }
6930 break;
6931 }
6932 case Intrinsic::amdgcn_cs_chain: {
6933 auto CallerCC = Call.getCaller()->getCallingConv();
6934 switch (CallerCC) {
6935 case CallingConv::AMDGPU_CS:
6936 case CallingConv::AMDGPU_CS_Chain:
6937 case CallingConv::AMDGPU_CS_ChainPreserve:
6938 case CallingConv::AMDGPU_ES:
6939 case CallingConv::AMDGPU_GS:
6940 case CallingConv::AMDGPU_HS:
6941 case CallingConv::AMDGPU_LS:
6942 case CallingConv::AMDGPU_VS:
6943 break;
6944 default:
6945 CheckFailed("Intrinsic cannot be called from functions with this "
6946 "calling convention",
6947 &Call);
6948 break;
6949 }
6950
6951 Check(Call.paramHasAttr(2, Attribute::InReg),
6952 "SGPR arguments must have the `inreg` attribute", &Call);
6953 Check(!Call.paramHasAttr(3, Attribute::InReg),
6954 "VGPR arguments must not have the `inreg` attribute", &Call);
6955
6956 auto *Next = Call.getNextNode();
6957 bool IsAMDUnreachable = Next && isa<IntrinsicInst>(Next) &&
6958 cast<IntrinsicInst>(Next)->getIntrinsicID() ==
6959 Intrinsic::amdgcn_unreachable;
6960 Check(Next && (isa<UnreachableInst>(Next) || IsAMDUnreachable),
6961 "llvm.amdgcn.cs.chain must be followed by unreachable", &Call);
6962 break;
6963 }
6964 case Intrinsic::amdgcn_init_exec_from_input: {
6965 const Argument *Arg = dyn_cast<Argument>(Call.getOperand(0));
6966 Check(Arg && Arg->hasInRegAttr(),
6967 "only inreg arguments to the parent function are valid as inputs to "
6968 "this intrinsic",
6969 &Call);
6970 break;
6971 }
6972 case Intrinsic::amdgcn_set_inactive_chain_arg: {
6973 auto CallerCC = Call.getCaller()->getCallingConv();
6974 switch (CallerCC) {
6975 case CallingConv::AMDGPU_CS_Chain:
6976 case CallingConv::AMDGPU_CS_ChainPreserve:
6977 break;
6978 default:
6979 CheckFailed("Intrinsic can only be used from functions with the "
6980 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
6981 "calling conventions",
6982 &Call);
6983 break;
6984 }
6985
6986 unsigned InactiveIdx = 1;
6987 Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
6988 "Value for inactive lanes must not have the `inreg` attribute",
6989 &Call);
6990 Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
6991 "Value for inactive lanes must be a function argument", &Call);
6992 Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
6993 "Value for inactive lanes must be a VGPR function argument", &Call);
6994 break;
6995 }
6996 case Intrinsic::amdgcn_call_whole_wave: {
6998 Check(F, "Indirect whole wave calls are not allowed", &Call);
6999
7000 CallingConv::ID CC = F->getCallingConv();
7001 Check(CC == CallingConv::AMDGPU_Gfx_WholeWave,
7002 "Callee must have the amdgpu_gfx_whole_wave calling convention",
7003 &Call);
7004
7005 Check(!F->isVarArg(), "Variadic whole wave calls are not allowed", &Call);
7006
7007 Check(Call.arg_size() == F->arg_size(),
7008 "Call argument count must match callee argument count", &Call);
7009
7010 // The first argument of the call is the callee, and the first argument of
7011 // the callee is the active mask. The rest of the arguments must match.
7012 Check(F->arg_begin()->getType()->isIntegerTy(1),
7013 "Callee must have i1 as its first argument", &Call);
7014 for (auto [CallArg, FuncArg] :
7015 drop_begin(zip_equal(Call.args(), F->args()))) {
7016 Check(CallArg->getType() == FuncArg.getType(),
7017 "Argument types must match", &Call);
7018
7019 // Check that inreg attributes match between call site and function
7020 Check(Call.paramHasAttr(FuncArg.getArgNo(), Attribute::InReg) ==
7021 FuncArg.hasInRegAttr(),
7022 "Argument inreg attributes must match", &Call);
7023 }
7024 break;
7025 }
7026 case Intrinsic::amdgcn_s_prefetch_data: {
7027 Check(
7030 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
7031 break;
7032 }
7033 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
7034 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
7035 Value *Src0 = Call.getArgOperand(0);
7036 Value *Src1 = Call.getArgOperand(1);
7037
7038 uint64_t CBSZ = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
7039 uint64_t BLGP = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
7040 Check(CBSZ <= 4, "invalid value for cbsz format", Call,
7041 Call.getArgOperand(3));
7042 Check(BLGP <= 4, "invalid value for blgp format", Call,
7043 Call.getArgOperand(4));
7044
7045 // AMDGPU::MFMAScaleFormats values
7046 auto getFormatNumRegs = [](unsigned FormatVal) {
7047 switch (FormatVal) {
7048 case 0:
7049 case 1:
7050 return 8u;
7051 case 2:
7052 case 3:
7053 return 6u;
7054 case 4:
7055 return 4u;
7056 default:
7057 llvm_unreachable("invalid format value");
7058 }
7059 };
7060
7061 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7062 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7063 return false;
7064 unsigned NumElts = Ty->getNumElements();
7065 return NumElts == 4 || NumElts == 6 || NumElts == 8;
7066 };
7067
7068 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7069 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7070 Check(isValidSrcASrcBVector(Src0Ty),
7071 "operand 0 must be 4, 6 or 8 element i32 vector", &Call, Src0);
7072 Check(isValidSrcASrcBVector(Src1Ty),
7073 "operand 1 must be 4, 6 or 8 element i32 vector", &Call, Src1);
7074
7075 // Permit excess registers for the format.
7076 Check(Src0Ty->getNumElements() >= getFormatNumRegs(CBSZ),
7077 "invalid vector type for format", &Call, Src0, Call.getArgOperand(3));
7078 Check(Src1Ty->getNumElements() >= getFormatNumRegs(BLGP),
7079 "invalid vector type for format", &Call, Src1, Call.getArgOperand(5));
7080 break;
7081 }
7082 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
7083 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
7084 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
7085 Value *Src0 = Call.getArgOperand(1);
7086 Value *Src1 = Call.getArgOperand(3);
7087
7088 unsigned FmtA = cast<ConstantInt>(Call.getArgOperand(0))->getZExtValue();
7089 unsigned FmtB = cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue();
7090 Check(FmtA <= 4, "invalid value for matrix format", Call,
7091 Call.getArgOperand(0));
7092 Check(FmtB <= 4, "invalid value for matrix format", Call,
7093 Call.getArgOperand(2));
7094
7095 // AMDGPU::MatrixFMT values
7096 auto getFormatNumRegs = [](unsigned FormatVal) {
7097 switch (FormatVal) {
7098 case 0:
7099 case 1:
7100 return 16u;
7101 case 2:
7102 case 3:
7103 return 12u;
7104 case 4:
7105 return 8u;
7106 default:
7107 llvm_unreachable("invalid format value");
7108 }
7109 };
7110
7111 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7112 if (!Ty || !Ty->getElementType()->isIntegerTy(32))
7113 return false;
7114 unsigned NumElts = Ty->getNumElements();
7115 return NumElts == 16 || NumElts == 12 || NumElts == 8;
7116 };
7117
7118 auto *Src0Ty = dyn_cast<FixedVectorType>(Src0->getType());
7119 auto *Src1Ty = dyn_cast<FixedVectorType>(Src1->getType());
7120 Check(isValidSrcASrcBVector(Src0Ty),
7121 "operand 1 must be 8, 12 or 16 element i32 vector", &Call, Src0);
7122 Check(isValidSrcASrcBVector(Src1Ty),
7123 "operand 3 must be 8, 12 or 16 element i32 vector", &Call, Src1);
7124
7125 // Permit excess registers for the format.
7126 Check(Src0Ty->getNumElements() >= getFormatNumRegs(FmtA),
7127 "invalid vector type for format", &Call, Src0, Call.getArgOperand(0));
7128 Check(Src1Ty->getNumElements() >= getFormatNumRegs(FmtB),
7129 "invalid vector type for format", &Call, Src1, Call.getArgOperand(2));
7130 break;
7131 }
7132 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
7133 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
7134 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
7135 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
7136 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
7137 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
7138 // Check we only use this intrinsic on the FLAT or GLOBAL address spaces.
7139 Value *PtrArg = Call.getArgOperand(0);
7140 const unsigned AS = PtrArg->getType()->getPointerAddressSpace();
7142 "cooperative atomic intrinsics require a generic or global pointer",
7143 &Call, PtrArg);
7144
7145 // Last argument must be a MD string
7147 MDNode *MD = cast<MDNode>(Op->getMetadata());
7148 Check((MD->getNumOperands() == 1) && isa<MDString>(MD->getOperand(0)),
7149 "cooperative atomic intrinsics require that the last argument is a "
7150 "metadata string",
7151 &Call, Op);
7152 break;
7153 }
7154 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7155 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7156 Value *V = Call.getArgOperand(0);
7157 unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
7158 Check(RegCount % 8 == 0,
7159 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7160 break;
7161 }
7162 case Intrinsic::experimental_convergence_entry:
7163 case Intrinsic::experimental_convergence_anchor:
7164 break;
7165 case Intrinsic::experimental_convergence_loop:
7166 break;
7167 case Intrinsic::ptrmask: {
7168 Type *Ty0 = Call.getArgOperand(0)->getType();
7169 Type *Ty1 = Call.getArgOperand(1)->getType();
7171 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7172 "of pointers",
7173 &Call);
7174 Check(
7175 Ty0->isVectorTy() == Ty1->isVectorTy(),
7176 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7177 &Call);
7178 if (Ty0->isVectorTy())
7179 Check(cast<VectorType>(Ty0)->getElementCount() ==
7180 cast<VectorType>(Ty1)->getElementCount(),
7181 "llvm.ptrmask intrinsic arguments must have the same number of "
7182 "elements",
7183 &Call);
7184 Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
7185 "llvm.ptrmask intrinsic second argument bitwidth must match "
7186 "pointer index type size of first argument",
7187 &Call);
7188 break;
7189 }
7190 case Intrinsic::thread_pointer: {
7192 DL.getDefaultGlobalsAddressSpace(),
7193 "llvm.thread.pointer intrinsic return type must be for the globals "
7194 "address space",
7195 &Call);
7196 break;
7197 }
7198 case Intrinsic::threadlocal_address: {
7199 const Value &Arg0 = *Call.getArgOperand(0);
7200 Check(isa<GlobalValue>(Arg0),
7201 "llvm.threadlocal.address first argument must be a GlobalValue");
7202 Check(cast<GlobalValue>(Arg0).isThreadLocal(),
7203 "llvm.threadlocal.address operand isThreadLocal() must be true");
7204 break;
7205 }
7206 case Intrinsic::lifetime_start:
7207 case Intrinsic::lifetime_end: {
7208 Value *Ptr = Call.getArgOperand(0);
7210 "llvm.lifetime.start/end can only be used on alloca or poison",
7211 &Call);
7212 break;
7213 }
7214 case Intrinsic::sponentry: {
7215 const unsigned StackAS = DL.getAllocaAddrSpace();
7216 const Type *RetTy = Call.getFunctionType()->getReturnType();
7217 Check(RetTy->getPointerAddressSpace() == StackAS,
7218 "llvm.sponentry must return a pointer to the stack", &Call);
7219 break;
7220 }
7221 };
7222
7223 // Verify that there aren't any unmediated control transfers between funclets.
7225 Function *F = Call.getParent()->getParent();
7226 if (F->hasPersonalityFn() &&
7227 isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
7228 // Run EH funclet coloring on-demand and cache results for other intrinsic
7229 // calls in this function
7230 if (BlockEHFuncletColors.empty())
7231 BlockEHFuncletColors = colorEHFunclets(*F);
7232
7233 // Check for catch-/cleanup-pad in first funclet block
7234 bool InEHFunclet = false;
7235 BasicBlock *CallBB = Call.getParent();
7236 const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
7237 assert(CV.size() > 0 && "Uncolored block");
7238 for (BasicBlock *ColorFirstBB : CV)
7239 if (auto It = ColorFirstBB->getFirstNonPHIIt();
7240 It != ColorFirstBB->end())
7242 InEHFunclet = true;
7243
7244 // Check for funclet operand bundle
7245 bool HasToken = false;
7246 for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
7248 HasToken = true;
7249
7250 // This would cause silent code truncation in WinEHPrepare
7251 if (InEHFunclet)
7252 Check(HasToken, "Missing funclet token on intrinsic call", &Call);
7253 }
7254 }
7255}
7256
7257/// Carefully grab the subprogram from a local scope.
7258///
7259/// This carefully grabs the subprogram from a local scope, avoiding the
7260/// built-in assertions that would typically fire.
7262 if (!LocalScope)
7263 return nullptr;
7264
7265 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
7266 return SP;
7267
7268 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
7269 return getSubprogram(LB->getRawScope());
7270
7271 // Just return null; broken scope chains are checked elsewhere.
7272 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
7273 return nullptr;
7274}
7275
7276void Verifier::visit(DbgLabelRecord &DLR) {
7278 "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
7279
7280 // Ignore broken !dbg attachments; they're checked elsewhere.
7281 if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
7282 if (!isa<DILocation>(N))
7283 return;
7284
7285 BasicBlock *BB = DLR.getParent();
7286 Function *F = BB ? BB->getParent() : nullptr;
7287
7288 // The scopes for variables and !dbg attachments must agree.
7289 DILabel *Label = DLR.getLabel();
7290 DILocation *Loc = DLR.getDebugLoc();
7291 CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
7292
7293 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
7294 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7295 if (!LabelSP || !LocSP)
7296 return;
7297
7298 CheckDI(LabelSP == LocSP,
7299 "mismatched subprogram between #dbg_label label and !dbg attachment",
7300 &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
7301 Loc->getScope()->getSubprogram());
7302}
7303
7304void Verifier::visit(DbgVariableRecord &DVR) {
7305 BasicBlock *BB = DVR.getParent();
7306 Function *F = BB->getParent();
7307
7308 CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
7309 DVR.getType() == DbgVariableRecord::LocationType::Declare ||
7310 DVR.getType() == DbgVariableRecord::LocationType::DeclareValue ||
7311 DVR.getType() == DbgVariableRecord::LocationType::Assign,
7312 "invalid #dbg record type", &DVR, DVR.getType(), BB, F);
7313
7314 // The location for a DbgVariableRecord must be either a ValueAsMetadata,
7315 // DIArgList, or an empty MDNode (which is a legacy representation for an
7316 // "undef" location).
7317 auto *MD = DVR.getRawLocation();
7318 CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
7319 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
7320 "invalid #dbg record address/value", &DVR, MD, BB, F);
7321 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
7322 visitValueAsMetadata(*VAM, F);
7323 if (DVR.isDbgDeclare()) {
7324 // Allow integers here to support inttoptr salvage.
7325 Type *Ty = VAM->getValue()->getType();
7326 CheckDI(Ty->isPointerTy() || Ty->isIntegerTy(),
7327 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7328 F);
7329 }
7330 } else if (auto *AL = dyn_cast<DIArgList>(MD)) {
7331 visitDIArgList(*AL, F);
7332 }
7333
7335 "invalid #dbg record variable", &DVR, DVR.getRawVariable(), BB, F);
7336 visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
7337
7339 "invalid #dbg record expression", &DVR, DVR.getRawExpression(), BB,
7340 F);
7341 visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
7342
7343 if (DVR.isDbgAssign()) {
7345 "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID(), BB,
7346 F);
7347 visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
7348 AreDebugLocsAllowed::No);
7349
7350 const auto *RawAddr = DVR.getRawAddress();
7351 // Similarly to the location above, the address for an assign
7352 // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
7353 // represents an undef address.
7354 CheckDI(
7355 isa<ValueAsMetadata>(RawAddr) ||
7356 (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
7357 "invalid #dbg_assign address", &DVR, DVR.getRawAddress(), BB, F);
7358 if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
7359 visitValueAsMetadata(*VAM, F);
7360
7362 "invalid #dbg_assign address expression", &DVR,
7363 DVR.getRawAddressExpression(), BB, F);
7364 visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
7365
7366 // All of the linked instructions should be in the same function as DVR.
7367 for (Instruction *I : at::getAssignmentInsts(&DVR))
7368 CheckDI(DVR.getFunction() == I->getFunction(),
7369 "inst not in same function as #dbg_assign", I, &DVR, BB, F);
7370 }
7371
7372 // This check is redundant with one in visitLocalVariable().
7373 DILocalVariable *Var = DVR.getVariable();
7374 CheckDI(isType(Var->getRawType()), "invalid type ref", Var, Var->getRawType(),
7375 BB, F);
7376
7377 auto *DLNode = DVR.getDebugLoc().getAsMDNode();
7378 CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
7379 &DVR, DLNode, BB, F);
7380 DILocation *Loc = DVR.getDebugLoc();
7381
7382 // The scopes for variables and !dbg attachments must agree.
7383 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
7384 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7385 if (!VarSP || !LocSP)
7386 return; // Broken scope chains are checked elsewhere.
7387
7388 CheckDI(VarSP == LocSP,
7389 "mismatched subprogram between #dbg record variable and DILocation",
7390 &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
7391 Loc->getScope()->getSubprogram(), BB, F);
7392
7393 verifyFnArgs(DVR);
7394}
7395
7396void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7397 if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
7398 auto *RetTy = cast<VectorType>(VPCast->getType());
7399 auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
7400 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7401 "VP cast intrinsic first argument and result vector lengths must be "
7402 "equal",
7403 *VPCast);
7404
7405 switch (VPCast->getIntrinsicID()) {
7406 default:
7407 llvm_unreachable("Unknown VP cast intrinsic");
7408 case Intrinsic::vp_trunc:
7409 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7410 "llvm.vp.trunc intrinsic first argument and result element type "
7411 "must be integer",
7412 *VPCast);
7413 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7414 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7415 "larger than the bit size of the return type",
7416 *VPCast);
7417 break;
7418 case Intrinsic::vp_zext:
7419 case Intrinsic::vp_sext:
7420 Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
7421 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
7422 "element type must be integer",
7423 *VPCast);
7424 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7425 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7426 "argument must be smaller than the bit size of the return type",
7427 *VPCast);
7428 break;
7429 case Intrinsic::vp_fptoui:
7430 case Intrinsic::vp_fptosi:
7431 case Intrinsic::vp_lrint:
7432 case Intrinsic::vp_llrint:
7433 Check(
7434 RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
7435 "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
7436 "type must be floating-point and result element type must be integer",
7437 *VPCast);
7438 break;
7439 case Intrinsic::vp_uitofp:
7440 case Intrinsic::vp_sitofp:
7441 Check(
7442 RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
7443 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
7444 "type must be integer and result element type must be floating-point",
7445 *VPCast);
7446 break;
7447 case Intrinsic::vp_fptrunc:
7448 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7449 "llvm.vp.fptrunc intrinsic first argument and result element type "
7450 "must be floating-point",
7451 *VPCast);
7452 Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
7453 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7454 "larger than the bit size of the return type",
7455 *VPCast);
7456 break;
7457 case Intrinsic::vp_fpext:
7458 Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
7459 "llvm.vp.fpext intrinsic first argument and result element type "
7460 "must be floating-point",
7461 *VPCast);
7462 Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
7463 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7464 "smaller than the bit size of the return type",
7465 *VPCast);
7466 break;
7467 case Intrinsic::vp_ptrtoint:
7468 Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
7469 "llvm.vp.ptrtoint intrinsic first argument element type must be "
7470 "pointer and result element type must be integer",
7471 *VPCast);
7472 break;
7473 case Intrinsic::vp_inttoptr:
7474 Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
7475 "llvm.vp.inttoptr intrinsic first argument element type must be "
7476 "integer and result element type must be pointer",
7477 *VPCast);
7478 break;
7479 }
7480 }
7481
7482 switch (VPI.getIntrinsicID()) {
7483 case Intrinsic::vp_fcmp: {
7484 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7486 "invalid predicate for VP FP comparison intrinsic", &VPI);
7487 break;
7488 }
7489 case Intrinsic::vp_icmp: {
7490 auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
7492 "invalid predicate for VP integer comparison intrinsic", &VPI);
7493 break;
7494 }
7495 case Intrinsic::vp_is_fpclass: {
7496 auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
7497 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
7498 "unsupported bits for llvm.vp.is.fpclass test mask");
7499 break;
7500 }
7501 case Intrinsic::experimental_vp_splice: {
7502 VectorType *VecTy = cast<VectorType>(VPI.getType());
7503 int64_t Idx = cast<ConstantInt>(VPI.getArgOperand(2))->getSExtValue();
7504 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7505 if (VPI.getParent() && VPI.getParent()->getParent()) {
7506 AttributeList Attrs = VPI.getParent()->getParent()->getAttributes();
7507 if (Attrs.hasFnAttr(Attribute::VScaleRange))
7508 KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
7509 }
7510 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7511 (Idx >= 0 && Idx < KnownMinNumElements),
7512 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7513 "known minimum number of elements in the vector. For scalable "
7514 "vectors the minimum number of elements is determined from "
7515 "vscale_range.",
7516 &VPI);
7517 break;
7518 }
7519 }
7520}
7521
7522void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7523 unsigned NumOperands = FPI.getNonMetadataArgCount();
7524 bool HasRoundingMD =
7526
7527 // Add the expected number of metadata operands.
7528 NumOperands += (1 + HasRoundingMD);
7529
7530 // Compare intrinsics carry an extra predicate metadata operand.
7532 NumOperands += 1;
7533 Check((FPI.arg_size() == NumOperands),
7534 "invalid arguments for constrained FP intrinsic", &FPI);
7535
7536 switch (FPI.getIntrinsicID()) {
7537 case Intrinsic::experimental_constrained_lrint:
7538 case Intrinsic::experimental_constrained_llrint: {
7539 Type *ValTy = FPI.getArgOperand(0)->getType();
7540 Type *ResultTy = FPI.getType();
7541 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7542 "Intrinsic does not support vectors", &FPI);
7543 break;
7544 }
7545
7546 case Intrinsic::experimental_constrained_lround:
7547 case Intrinsic::experimental_constrained_llround: {
7548 Type *ValTy = FPI.getArgOperand(0)->getType();
7549 Type *ResultTy = FPI.getType();
7550 Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
7551 "Intrinsic does not support vectors", &FPI);
7552 break;
7553 }
7554
7555 case Intrinsic::experimental_constrained_fcmp:
7556 case Intrinsic::experimental_constrained_fcmps: {
7557 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
7559 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7560 break;
7561 }
7562
7563 case Intrinsic::experimental_constrained_fptosi:
7564 case Intrinsic::experimental_constrained_fptoui: {
7565 Value *Operand = FPI.getArgOperand(0);
7566 ElementCount SrcEC;
7567 Check(Operand->getType()->isFPOrFPVectorTy(),
7568 "Intrinsic first argument must be floating point", &FPI);
7569 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7570 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7571 }
7572
7573 Operand = &FPI;
7574 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7575 "Intrinsic first argument and result disagree on vector use", &FPI);
7576 Check(Operand->getType()->isIntOrIntVectorTy(),
7577 "Intrinsic result must be an integer", &FPI);
7578 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7579 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7580 "Intrinsic first argument and result vector lengths must be equal",
7581 &FPI);
7582 }
7583 break;
7584 }
7585
7586 case Intrinsic::experimental_constrained_sitofp:
7587 case Intrinsic::experimental_constrained_uitofp: {
7588 Value *Operand = FPI.getArgOperand(0);
7589 ElementCount SrcEC;
7590 Check(Operand->getType()->isIntOrIntVectorTy(),
7591 "Intrinsic first argument must be integer", &FPI);
7592 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7593 SrcEC = cast<VectorType>(OperandT)->getElementCount();
7594 }
7595
7596 Operand = &FPI;
7597 Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
7598 "Intrinsic first argument and result disagree on vector use", &FPI);
7599 Check(Operand->getType()->isFPOrFPVectorTy(),
7600 "Intrinsic result must be a floating point", &FPI);
7601 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
7602 Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
7603 "Intrinsic first argument and result vector lengths must be equal",
7604 &FPI);
7605 }
7606 break;
7607 }
7608
7609 case Intrinsic::experimental_constrained_fptrunc:
7610 case Intrinsic::experimental_constrained_fpext: {
7611 Value *Operand = FPI.getArgOperand(0);
7612 Type *OperandTy = Operand->getType();
7613 Value *Result = &FPI;
7614 Type *ResultTy = Result->getType();
7615 Check(OperandTy->isFPOrFPVectorTy(),
7616 "Intrinsic first argument must be FP or FP vector", &FPI);
7617 Check(ResultTy->isFPOrFPVectorTy(),
7618 "Intrinsic result must be FP or FP vector", &FPI);
7619 Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
7620 "Intrinsic first argument and result disagree on vector use", &FPI);
7621 if (OperandTy->isVectorTy()) {
7622 Check(cast<VectorType>(OperandTy)->getElementCount() ==
7623 cast<VectorType>(ResultTy)->getElementCount(),
7624 "Intrinsic first argument and result vector lengths must be equal",
7625 &FPI);
7626 }
7627 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7628 Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
7629 "Intrinsic first argument's type must be larger than result type",
7630 &FPI);
7631 } else {
7632 Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
7633 "Intrinsic first argument's type must be smaller than result type",
7634 &FPI);
7635 }
7636 break;
7637 }
7638
7639 default:
7640 break;
7641 }
7642
7643 // If a non-metadata argument is passed in a metadata slot then the
7644 // error will be caught earlier when the incorrect argument doesn't
7645 // match the specification in the intrinsic call table. Thus, no
7646 // argument type check is needed here.
7647
7648 Check(FPI.getExceptionBehavior().has_value(),
7649 "invalid exception behavior argument", &FPI);
7650 if (HasRoundingMD) {
7651 Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
7652 &FPI);
7653 }
7654}
7655
7656void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
7657 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
7658 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7659
7660 // We don't know whether this intrinsic verified correctly.
7661 if (!V || !E || !E->isValid())
7662 return;
7663
7664 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
7665 auto Fragment = E->getFragmentInfo();
7666 if (!Fragment)
7667 return;
7668
7669 // The frontend helps out GDB by emitting the members of local anonymous
7670 // unions as artificial local variables with shared storage. When SROA splits
7671 // the storage for artificial local variables that are smaller than the entire
7672 // union, the overhang piece will be outside of the allotted space for the
7673 // variable and this check fails.
7674 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
7675 if (V->isArtificial())
7676 return;
7677
7678 verifyFragmentExpression(*V, *Fragment, &DVR);
7679}
7680
7681template <typename ValueOrMetadata>
7682void Verifier::verifyFragmentExpression(const DIVariable &V,
7684 ValueOrMetadata *Desc) {
7685 // If there's no size, the type is broken, but that should be checked
7686 // elsewhere.
7687 auto VarSize = V.getSizeInBits();
7688 if (!VarSize)
7689 return;
7690
7691 unsigned FragSize = Fragment.SizeInBits;
7692 unsigned FragOffset = Fragment.OffsetInBits;
7693 CheckDI(FragSize + FragOffset <= *VarSize,
7694 "fragment is larger than or outside of variable", Desc, &V);
7695 CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
7696}
7697
7698void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
7699 // This function does not take the scope of noninlined function arguments into
7700 // account. Don't run it if current function is nodebug, because it may
7701 // contain inlined debug intrinsics.
7702 if (!HasDebugInfo)
7703 return;
7704
7705 // For performance reasons only check non-inlined ones.
7706 if (DVR.getDebugLoc()->getInlinedAt())
7707 return;
7708
7709 DILocalVariable *Var = DVR.getVariable();
7710 CheckDI(Var, "#dbg record without variable");
7711
7712 unsigned ArgNo = Var->getArg();
7713 if (!ArgNo)
7714 return;
7715
7716 // Verify there are no duplicate function argument debug info entries.
7717 // These will cause hard-to-debug assertions in the DWARF backend.
7718 if (DebugFnArgs.size() < ArgNo)
7719 DebugFnArgs.resize(ArgNo, nullptr);
7720
7721 auto *Prev = DebugFnArgs[ArgNo - 1];
7722 DebugFnArgs[ArgNo - 1] = Var;
7723 CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
7724 Prev, Var);
7725}
7726
7727void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
7728 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7729
7730 // We don't know whether this intrinsic verified correctly.
7731 if (!E || !E->isValid())
7732 return;
7733
7735 Value *VarValue = DVR.getVariableLocationOp(0);
7736 if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
7737 return;
7738 // We allow EntryValues for swift async arguments, as they have an
7739 // ABI-guarantee to be turned into a specific register.
7740 if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
7741 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7742 return;
7743 }
7744
7745 CheckDI(!E->isEntryValue(),
7746 "Entry values are only allowed in MIR unless they target a "
7747 "swiftasync Argument",
7748 &DVR);
7749}
7750
7751void Verifier::verifyCompileUnits() {
7752 // When more than one Module is imported into the same context, such as during
7753 // an LTO build before linking the modules, ODR type uniquing may cause types
7754 // to point to a different CU. This check does not make sense in this case.
7755 if (M.getContext().isODRUniquingDebugTypes())
7756 return;
7757 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
7758 SmallPtrSet<const Metadata *, 2> Listed;
7759 if (CUs)
7760 Listed.insert_range(CUs->operands());
7761 for (const auto *CU : CUVisited)
7762 CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
7763 CUVisited.clear();
7764}
7765
7766void Verifier::verifyDeoptimizeCallingConvs() {
7767 if (DeoptimizeDeclarations.empty())
7768 return;
7769
7770 const Function *First = DeoptimizeDeclarations[0];
7771 for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
7772 Check(First->getCallingConv() == F->getCallingConv(),
7773 "All llvm.experimental.deoptimize declarations must have the same "
7774 "calling convention",
7775 First, F);
7776 }
7777}
7778
7779void Verifier::verifyAttachedCallBundle(const CallBase &Call,
7780 const OperandBundleUse &BU) {
7781 FunctionType *FTy = Call.getFunctionType();
7782
7783 Check((FTy->getReturnType()->isPointerTy() ||
7784 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
7785 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7786 "function returning a pointer or a non-returning function that has a "
7787 "void return type",
7788 Call);
7789
7790 Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
7791 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7792 "an argument",
7793 Call);
7794
7795 auto *Fn = cast<Function>(BU.Inputs.front());
7796 Intrinsic::ID IID = Fn->getIntrinsicID();
7797
7798 if (IID) {
7799 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7800 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7801 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7802 "invalid function argument", Call);
7803 } else {
7804 StringRef FnName = Fn->getName();
7805 Check((FnName == "objc_retainAutoreleasedReturnValue" ||
7806 FnName == "objc_claimAutoreleasedReturnValue" ||
7807 FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
7808 "invalid function argument", Call);
7809 }
7810}
7811
7812void Verifier::verifyNoAliasScopeDecl() {
7813 if (NoAliasScopeDecls.empty())
7814 return;
7815
7816 // only a single scope must be declared at a time.
7817 for (auto *II : NoAliasScopeDecls) {
7818 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7819 "Not a llvm.experimental.noalias.scope.decl ?");
7820 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
7822 Check(ScopeListMV != nullptr,
7823 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7824 "argument",
7825 II);
7826
7827 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
7828 Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
7829 Check(ScopeListMD->getNumOperands() == 1,
7830 "!id.scope.list must point to a list with a single scope", II);
7831 visitAliasScopeListMetadata(ScopeListMD);
7832 }
7833
7834 // Only check the domination rule when requested. Once all passes have been
7835 // adapted this option can go away.
7837 return;
7838
7839 // Now sort the intrinsics based on the scope MDNode so that declarations of
7840 // the same scopes are next to each other.
7841 auto GetScope = [](IntrinsicInst *II) {
7842 const auto *ScopeListMV = cast<MetadataAsValue>(
7844 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7845 };
7846
7847 // We are sorting on MDNode pointers here. For valid input IR this is ok.
7848 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
7849 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7850 return GetScope(Lhs) < GetScope(Rhs);
7851 };
7852
7853 llvm::sort(NoAliasScopeDecls, Compare);
7854
7855 // Go over the intrinsics and check that for the same scope, they are not
7856 // dominating each other.
7857 auto ItCurrent = NoAliasScopeDecls.begin();
7858 while (ItCurrent != NoAliasScopeDecls.end()) {
7859 auto CurScope = GetScope(*ItCurrent);
7860 auto ItNext = ItCurrent;
7861 do {
7862 ++ItNext;
7863 } while (ItNext != NoAliasScopeDecls.end() &&
7864 GetScope(*ItNext) == CurScope);
7865
7866 // [ItCurrent, ItNext) represents the declarations for the same scope.
7867 // Ensure they are not dominating each other.. but only if it is not too
7868 // expensive.
7869 if (ItNext - ItCurrent < 32)
7870 for (auto *I : llvm::make_range(ItCurrent, ItNext))
7871 for (auto *J : llvm::make_range(ItCurrent, ItNext))
7872 if (I != J)
7873 Check(!DT.dominates(I, J),
7874 "llvm.experimental.noalias.scope.decl dominates another one "
7875 "with the same scope",
7876 I);
7877 ItCurrent = ItNext;
7878 }
7879}
7880
7881//===----------------------------------------------------------------------===//
7882// Implement the public interfaces to this file...
7883//===----------------------------------------------------------------------===//
7884
7886 Function &F = const_cast<Function &>(f);
7887
7888 // Don't use a raw_null_ostream. Printing IR is expensive.
7889 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
7890
7891 // Note that this function's return value is inverted from what you would
7892 // expect of a function called "verify".
7893 return !V.verify(F);
7894}
7895
7897 bool *BrokenDebugInfo) {
7898 // Don't use a raw_null_ostream. Printing IR is expensive.
7899 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
7900
7901 bool Broken = false;
7902 for (const Function &F : M)
7903 Broken |= !V.verify(F);
7904
7905 Broken |= !V.verify();
7906 if (BrokenDebugInfo)
7907 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7908 // Note that this function's return value is inverted from what you would
7909 // expect of a function called "verify".
7910 return Broken;
7911}
7912
7913namespace {
7914
7915struct VerifierLegacyPass : public FunctionPass {
7916 static char ID;
7917
7918 std::unique_ptr<Verifier> V;
7919 bool FatalErrors = true;
7920
7921 VerifierLegacyPass() : FunctionPass(ID) {}
7922 explicit VerifierLegacyPass(bool FatalErrors)
7923 : FunctionPass(ID), FatalErrors(FatalErrors) {}
7924
7925 bool doInitialization(Module &M) override {
7926 V = std::make_unique<Verifier>(
7927 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
7928 return false;
7929 }
7930
7931 bool runOnFunction(Function &F) override {
7932 if (!V->verify(F) && FatalErrors) {
7933 errs() << "in function " << F.getName() << '\n';
7934 report_fatal_error("Broken function found, compilation aborted!");
7935 }
7936 return false;
7937 }
7938
7939 bool doFinalization(Module &M) override {
7940 bool HasErrors = false;
7941 for (Function &F : M)
7942 if (F.isDeclaration())
7943 HasErrors |= !V->verify(F);
7944
7945 HasErrors |= !V->verify();
7946 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
7947 report_fatal_error("Broken module found, compilation aborted!");
7948 return false;
7949 }
7950
7951 void getAnalysisUsage(AnalysisUsage &AU) const override {
7952 AU.setPreservesAll();
7953 }
7954};
7955
7956} // end anonymous namespace
7957
7958/// Helper to issue failure from the TBAA verification
7959template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
7960 if (Diagnostic)
7961 return Diagnostic->CheckFailed(Args...);
7962}
7963
7964#define CheckTBAA(C, ...) \
7965 do { \
7966 if (!(C)) { \
7967 CheckFailed(__VA_ARGS__); \
7968 return false; \
7969 } \
7970 } while (false)
7971
7972/// Verify that \p BaseNode can be used as the "base type" in the struct-path
7973/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
7974/// struct-type node describing an aggregate data structure (like a struct).
7975TBAAVerifier::TBAABaseNodeSummary
7976TBAAVerifier::verifyTBAABaseNode(const Instruction *I, const MDNode *BaseNode,
7977 bool IsNewFormat) {
7978 if (BaseNode->getNumOperands() < 2) {
7979 CheckFailed("Base nodes must have at least two operands", I, BaseNode);
7980 return {true, ~0u};
7981 }
7982
7983 auto Itr = TBAABaseNodes.find(BaseNode);
7984 if (Itr != TBAABaseNodes.end())
7985 return Itr->second;
7986
7987 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
7988 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7989 (void)InsertResult;
7990 assert(InsertResult.second && "We just checked!");
7991 return Result;
7992}
7993
7994TBAAVerifier::TBAABaseNodeSummary
7995TBAAVerifier::verifyTBAABaseNodeImpl(const Instruction *I,
7996 const MDNode *BaseNode, bool IsNewFormat) {
7997 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
7998
7999 if (BaseNode->getNumOperands() == 2) {
8000 // Scalar nodes can only be accessed at offset 0.
8001 return isValidScalarTBAANode(BaseNode)
8002 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
8003 : InvalidNode;
8004 }
8005
8006 if (IsNewFormat) {
8007 if (BaseNode->getNumOperands() % 3 != 0) {
8008 CheckFailed("Access tag nodes must have the number of operands that is a "
8009 "multiple of 3!", BaseNode);
8010 return InvalidNode;
8011 }
8012 } else {
8013 if (BaseNode->getNumOperands() % 2 != 1) {
8014 CheckFailed("Struct tag nodes must have an odd number of operands!",
8015 BaseNode);
8016 return InvalidNode;
8017 }
8018 }
8019
8020 // Check the type size field.
8021 if (IsNewFormat) {
8022 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8023 BaseNode->getOperand(1));
8024 if (!TypeSizeNode) {
8025 CheckFailed("Type size nodes must be constants!", I, BaseNode);
8026 return InvalidNode;
8027 }
8028 }
8029
8030 // Check the type name field. In the new format it can be anything.
8031 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
8032 CheckFailed("Struct tag nodes have a string as their first operand",
8033 BaseNode);
8034 return InvalidNode;
8035 }
8036
8037 bool Failed = false;
8038
8039 std::optional<APInt> PrevOffset;
8040 unsigned BitWidth = ~0u;
8041
8042 // We've already checked that BaseNode is not a degenerate root node with one
8043 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
8044 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8045 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8046 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8047 Idx += NumOpsPerField) {
8048 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
8049 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
8050 if (!isa<MDNode>(FieldTy)) {
8051 CheckFailed("Incorrect field entry in struct type node!", I, BaseNode);
8052 Failed = true;
8053 continue;
8054 }
8055
8056 auto *OffsetEntryCI =
8058 if (!OffsetEntryCI) {
8059 CheckFailed("Offset entries must be constants!", I, BaseNode);
8060 Failed = true;
8061 continue;
8062 }
8063
8064 if (BitWidth == ~0u)
8065 BitWidth = OffsetEntryCI->getBitWidth();
8066
8067 if (OffsetEntryCI->getBitWidth() != BitWidth) {
8068 CheckFailed(
8069 "Bitwidth between the offsets and struct type entries must match", I,
8070 BaseNode);
8071 Failed = true;
8072 continue;
8073 }
8074
8075 // NB! As far as I can tell, we generate a non-strictly increasing offset
8076 // sequence only from structs that have zero size bit fields. When
8077 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
8078 // pick the field lexically the latest in struct type metadata node. This
8079 // mirrors the actual behavior of the alias analysis implementation.
8080 bool IsAscending =
8081 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8082
8083 if (!IsAscending) {
8084 CheckFailed("Offsets must be increasing!", I, BaseNode);
8085 Failed = true;
8086 }
8087
8088 PrevOffset = OffsetEntryCI->getValue();
8089
8090 if (IsNewFormat) {
8091 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8092 BaseNode->getOperand(Idx + 2));
8093 if (!MemberSizeNode) {
8094 CheckFailed("Member size entries must be constants!", I, BaseNode);
8095 Failed = true;
8096 continue;
8097 }
8098 }
8099 }
8100
8101 return Failed ? InvalidNode
8102 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
8103}
8104
8105static bool IsRootTBAANode(const MDNode *MD) {
8106 return MD->getNumOperands() < 2;
8107}
8108
8109static bool IsScalarTBAANodeImpl(const MDNode *MD,
8111 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
8112 return false;
8113
8114 if (!isa<MDString>(MD->getOperand(0)))
8115 return false;
8116
8117 if (MD->getNumOperands() == 3) {
8119 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
8120 return false;
8121 }
8122
8123 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8124 return Parent && Visited.insert(Parent).second &&
8125 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
8126}
8127
8128bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
8129 auto ResultIt = TBAAScalarNodes.find(MD);
8130 if (ResultIt != TBAAScalarNodes.end())
8131 return ResultIt->second;
8132
8133 SmallPtrSet<const MDNode *, 4> Visited;
8134 bool Result = IsScalarTBAANodeImpl(MD, Visited);
8135 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
8136 (void)InsertResult;
8137 assert(InsertResult.second && "Just checked!");
8138
8139 return Result;
8140}
8141
8142/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
8143/// Offset in place to be the offset within the field node returned.
8144///
8145/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
8146MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(const Instruction *I,
8147 const MDNode *BaseNode,
8148 APInt &Offset,
8149 bool IsNewFormat) {
8150 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
8151
8152 // Scalar nodes have only one possible "field" -- their parent in the access
8153 // hierarchy. Offset must be zero at this point, but our caller is supposed
8154 // to check that.
8155 if (BaseNode->getNumOperands() == 2)
8156 return cast<MDNode>(BaseNode->getOperand(1));
8157
8158 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8159 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8160 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8161 Idx += NumOpsPerField) {
8162 auto *OffsetEntryCI =
8163 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
8164 if (OffsetEntryCI->getValue().ugt(Offset)) {
8165 if (Idx == FirstFieldOpNo) {
8166 CheckFailed("Could not find TBAA parent in struct type node", I,
8167 BaseNode, &Offset);
8168 return nullptr;
8169 }
8170
8171 unsigned PrevIdx = Idx - NumOpsPerField;
8172 auto *PrevOffsetEntryCI =
8173 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
8174 Offset -= PrevOffsetEntryCI->getValue();
8175 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
8176 }
8177 }
8178
8179 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
8180 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
8181 BaseNode->getOperand(LastIdx + 1));
8182 Offset -= LastOffsetEntryCI->getValue();
8183 return cast<MDNode>(BaseNode->getOperand(LastIdx));
8184}
8185
8187 if (!Type || Type->getNumOperands() < 3)
8188 return false;
8189
8190 // In the new format type nodes shall have a reference to the parent type as
8191 // its first operand.
8192 return isa_and_nonnull<MDNode>(Type->getOperand(0));
8193}
8194
8196 CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands", I,
8197 MD);
8198
8199 if (I)
8203 "This instruction shall not have a TBAA access tag!", I);
8204
8205 bool IsStructPathTBAA =
8206 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
8207
8208 CheckTBAA(IsStructPathTBAA,
8209 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8210 I);
8211
8212 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
8213 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8214
8215 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
8216
8217 if (IsNewFormat) {
8218 CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
8219 "Access tag metadata must have either 4 or 5 operands", I, MD);
8220 } else {
8221 CheckTBAA(MD->getNumOperands() < 5,
8222 "Struct tag metadata must have either 3 or 4 operands", I, MD);
8223 }
8224
8225 // Check the access size field.
8226 if (IsNewFormat) {
8227 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8228 MD->getOperand(3));
8229 CheckTBAA(AccessSizeNode, "Access size field must be a constant", I, MD);
8230 }
8231
8232 // Check the immutability flag.
8233 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8234 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
8235 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
8236 MD->getOperand(ImmutabilityFlagOpNo));
8237 CheckTBAA(IsImmutableCI,
8238 "Immutability tag on struct tag metadata must be a constant", I,
8239 MD);
8240 CheckTBAA(
8241 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8242 "Immutability part of the struct tag metadata must be either 0 or 1", I,
8243 MD);
8244 }
8245
8246 CheckTBAA(BaseNode && AccessType,
8247 "Malformed struct tag metadata: base and access-type "
8248 "should be non-null and point to Metadata nodes",
8249 I, MD, BaseNode, AccessType);
8250
8251 if (!IsNewFormat) {
8252 CheckTBAA(isValidScalarTBAANode(AccessType),
8253 "Access type node must be a valid scalar type", I, MD,
8254 AccessType);
8255 }
8256
8258 CheckTBAA(OffsetCI, "Offset must be constant integer", I, MD);
8259
8260 APInt Offset = OffsetCI->getValue();
8261 bool SeenAccessTypeInPath = false;
8262
8263 SmallPtrSet<MDNode *, 4> StructPath;
8264
8265 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
8266 BaseNode =
8267 getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, IsNewFormat)) {
8268 if (!StructPath.insert(BaseNode).second) {
8269 CheckFailed("Cycle detected in struct path", I, MD);
8270 return false;
8271 }
8272
8273 bool Invalid;
8274 unsigned BaseNodeBitWidth;
8275 std::tie(Invalid, BaseNodeBitWidth) =
8276 verifyTBAABaseNode(I, BaseNode, IsNewFormat);
8277
8278 // If the base node is invalid in itself, then we've already printed all the
8279 // errors we wanted to print.
8280 if (Invalid)
8281 return false;
8282
8283 SeenAccessTypeInPath |= BaseNode == AccessType;
8284
8285 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8286 CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access", I,
8287 MD, &Offset);
8288
8289 CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
8290 (BaseNodeBitWidth == 0 && Offset == 0) ||
8291 (IsNewFormat && BaseNodeBitWidth == ~0u),
8292 "Access bit-width not the same as description bit-width", I, MD,
8293 BaseNodeBitWidth, Offset.getBitWidth());
8294
8295 if (IsNewFormat && SeenAccessTypeInPath)
8296 break;
8297 }
8298
8299 CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", I,
8300 MD);
8301 return true;
8302}
8303
8304char VerifierLegacyPass::ID = 0;
8305INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
8306
8308 return new VerifierLegacyPass(FatalErrors);
8309}
8310
8311AnalysisKey VerifierAnalysis::Key;
8318
8323
8325 auto Res = AM.getResult<VerifierAnalysis>(M);
8326 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8327 report_fatal_error("Broken module found, compilation aborted!");
8328
8329 return PreservedAnalyses::all();
8330}
8331
8333 auto res = AM.getResult<VerifierAnalysis>(F);
8334 if (res.IRBroken && FatalErrors)
8335 report_fatal_error("Broken function found, compilation aborted!");
8336
8337 return PreservedAnalyses::all();
8338}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
ArrayRef< TableEntry > TableRef
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
@ RetAttr
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
#define Check(C,...)
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
This file contains the declarations for metadata subclasses.
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getNumElements(Type *Ty)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
Definition Verifier.cpp:684
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
Definition Verifier.cpp:725
static bool isDINode(const Metadata *MD)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
static bool isTypeCongruent(Type *L, Type *R)
Two types are "congruent" if they are identical, or if they are both pointer types with different poi...
#define CheckTBAA(C,...)
static bool isConstantIntMetadataOperand(const Metadata *MD)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6080
bool isFiniteNonZero() const
Definition APFloat.h:1522
bool isNegative() const
Definition APFloat.h:1512
const fltSemantics & getSemantics() const
Definition APFloat.h:1520
Class for arbitrary precision integers.
Definition APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:418
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1157
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1577
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition APInt.h:400
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
Definition Function.cpp:292
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:470
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:539
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
Definition BasicBlock.h:493
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
bool isConditional() const
Value * getCondition() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
BasicBlock * getIndirectDest(unsigned i) const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
Definition InstrTypes.h:782
bool isIntPredicate() const
Definition InstrTypes.h:783
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:776
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isNegative() const
Definition Constants.h:214
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1078
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1065
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1068
Constant * getDeactivationSymbol() const
Definition Constants.h:1087
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1071
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI const BasicBlock * getParent() const
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
@ End
Marks the end of the concrete types.
@ Any
To indicate all LocationTypes in searches.
DIExpression * getAddressExpression() const
MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.h:290
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool empty() const
Definition DenseMap.h:109
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:246
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
const Function & getFunction() const
Definition Function.h:166
const std::string & getGC() const
Definition Function.cpp:819
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:216
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:680
static bool isValidLinkage(LinkageTypes L)
Definition GlobalIFunc.h:86
const Constant * getResolver() const
Definition GlobalIFunc.h:73
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition Value.h:577
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:329
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:108
bool hasComdat() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:561
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1080
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1444
bool isTemporary() const
Definition Metadata.h:1264
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
bool isDistinct() const
Definition Metadata.h:1263
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1260
LLVMContext & getContext() const
Definition Metadata.h:1244
bool equalsStr(StringRef Str) const
Definition Metadata.h:924
Metadata * get() const
Definition Metadata.h:931
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:632
static LLVM_ABI bool isTagMD(const Metadata *MD)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:118
Metadata * getMetadata() const
Definition Metadata.h:202
Root of the metadata hierarchy.
Definition Metadata.h:64
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
unsigned getMetadataID() const
Definition Metadata.h:104
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVM_ABI StringRef getName() const
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
static constexpr size_t npos
Definition StringRef.h:57
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
Definition Type.cpp:718
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:440
Verify that the TBAA Metadatas are valid.
Definition Verifier.h:40
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
Definition Type.cpp:74
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
Definition Type.cpp:90
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1065
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:296
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Definition Type.cpp:153
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:311
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:255
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:225
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:231
This class represents a cast unsigned integer to floating point.
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getValue() const
Definition Metadata.h:499
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > materialized_users()
Definition Value.h:421
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:717
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:824
iterator_range< user_iterator > users()
Definition Value.h:427
bool materialized_use_empty() const
Definition Value.h:352
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool hasName() const
Definition Value.h:262
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
Check a module for errors, and report separate error states for IR and debug info errors.
Definition Verifier.h:109
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
constexpr bool isNonZero() const
Definition TypeSize.h:155
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool isFlatGlobalAddrSpace(unsigned AS)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI MatchIntrinsicTypesResult matchIntrinsicSignature(FunctionType *FTy, ArrayRef< IITDescriptor > &Infos, SmallVectorImpl< Type * > &ArgTys)
Match the specified function type with the type constraints specified by the .td file.
LLVM_ABI void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
@ MatchIntrinsicTypes_NoMatchRet
Definition Intrinsics.h:258
@ MatchIntrinsicTypes_NoMatchArg
Definition Intrinsics.h:259
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
Definition Intrinsics.h:41
LLVM_ABI bool matchIntrinsicVarArg(bool isVarArg, ArrayRef< IITDescriptor > &Infos)
Verify if the intrinsic has variable arguments.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:189
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:48
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
@ DW_MACINFO_undef
Definition Dwarf.h:818
@ DW_MACINFO_start_file
Definition Dwarf.h:819
@ DW_MACINFO_define
Definition Dwarf.h:817
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:709
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:696
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:841
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
AllocFnKind
Definition Attributes.h:53
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
generic_gep_type_iterator<> gep_type_iterator
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:119
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
ArrayRef< Use > Inputs
void DebugInfoCheckFailed(const Twine &Message)
A debug info check failed.
Definition Verifier.cpp:307
VerifierSupport(raw_ostream *OS, const Module &M)
Definition Verifier.cpp:156
bool Broken
Track the brokenness of the module while recursively visiting.
Definition Verifier.cpp:150
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
Definition Verifier.cpp:300
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
Definition Verifier.cpp:152
LLVMContext & Context
Definition Verifier.cpp:147
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
Definition Verifier.cpp:154
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
Definition Verifier.cpp:289
const Module & M
Definition Verifier.cpp:143
const DataLayout & DL
Definition Verifier.cpp:146
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).
Definition Verifier.cpp:316
const Triple & TT
Definition Verifier.cpp:145
ModuleSlotTracker MST
Definition Verifier.cpp:144