1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
13 // Note that this does not provide full `Java style' security and verifications,
14 // instead it just tries to ensure that code is well-formed.
16 // * Both of a binary operator's parameters are of the same type
17 // * Verify that the indices of mem access instructions match other operands
18 // * Verify that arithmetic and other things are only performed on first-class
19 // types. Verify that shifts & logicals only happen on integrals f.e.
20 // * All of the constants in a switch statement are of the correct type
21 // * The code is in valid SSA form
22 // * It should be illegal to put a label into any other type (like a structure)
23 // or to return one. [except constant arrays!]
24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 // * PHI nodes must have an entry for each predecessor, with no extras.
26 // * PHI nodes must be the first thing in a basic block, all grouped together
27 // * PHI nodes must have at least one entry
28 // * All basic blocks should only end with terminator insts, not contain them
29 // * The entry node to a function must not have predecessors
30 // * All Instructions must be embedded into a basic block
31 // * Functions cannot take a void-typed parameter
32 // * Verify that a function's argument list agrees with it's declared type.
33 // * It is illegal to specify a name for a void value.
34 // * It is illegal to have a internal global value with no initializer
35 // * It is illegal to have a ret instruction that returns a value that does not
36 // agree with the function return value type.
37 // * Function call argument types match the function prototype
38 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
42 // * Landingpad instructions must be in a function with a personality function.
43 // * All other things that are tested by asserts spread about the code...
45 //===----------------------------------------------------------------------===//
47 #include "llvm/IR/Verifier.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/CallSite.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/ConstantRange.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DebugInfo.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/Dominators.h"
62 #include "llvm/IR/InlineAsm.h"
63 #include "llvm/IR/InstIterator.h"
64 #include "llvm/IR/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/IR/Statepoint.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
83 struct VerifierSupport {
87 /// \brief Track the brokenness of the module while recursively visiting.
90 explicit VerifierSupport(raw_ostream &OS)
91 : OS(OS), M(nullptr), Broken(false) {}
94 template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
98 void Write(const Module *M) {
101 OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
104 void Write(const Value *V) {
107 if (isa<Instruction>(V)) {
110 V->printAsOperand(OS, true, M);
114 void Write(ImmutableCallSite CS) {
115 Write(CS.getInstruction());
118 void Write(const Metadata *MD) {
125 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
129 void Write(const NamedMDNode *NMD) {
136 void Write(Type *T) {
142 void Write(const Comdat *C) {
148 template <typename T1, typename... Ts>
149 void WriteTs(const T1 &V1, const Ts &... Vs) {
154 template <typename... Ts> void WriteTs() {}
157 /// \brief A check failed, so printout out the condition and the message.
159 /// This provides a nice place to put a breakpoint if you want to see why
160 /// something is not correct.
161 void CheckFailed(const Twine &Message) {
162 OS << Message << '\n';
166 /// \brief A check failed (with values to print).
168 /// This calls the Message-only version so that the above is easier to set a
170 template <typename T1, typename... Ts>
171 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
172 CheckFailed(Message);
177 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
178 friend class InstVisitor<Verifier>;
180 LLVMContext *Context;
183 /// \brief When verifying a basic block, keep track of all of the
184 /// instructions we have seen so far.
186 /// This allows us to do efficient dominance checks for the case when an
187 /// instruction has an operand that is an instruction in the same block.
188 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
190 /// \brief Keep track of the metadata nodes that have been checked already.
191 SmallPtrSet<const Metadata *, 32> MDNodes;
193 /// \brief Track unresolved string-based type references.
194 SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
196 /// \brief The result type for a landingpad.
197 Type *LandingPadResultTy;
199 /// \brief Whether we've seen a call to @llvm.localescape in this function
203 /// Stores the count of how many objects were passed to llvm.localescape for a
204 /// given function and the largest index passed to llvm.localrecover.
205 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
207 /// Cache of constants visited in search of ConstantExprs.
208 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
210 void checkAtomicMemAccessSize(const Module *M, Type *Ty,
211 const Instruction *I);
213 explicit Verifier(raw_ostream &OS)
214 : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
215 SawFrameEscape(false) {}
217 bool verify(const Function &F) {
219 Context = &M->getContext();
221 // First ensure the function is well-enough formed to compute dominance
224 OS << "Function '" << F.getName()
225 << "' does not contain an entry block!\n";
228 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
229 if (I->empty() || !I->back().isTerminator()) {
230 OS << "Basic Block in function '" << F.getName()
231 << "' does not have terminator!\n";
232 I->printAsOperand(OS, true);
238 // Now directly compute a dominance tree. We don't rely on the pass
239 // manager to provide this as it isolates us from a potentially
240 // out-of-date dominator tree and makes it significantly more complex to
241 // run this code outside of a pass manager.
242 // FIXME: It's really gross that we have to cast away constness here.
243 DT.recalculate(const_cast<Function &>(F));
246 // FIXME: We strip const here because the inst visitor strips const.
247 visit(const_cast<Function &>(F));
248 InstsInThisBlock.clear();
249 LandingPadResultTy = nullptr;
250 SawFrameEscape = false;
255 bool verify(const Module &M) {
257 Context = &M.getContext();
260 // Scan through, checking all of the external function's linkage now...
261 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
262 visitGlobalValue(*I);
264 // Check to make sure function prototypes are okay.
265 if (I->isDeclaration())
269 // Now that we've visited every function, verify that we never asked to
270 // recover a frame index that wasn't escaped.
271 verifyFrameRecoverIndices();
273 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
275 visitGlobalVariable(*I);
277 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
279 visitGlobalAlias(*I);
281 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
282 E = M.named_metadata_end();
284 visitNamedMDNode(*I);
286 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
287 visitComdat(SMEC.getValue());
290 visitModuleIdents(M);
292 // Verify type referneces last.
299 // Verification methods...
300 void visitGlobalValue(const GlobalValue &GV);
301 void visitGlobalVariable(const GlobalVariable &GV);
302 void visitGlobalAlias(const GlobalAlias &GA);
303 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
304 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
305 const GlobalAlias &A, const Constant &C);
306 void visitNamedMDNode(const NamedMDNode &NMD);
307 void visitMDNode(const MDNode &MD);
308 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
309 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
310 void visitComdat(const Comdat &C);
311 void visitModuleIdents(const Module &M);
312 void visitModuleFlags(const Module &M);
313 void visitModuleFlag(const MDNode *Op,
314 DenseMap<const MDString *, const MDNode *> &SeenIDs,
315 SmallVectorImpl<const MDNode *> &Requirements);
316 void visitFunction(const Function &F);
317 void visitBasicBlock(BasicBlock &BB);
318 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
319 void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
321 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
322 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
323 #include "llvm/IR/Metadata.def"
324 void visitDIScope(const DIScope &N);
325 void visitDIVariable(const DIVariable &N);
326 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
327 void visitDITemplateParameter(const DITemplateParameter &N);
329 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
331 /// \brief Check for a valid string-based type reference.
333 /// Checks if \c MD is a string-based type reference. If it is, keeps track
334 /// of it (and its user, \c N) for error messages later.
335 bool isValidUUID(const MDNode &N, const Metadata *MD);
337 /// \brief Check for a valid type reference.
339 /// Checks for subclasses of \a DIType, or \a isValidUUID().
340 bool isTypeRef(const MDNode &N, const Metadata *MD);
342 /// \brief Check for a valid scope reference.
344 /// Checks for subclasses of \a DIScope, or \a isValidUUID().
345 bool isScopeRef(const MDNode &N, const Metadata *MD);
347 /// \brief Check for a valid debug info reference.
349 /// Checks for subclasses of \a DINode, or \a isValidUUID().
350 bool isDIRef(const MDNode &N, const Metadata *MD);
352 // InstVisitor overrides...
353 using InstVisitor<Verifier>::visit;
354 void visit(Instruction &I);
356 void visitTruncInst(TruncInst &I);
357 void visitZExtInst(ZExtInst &I);
358 void visitSExtInst(SExtInst &I);
359 void visitFPTruncInst(FPTruncInst &I);
360 void visitFPExtInst(FPExtInst &I);
361 void visitFPToUIInst(FPToUIInst &I);
362 void visitFPToSIInst(FPToSIInst &I);
363 void visitUIToFPInst(UIToFPInst &I);
364 void visitSIToFPInst(SIToFPInst &I);
365 void visitIntToPtrInst(IntToPtrInst &I);
366 void visitPtrToIntInst(PtrToIntInst &I);
367 void visitBitCastInst(BitCastInst &I);
368 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
369 void visitPHINode(PHINode &PN);
370 void visitBinaryOperator(BinaryOperator &B);
371 void visitICmpInst(ICmpInst &IC);
372 void visitFCmpInst(FCmpInst &FC);
373 void visitExtractElementInst(ExtractElementInst &EI);
374 void visitInsertElementInst(InsertElementInst &EI);
375 void visitShuffleVectorInst(ShuffleVectorInst &EI);
376 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
377 void visitCallInst(CallInst &CI);
378 void visitInvokeInst(InvokeInst &II);
379 void visitGetElementPtrInst(GetElementPtrInst &GEP);
380 void visitLoadInst(LoadInst &LI);
381 void visitStoreInst(StoreInst &SI);
382 void verifyDominatesUse(Instruction &I, unsigned i);
383 void visitInstruction(Instruction &I);
384 void visitTerminatorInst(TerminatorInst &I);
385 void visitBranchInst(BranchInst &BI);
386 void visitReturnInst(ReturnInst &RI);
387 void visitSwitchInst(SwitchInst &SI);
388 void visitIndirectBrInst(IndirectBrInst &BI);
389 void visitSelectInst(SelectInst &SI);
390 void visitUserOp1(Instruction &I);
391 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
392 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
393 template <class DbgIntrinsicTy>
394 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
395 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
396 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
397 void visitFenceInst(FenceInst &FI);
398 void visitAllocaInst(AllocaInst &AI);
399 void visitExtractValueInst(ExtractValueInst &EVI);
400 void visitInsertValueInst(InsertValueInst &IVI);
401 void visitEHPadPredecessors(Instruction &I);
402 void visitLandingPadInst(LandingPadInst &LPI);
403 void visitCatchPadInst(CatchPadInst &CPI);
404 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
405 void visitCleanupPadInst(CleanupPadInst &CPI);
406 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
407 void visitCleanupReturnInst(CleanupReturnInst &CRI);
409 void VerifyCallSite(CallSite CS);
410 void verifyMustTailCall(CallInst &CI);
411 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
412 unsigned ArgNo, std::string &Suffix);
413 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
414 SmallVectorImpl<Type *> &ArgTys);
415 bool VerifyIntrinsicIsVarArg(bool isVarArg,
416 ArrayRef<Intrinsic::IITDescriptor> &Infos);
417 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
418 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
420 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
421 bool isReturnValue, const Value *V);
422 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
424 void VerifyFunctionMetadata(
425 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
427 void visitConstantExprsRecursively(const Constant *EntryC);
428 void visitConstantExpr(const ConstantExpr *CE);
429 void VerifyStatepoint(ImmutableCallSite CS);
430 void verifyFrameRecoverIndices();
432 // Module-level debug info verification...
433 void verifyTypeRefs();
434 template <class MapTy>
435 void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
436 const MapTy &TypeRefs);
437 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
439 } // End anonymous namespace
441 // Assert - We know that cond should be true, if not print an error message.
442 #define Assert(C, ...) \
443 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
445 void Verifier::visit(Instruction &I) {
446 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
447 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
448 InstVisitor<Verifier>::visit(I);
452 void Verifier::visitGlobalValue(const GlobalValue &GV) {
453 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
454 GV.hasExternalWeakLinkage(),
455 "Global is external, but doesn't have external or weak linkage!", &GV);
457 Assert(GV.getAlignment() <= Value::MaximumAlignment,
458 "huge alignment values are unsupported", &GV);
459 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
460 "Only global variables can have appending linkage!", &GV);
462 if (GV.hasAppendingLinkage()) {
463 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
464 Assert(GVar && GVar->getValueType()->isArrayTy(),
465 "Only global arrays can have appending linkage!", GVar);
468 if (GV.isDeclarationForLinker())
469 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
472 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
473 if (GV.hasInitializer()) {
474 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
475 "Global variable initializer type does not match global "
479 // If the global has common linkage, it must have a zero initializer and
480 // cannot be constant.
481 if (GV.hasCommonLinkage()) {
482 Assert(GV.getInitializer()->isNullValue(),
483 "'common' global must have a zero initializer!", &GV);
484 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
486 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
489 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
490 "invalid linkage type for global declaration", &GV);
493 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
494 GV.getName() == "llvm.global_dtors")) {
495 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
496 "invalid linkage for intrinsic global variable", &GV);
497 // Don't worry about emitting an error for it not being an array,
498 // visitGlobalValue will complain on appending non-array.
499 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
500 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
501 PointerType *FuncPtrTy =
502 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
503 // FIXME: Reject the 2-field form in LLVM 4.0.
505 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
506 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
507 STy->getTypeAtIndex(1) == FuncPtrTy,
508 "wrong type for intrinsic global variable", &GV);
509 if (STy->getNumElements() == 3) {
510 Type *ETy = STy->getTypeAtIndex(2);
511 Assert(ETy->isPointerTy() &&
512 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
513 "wrong type for intrinsic global variable", &GV);
518 if (GV.hasName() && (GV.getName() == "llvm.used" ||
519 GV.getName() == "llvm.compiler.used")) {
520 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
521 "invalid linkage for intrinsic global variable", &GV);
522 Type *GVType = GV.getValueType();
523 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
524 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
525 Assert(PTy, "wrong type for intrinsic global variable", &GV);
526 if (GV.hasInitializer()) {
527 const Constant *Init = GV.getInitializer();
528 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
529 Assert(InitArray, "wrong initalizer for intrinsic global variable",
531 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
532 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
533 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
535 "invalid llvm.used member", V);
536 Assert(V->hasName(), "members of llvm.used must be named", V);
542 Assert(!GV.hasDLLImportStorageClass() ||
543 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
544 GV.hasAvailableExternallyLinkage(),
545 "Global is marked as dllimport, but not external", &GV);
547 if (!GV.hasInitializer()) {
548 visitGlobalValue(GV);
552 // Walk any aggregate initializers looking for bitcasts between address spaces
553 visitConstantExprsRecursively(GV.getInitializer());
555 visitGlobalValue(GV);
558 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
559 SmallPtrSet<const GlobalAlias*, 4> Visited;
561 visitAliaseeSubExpr(Visited, GA, C);
564 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
565 const GlobalAlias &GA, const Constant &C) {
566 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
567 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
570 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
571 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
573 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
576 // Only continue verifying subexpressions of GlobalAliases.
577 // Do not recurse into global initializers.
582 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
583 visitConstantExprsRecursively(CE);
585 for (const Use &U : C.operands()) {
587 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
588 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
589 else if (const auto *C2 = dyn_cast<Constant>(V))
590 visitAliaseeSubExpr(Visited, GA, *C2);
594 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
595 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
596 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
597 "weak_odr, or external linkage!",
599 const Constant *Aliasee = GA.getAliasee();
600 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
601 Assert(GA.getType() == Aliasee->getType(),
602 "Alias and aliasee types should match!", &GA);
604 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
605 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
607 visitAliaseeSubExpr(GA, *Aliasee);
609 visitGlobalValue(GA);
612 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
613 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
614 MDNode *MD = NMD.getOperand(i);
616 if (NMD.getName() == "llvm.dbg.cu") {
617 Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
627 void Verifier::visitMDNode(const MDNode &MD) {
628 // Only visit each node once. Metadata can be mutually recursive, so this
629 // avoids infinite recursion here, as well as being an optimization.
630 if (!MDNodes.insert(&MD).second)
633 switch (MD.getMetadataID()) {
635 llvm_unreachable("Invalid MDNode subclass");
636 case Metadata::MDTupleKind:
638 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
639 case Metadata::CLASS##Kind: \
640 visit##CLASS(cast<CLASS>(MD)); \
642 #include "llvm/IR/Metadata.def"
645 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
646 Metadata *Op = MD.getOperand(i);
649 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
651 if (auto *N = dyn_cast<MDNode>(Op)) {
655 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
656 visitValueAsMetadata(*V, nullptr);
661 // Check these last, so we diagnose problems in operands first.
662 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
663 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
666 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
667 Assert(MD.getValue(), "Expected valid value", &MD);
668 Assert(!MD.getValue()->getType()->isMetadataTy(),
669 "Unexpected metadata round-trip through values", &MD, MD.getValue());
671 auto *L = dyn_cast<LocalAsMetadata>(&MD);
675 Assert(F, "function-local metadata used outside a function", L);
677 // If this was an instruction, bb, or argument, verify that it is in the
678 // function that we expect.
679 Function *ActualF = nullptr;
680 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
681 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
682 ActualF = I->getParent()->getParent();
683 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
684 ActualF = BB->getParent();
685 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
686 ActualF = A->getParent();
687 assert(ActualF && "Unimplemented function local metadata case!");
689 Assert(ActualF == F, "function-local metadata used in wrong function", L);
692 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
693 Metadata *MD = MDV.getMetadata();
694 if (auto *N = dyn_cast<MDNode>(MD)) {
699 // Only visit each node once. Metadata can be mutually recursive, so this
700 // avoids infinite recursion here, as well as being an optimization.
701 if (!MDNodes.insert(MD).second)
704 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
705 visitValueAsMetadata(*V, F);
708 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
709 auto *S = dyn_cast<MDString>(MD);
712 if (S->getString().empty())
715 // Keep track of names of types referenced via UUID so we can check that they
717 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
721 /// \brief Check if a value can be a reference to a type.
722 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
723 return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
726 /// \brief Check if a value can be a ScopeRef.
727 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
728 return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
731 /// \brief Check if a value can be a debug info ref.
732 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
733 return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
737 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
738 for (Metadata *MD : N.operands()) {
751 bool isValidMetadataArray(const MDTuple &N) {
752 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
756 bool isValidMetadataNullArray(const MDTuple &N) {
757 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
760 void Verifier::visitDILocation(const DILocation &N) {
761 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
762 "location requires a valid scope", &N, N.getRawScope());
763 if (auto *IA = N.getRawInlinedAt())
764 Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
767 void Verifier::visitGenericDINode(const GenericDINode &N) {
768 Assert(N.getTag(), "invalid tag", &N);
771 void Verifier::visitDIScope(const DIScope &N) {
772 if (auto *F = N.getRawFile())
773 Assert(isa<DIFile>(F), "invalid file", &N, F);
776 void Verifier::visitDISubrange(const DISubrange &N) {
777 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
778 Assert(N.getCount() >= -1, "invalid subrange count", &N);
781 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
782 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
785 void Verifier::visitDIBasicType(const DIBasicType &N) {
786 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
787 N.getTag() == dwarf::DW_TAG_unspecified_type,
791 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
792 // Common scope checks.
795 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
796 N.getTag() == dwarf::DW_TAG_pointer_type ||
797 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
798 N.getTag() == dwarf::DW_TAG_reference_type ||
799 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
800 N.getTag() == dwarf::DW_TAG_const_type ||
801 N.getTag() == dwarf::DW_TAG_volatile_type ||
802 N.getTag() == dwarf::DW_TAG_restrict_type ||
803 N.getTag() == dwarf::DW_TAG_member ||
804 N.getTag() == dwarf::DW_TAG_inheritance ||
805 N.getTag() == dwarf::DW_TAG_friend,
807 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
808 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
812 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
813 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
817 static bool hasConflictingReferenceFlags(unsigned Flags) {
818 return (Flags & DINode::FlagLValueReference) &&
819 (Flags & DINode::FlagRValueReference);
822 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
823 auto *Params = dyn_cast<MDTuple>(&RawParams);
824 Assert(Params, "invalid template params", &N, &RawParams);
825 for (Metadata *Op : Params->operands()) {
826 Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
831 void Verifier::visitDICompositeType(const DICompositeType &N) {
832 // Common scope checks.
835 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
836 N.getTag() == dwarf::DW_TAG_structure_type ||
837 N.getTag() == dwarf::DW_TAG_union_type ||
838 N.getTag() == dwarf::DW_TAG_enumeration_type ||
839 N.getTag() == dwarf::DW_TAG_class_type,
842 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
843 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
846 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
847 "invalid composite elements", &N, N.getRawElements());
848 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
849 N.getRawVTableHolder());
850 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
852 if (auto *Params = N.getRawTemplateParams())
853 visitTemplateParams(N, *Params);
855 if (N.getTag() == dwarf::DW_TAG_class_type ||
856 N.getTag() == dwarf::DW_TAG_union_type) {
857 Assert(N.getFile() && !N.getFile()->getFilename().empty(),
858 "class/union requires a filename", &N, N.getFile());
862 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
863 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
864 if (auto *Types = N.getRawTypeArray()) {
865 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
866 for (Metadata *Ty : N.getTypeArray()->operands()) {
867 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
870 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
874 void Verifier::visitDIFile(const DIFile &N) {
875 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
878 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
879 Assert(N.isDistinct(), "compile units must be distinct", &N);
880 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
882 // Don't bother verifying the compilation directory or producer string
883 // as those could be empty.
884 Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
886 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
889 if (auto *Array = N.getRawEnumTypes()) {
890 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
891 for (Metadata *Op : N.getEnumTypes()->operands()) {
892 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
893 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
894 "invalid enum type", &N, N.getEnumTypes(), Op);
897 if (auto *Array = N.getRawRetainedTypes()) {
898 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
899 for (Metadata *Op : N.getRetainedTypes()->operands()) {
900 Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
903 if (auto *Array = N.getRawSubprograms()) {
904 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
905 for (Metadata *Op : N.getSubprograms()->operands()) {
906 Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
909 if (auto *Array = N.getRawGlobalVariables()) {
910 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
911 for (Metadata *Op : N.getGlobalVariables()->operands()) {
912 Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
916 if (auto *Array = N.getRawImportedEntities()) {
917 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
918 for (Metadata *Op : N.getImportedEntities()->operands()) {
919 Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
923 if (auto *Array = N.getRawMacros()) {
924 Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
925 for (Metadata *Op : N.getMacros()->operands()) {
926 Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
931 void Verifier::visitDISubprogram(const DISubprogram &N) {
932 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
933 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
934 if (auto *T = N.getRawType())
935 Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
936 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
937 N.getRawContainingType());
938 if (auto *Params = N.getRawTemplateParams())
939 visitTemplateParams(N, *Params);
940 if (auto *S = N.getRawDeclaration()) {
941 Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
942 "invalid subprogram declaration", &N, S);
944 if (auto *RawVars = N.getRawVariables()) {
945 auto *Vars = dyn_cast<MDTuple>(RawVars);
946 Assert(Vars, "invalid variable list", &N, RawVars);
947 for (Metadata *Op : Vars->operands()) {
948 Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
952 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
955 if (N.isDefinition())
956 Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
959 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
960 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
961 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
962 "invalid local scope", &N, N.getRawScope());
965 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
966 visitDILexicalBlockBase(N);
968 Assert(N.getLine() || !N.getColumn(),
969 "cannot have column info without line info", &N);
972 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
973 visitDILexicalBlockBase(N);
976 void Verifier::visitDINamespace(const DINamespace &N) {
977 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
978 if (auto *S = N.getRawScope())
979 Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
982 void Verifier::visitDIMacro(const DIMacro &N) {
983 Assert(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
984 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
985 "invalid macinfo type", &N);
986 Assert(!N.getName().empty(), "anonymous macro", &N);
987 if (!N.getValue().empty()) {
988 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
992 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
993 Assert(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
994 "invalid macinfo type", &N);
995 if (auto *F = N.getRawFile())
996 Assert(isa<DIFile>(F), "invalid file", &N, F);
998 if (auto *Array = N.getRawElements()) {
999 Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1000 for (Metadata *Op : N.getElements()->operands()) {
1001 Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1006 void Verifier::visitDIModule(const DIModule &N) {
1007 Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1008 Assert(!N.getName().empty(), "anonymous module", &N);
1011 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1012 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1015 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1016 visitDITemplateParameter(N);
1018 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1022 void Verifier::visitDITemplateValueParameter(
1023 const DITemplateValueParameter &N) {
1024 visitDITemplateParameter(N);
1026 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1027 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1028 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1032 void Verifier::visitDIVariable(const DIVariable &N) {
1033 if (auto *S = N.getRawScope())
1034 Assert(isa<DIScope>(S), "invalid scope", &N, S);
1035 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1036 if (auto *F = N.getRawFile())
1037 Assert(isa<DIFile>(F), "invalid file", &N, F);
1040 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1041 // Checks common to all variables.
1044 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1045 Assert(!N.getName().empty(), "missing global variable name", &N);
1046 if (auto *V = N.getRawVariable()) {
1047 Assert(isa<ConstantAsMetadata>(V) &&
1048 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1049 "invalid global varaible ref", &N, V);
1051 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1052 Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1057 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1058 // Checks common to all variables.
1061 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1062 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1063 "local variable requires a valid scope", &N, N.getRawScope());
1066 void Verifier::visitDIExpression(const DIExpression &N) {
1067 Assert(N.isValid(), "invalid expression", &N);
1070 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1071 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1072 if (auto *T = N.getRawType())
1073 Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1074 if (auto *F = N.getRawFile())
1075 Assert(isa<DIFile>(F), "invalid file", &N, F);
1078 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1079 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1080 N.getTag() == dwarf::DW_TAG_imported_declaration,
1082 if (auto *S = N.getRawScope())
1083 Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1084 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1088 void Verifier::visitComdat(const Comdat &C) {
1089 // The Module is invalid if the GlobalValue has private linkage. Entities
1090 // with private linkage don't have entries in the symbol table.
1091 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1092 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1096 void Verifier::visitModuleIdents(const Module &M) {
1097 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1101 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1102 // Scan each llvm.ident entry and make sure that this requirement is met.
1103 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1104 const MDNode *N = Idents->getOperand(i);
1105 Assert(N->getNumOperands() == 1,
1106 "incorrect number of operands in llvm.ident metadata", N);
1107 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1108 ("invalid value for llvm.ident metadata entry operand"
1109 "(the operand should be a string)"),
1114 void Verifier::visitModuleFlags(const Module &M) {
1115 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1118 // Scan each flag, and track the flags and requirements.
1119 DenseMap<const MDString*, const MDNode*> SeenIDs;
1120 SmallVector<const MDNode*, 16> Requirements;
1121 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1122 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1125 // Validate that the requirements in the module are valid.
1126 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1127 const MDNode *Requirement = Requirements[I];
1128 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1129 const Metadata *ReqValue = Requirement->getOperand(1);
1131 const MDNode *Op = SeenIDs.lookup(Flag);
1133 CheckFailed("invalid requirement on flag, flag is not present in module",
1138 if (Op->getOperand(2) != ReqValue) {
1139 CheckFailed(("invalid requirement on flag, "
1140 "flag does not have the required value"),
1148 Verifier::visitModuleFlag(const MDNode *Op,
1149 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1150 SmallVectorImpl<const MDNode *> &Requirements) {
1151 // Each module flag should have three arguments, the merge behavior (a
1152 // constant int), the flag ID (an MDString), and the value.
1153 Assert(Op->getNumOperands() == 3,
1154 "incorrect number of operands in module flag", Op);
1155 Module::ModFlagBehavior MFB;
1156 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1158 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1159 "invalid behavior operand in module flag (expected constant integer)",
1162 "invalid behavior operand in module flag (unexpected constant)",
1165 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1166 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1169 // Sanity check the values for behaviors with additional requirements.
1172 case Module::Warning:
1173 case Module::Override:
1174 // These behavior types accept any value.
1177 case Module::Require: {
1178 // The value should itself be an MDNode with two operands, a flag ID (an
1179 // MDString), and a value.
1180 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1181 Assert(Value && Value->getNumOperands() == 2,
1182 "invalid value for 'require' module flag (expected metadata pair)",
1184 Assert(isa<MDString>(Value->getOperand(0)),
1185 ("invalid value for 'require' module flag "
1186 "(first value operand should be a string)"),
1187 Value->getOperand(0));
1189 // Append it to the list of requirements, to check once all module flags are
1191 Requirements.push_back(Value);
1195 case Module::Append:
1196 case Module::AppendUnique: {
1197 // These behavior types require the operand be an MDNode.
1198 Assert(isa<MDNode>(Op->getOperand(2)),
1199 "invalid value for 'append'-type module flag "
1200 "(expected a metadata node)",
1206 // Unless this is a "requires" flag, check the ID is unique.
1207 if (MFB != Module::Require) {
1208 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1210 "module flag identifiers must be unique (or of 'require' type)", ID);
1214 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1215 bool isFunction, const Value *V) {
1216 unsigned Slot = ~0U;
1217 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1218 if (Attrs.getSlotIndex(I) == Idx) {
1223 assert(Slot != ~0U && "Attribute set inconsistency!");
1225 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1227 if (I->isStringAttribute())
1230 if (I->getKindAsEnum() == Attribute::NoReturn ||
1231 I->getKindAsEnum() == Attribute::NoUnwind ||
1232 I->getKindAsEnum() == Attribute::NoInline ||
1233 I->getKindAsEnum() == Attribute::AlwaysInline ||
1234 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1235 I->getKindAsEnum() == Attribute::StackProtect ||
1236 I->getKindAsEnum() == Attribute::StackProtectReq ||
1237 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1238 I->getKindAsEnum() == Attribute::SafeStack ||
1239 I->getKindAsEnum() == Attribute::NoRedZone ||
1240 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1241 I->getKindAsEnum() == Attribute::Naked ||
1242 I->getKindAsEnum() == Attribute::InlineHint ||
1243 I->getKindAsEnum() == Attribute::StackAlignment ||
1244 I->getKindAsEnum() == Attribute::UWTable ||
1245 I->getKindAsEnum() == Attribute::NonLazyBind ||
1246 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1247 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1248 I->getKindAsEnum() == Attribute::SanitizeThread ||
1249 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1250 I->getKindAsEnum() == Attribute::MinSize ||
1251 I->getKindAsEnum() == Attribute::NoDuplicate ||
1252 I->getKindAsEnum() == Attribute::Builtin ||
1253 I->getKindAsEnum() == Attribute::NoBuiltin ||
1254 I->getKindAsEnum() == Attribute::Cold ||
1255 I->getKindAsEnum() == Attribute::OptimizeNone ||
1256 I->getKindAsEnum() == Attribute::JumpTable ||
1257 I->getKindAsEnum() == Attribute::Convergent ||
1258 I->getKindAsEnum() == Attribute::ArgMemOnly ||
1259 I->getKindAsEnum() == Attribute::NoRecurse ||
1260 I->getKindAsEnum() == Attribute::InaccessibleMemOnly ||
1261 I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly) {
1263 CheckFailed("Attribute '" + I->getAsString() +
1264 "' only applies to functions!", V);
1267 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1268 I->getKindAsEnum() == Attribute::ReadNone) {
1270 CheckFailed("Attribute '" + I->getAsString() +
1271 "' does not apply to function returns");
1274 } else if (isFunction) {
1275 CheckFailed("Attribute '" + I->getAsString() +
1276 "' does not apply to functions!", V);
1282 // VerifyParameterAttrs - Check the given attributes for an argument or return
1283 // value of the specified type. The value V is printed in error messages.
1284 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1285 bool isReturnValue, const Value *V) {
1286 if (!Attrs.hasAttributes(Idx))
1289 VerifyAttributeTypes(Attrs, Idx, false, V);
1292 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1293 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1294 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1295 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1296 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1297 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1298 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1299 "'returned' do not apply to return values!",
1302 // Check for mutually incompatible attributes. Only inreg is compatible with
1304 unsigned AttrCount = 0;
1305 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1306 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1307 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1308 Attrs.hasAttribute(Idx, Attribute::InReg);
1309 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1310 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1311 "and 'sret' are incompatible!",
1314 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1315 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1317 "'inalloca and readonly' are incompatible!",
1320 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1321 Attrs.hasAttribute(Idx, Attribute::Returned)),
1323 "'sret and returned' are incompatible!",
1326 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1327 Attrs.hasAttribute(Idx, Attribute::SExt)),
1329 "'zeroext and signext' are incompatible!",
1332 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1333 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1335 "'readnone and readonly' are incompatible!",
1338 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1339 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1341 "'noinline and alwaysinline' are incompatible!",
1344 Assert(!AttrBuilder(Attrs, Idx)
1345 .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1346 "Wrong types for attribute: " +
1347 AttributeSet::get(*Context, Idx,
1348 AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1351 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1352 SmallPtrSet<Type*, 4> Visited;
1353 if (!PTy->getElementType()->isSized(&Visited)) {
1354 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1355 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1356 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1360 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1361 "Attribute 'byval' only applies to parameters with pointer type!",
1366 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1367 // The value V is printed in error messages.
1368 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1370 if (Attrs.isEmpty())
1373 bool SawNest = false;
1374 bool SawReturned = false;
1375 bool SawSRet = false;
1377 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1378 unsigned Idx = Attrs.getSlotIndex(i);
1382 Ty = FT->getReturnType();
1383 else if (Idx-1 < FT->getNumParams())
1384 Ty = FT->getParamType(Idx-1);
1386 break; // VarArgs attributes, verified elsewhere.
1388 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1393 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1394 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1398 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1399 Assert(!SawReturned, "More than one parameter has attribute returned!",
1401 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1403 "argument and return types for 'returned' attribute",
1408 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1409 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1410 Assert(Idx == 1 || Idx == 2,
1411 "Attribute 'sret' is not on first or second parameter!", V);
1415 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1416 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1421 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1424 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1427 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1428 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1429 "Attributes 'readnone and readonly' are incompatible!", V);
1432 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1433 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1434 Attribute::InaccessibleMemOrArgMemOnly)),
1435 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V);
1438 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1439 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1440 Attribute::InaccessibleMemOnly)),
1441 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1444 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1445 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1446 Attribute::AlwaysInline)),
1447 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1449 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1450 Attribute::OptimizeNone)) {
1451 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1452 "Attribute 'optnone' requires 'noinline'!", V);
1454 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1455 Attribute::OptimizeForSize),
1456 "Attributes 'optsize and optnone' are incompatible!", V);
1458 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1459 "Attributes 'minsize and optnone' are incompatible!", V);
1462 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1463 Attribute::JumpTable)) {
1464 const GlobalValue *GV = cast<GlobalValue>(V);
1465 Assert(GV->hasUnnamedAddr(),
1466 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1470 void Verifier::VerifyFunctionMetadata(
1471 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1475 for (unsigned i = 0; i < MDs.size(); i++) {
1476 if (MDs[i].first == LLVMContext::MD_prof) {
1477 MDNode *MD = MDs[i].second;
1478 Assert(MD->getNumOperands() == 2,
1479 "!prof annotations should have exactly 2 operands", MD);
1481 // Check first operand.
1482 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1484 Assert(isa<MDString>(MD->getOperand(0)),
1485 "expected string with name of the !prof annotation", MD);
1486 MDString *MDS = cast<MDString>(MD->getOperand(0));
1487 StringRef ProfName = MDS->getString();
1488 Assert(ProfName.equals("function_entry_count"),
1489 "first operand should be 'function_entry_count'", MD);
1491 // Check second operand.
1492 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1494 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1495 "expected integer argument to function_entry_count", MD);
1500 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1501 if (!ConstantExprVisited.insert(EntryC).second)
1504 SmallVector<const Constant *, 16> Stack;
1505 Stack.push_back(EntryC);
1507 while (!Stack.empty()) {
1508 const Constant *C = Stack.pop_back_val();
1510 // Check this constant expression.
1511 if (const auto *CE = dyn_cast<ConstantExpr>(C))
1512 visitConstantExpr(CE);
1514 // Visit all sub-expressions.
1515 for (const Use &U : C->operands()) {
1516 const auto *OpC = dyn_cast<Constant>(U);
1519 if (isa<GlobalValue>(OpC))
1520 continue; // Global values get visited separately.
1521 if (!ConstantExprVisited.insert(OpC).second)
1523 Stack.push_back(OpC);
1528 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
1529 if (CE->getOpcode() != Instruction::BitCast)
1532 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1534 "Invalid bitcast", CE);
1537 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1538 if (Attrs.getNumSlots() == 0)
1541 unsigned LastSlot = Attrs.getNumSlots() - 1;
1542 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1543 if (LastIndex <= Params
1544 || (LastIndex == AttributeSet::FunctionIndex
1545 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1551 /// \brief Verify that statepoint intrinsic is well formed.
1552 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1553 assert(CS.getCalledFunction() &&
1554 CS.getCalledFunction()->getIntrinsicID() ==
1555 Intrinsic::experimental_gc_statepoint);
1557 const Instruction &CI = *CS.getInstruction();
1559 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1560 !CS.onlyAccessesArgMemory(),
1561 "gc.statepoint must read and write all memory to preserve "
1562 "reordering restrictions required by safepoint semantics",
1565 const Value *IDV = CS.getArgument(0);
1566 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1569 const Value *NumPatchBytesV = CS.getArgument(1);
1570 Assert(isa<ConstantInt>(NumPatchBytesV),
1571 "gc.statepoint number of patchable bytes must be a constant integer",
1573 const int64_t NumPatchBytes =
1574 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1575 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1576 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1580 const Value *Target = CS.getArgument(2);
1581 auto *PT = dyn_cast<PointerType>(Target->getType());
1582 Assert(PT && PT->getElementType()->isFunctionTy(),
1583 "gc.statepoint callee must be of function pointer type", &CI, Target);
1584 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1586 const Value *NumCallArgsV = CS.getArgument(3);
1587 Assert(isa<ConstantInt>(NumCallArgsV),
1588 "gc.statepoint number of arguments to underlying call "
1589 "must be constant integer",
1591 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1592 Assert(NumCallArgs >= 0,
1593 "gc.statepoint number of arguments to underlying call "
1596 const int NumParams = (int)TargetFuncType->getNumParams();
1597 if (TargetFuncType->isVarArg()) {
1598 Assert(NumCallArgs >= NumParams,
1599 "gc.statepoint mismatch in number of vararg call args", &CI);
1601 // TODO: Remove this limitation
1602 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1603 "gc.statepoint doesn't support wrapping non-void "
1604 "vararg functions yet",
1607 Assert(NumCallArgs == NumParams,
1608 "gc.statepoint mismatch in number of call args", &CI);
1610 const Value *FlagsV = CS.getArgument(4);
1611 Assert(isa<ConstantInt>(FlagsV),
1612 "gc.statepoint flags must be constant integer", &CI);
1613 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1614 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1615 "unknown flag used in gc.statepoint flags argument", &CI);
1617 // Verify that the types of the call parameter arguments match
1618 // the type of the wrapped callee.
1619 for (int i = 0; i < NumParams; i++) {
1620 Type *ParamType = TargetFuncType->getParamType(i);
1621 Type *ArgType = CS.getArgument(5 + i)->getType();
1622 Assert(ArgType == ParamType,
1623 "gc.statepoint call argument does not match wrapped "
1628 const int EndCallArgsInx = 4 + NumCallArgs;
1630 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1631 Assert(isa<ConstantInt>(NumTransitionArgsV),
1632 "gc.statepoint number of transition arguments "
1633 "must be constant integer",
1635 const int NumTransitionArgs =
1636 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1637 Assert(NumTransitionArgs >= 0,
1638 "gc.statepoint number of transition arguments must be positive", &CI);
1639 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1641 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1642 Assert(isa<ConstantInt>(NumDeoptArgsV),
1643 "gc.statepoint number of deoptimization arguments "
1644 "must be constant integer",
1646 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1647 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1651 const int ExpectedNumArgs =
1652 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1653 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1654 "gc.statepoint too few arguments according to length fields", &CI);
1656 // Check that the only uses of this gc.statepoint are gc.result or
1657 // gc.relocate calls which are tied to this statepoint and thus part
1658 // of the same statepoint sequence
1659 for (const User *U : CI.users()) {
1660 const CallInst *Call = dyn_cast<const CallInst>(U);
1661 Assert(Call, "illegal use of statepoint token", &CI, U);
1662 if (!Call) continue;
1663 Assert(isa<GCRelocateInst>(Call) || isGCResult(Call),
1664 "gc.result or gc.relocate are the only value uses"
1665 "of a gc.statepoint",
1667 if (isGCResult(Call)) {
1668 Assert(Call->getArgOperand(0) == &CI,
1669 "gc.result connected to wrong gc.statepoint", &CI, Call);
1670 } else if (isa<GCRelocateInst>(Call)) {
1671 Assert(Call->getArgOperand(0) == &CI,
1672 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1676 // Note: It is legal for a single derived pointer to be listed multiple
1677 // times. It's non-optimal, but it is legal. It can also happen after
1678 // insertion if we strip a bitcast away.
1679 // Note: It is really tempting to check that each base is relocated and
1680 // that a derived pointer is never reused as a base pointer. This turns
1681 // out to be problematic since optimizations run after safepoint insertion
1682 // can recognize equality properties that the insertion logic doesn't know
1683 // about. See example statepoint.ll in the verifier subdirectory
1686 void Verifier::verifyFrameRecoverIndices() {
1687 for (auto &Counts : FrameEscapeInfo) {
1688 Function *F = Counts.first;
1689 unsigned EscapedObjectCount = Counts.second.first;
1690 unsigned MaxRecoveredIndex = Counts.second.second;
1691 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1692 "all indices passed to llvm.localrecover must be less than the "
1693 "number of arguments passed ot llvm.localescape in the parent "
1699 // visitFunction - Verify that a function is ok.
1701 void Verifier::visitFunction(const Function &F) {
1702 // Check function arguments.
1703 FunctionType *FT = F.getFunctionType();
1704 unsigned NumArgs = F.arg_size();
1706 Assert(Context == &F.getContext(),
1707 "Function context does not match Module context!", &F);
1709 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1710 Assert(FT->getNumParams() == NumArgs,
1711 "# formal arguments must match # of arguments for function type!", &F,
1713 Assert(F.getReturnType()->isFirstClassType() ||
1714 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1715 "Functions cannot return aggregate values!", &F);
1717 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1718 "Invalid struct return type!", &F);
1720 AttributeSet Attrs = F.getAttributes();
1722 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1723 "Attribute after last parameter!", &F);
1725 // Check function attributes.
1726 VerifyFunctionAttrs(FT, Attrs, &F);
1728 // On function declarations/definitions, we do not support the builtin
1729 // attribute. We do not check this in VerifyFunctionAttrs since that is
1730 // checking for Attributes that can/can not ever be on functions.
1731 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1732 "Attribute 'builtin' can only be applied to a callsite.", &F);
1734 // Check that this function meets the restrictions on this calling convention.
1735 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1736 // restrictions can be lifted.
1737 switch (F.getCallingConv()) {
1739 case CallingConv::C:
1741 case CallingConv::Fast:
1742 case CallingConv::Cold:
1743 case CallingConv::Intel_OCL_BI:
1744 case CallingConv::PTX_Kernel:
1745 case CallingConv::PTX_Device:
1746 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1747 "perfect forwarding!",
1752 bool isLLVMdotName = F.getName().size() >= 5 &&
1753 F.getName().substr(0, 5) == "llvm.";
1755 // Check that the argument values match the function type for this function...
1757 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1759 Assert(I->getType() == FT->getParamType(i),
1760 "Argument value does not match function argument type!", I,
1761 FT->getParamType(i));
1762 Assert(I->getType()->isFirstClassType(),
1763 "Function arguments must have first-class types!", I);
1764 if (!isLLVMdotName) {
1765 Assert(!I->getType()->isMetadataTy(),
1766 "Function takes metadata but isn't an intrinsic", I, &F);
1767 Assert(!I->getType()->isTokenTy(),
1768 "Function takes token but isn't an intrinsic", I, &F);
1773 Assert(!F.getReturnType()->isTokenTy(),
1774 "Functions returns a token but isn't an intrinsic", &F);
1776 // Get the function metadata attachments.
1777 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1778 F.getAllMetadata(MDs);
1779 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1780 VerifyFunctionMetadata(MDs);
1782 // Check validity of the personality function
1783 if (F.hasPersonalityFn()) {
1784 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1786 Assert(Per->getParent() == F.getParent(),
1787 "Referencing personality function in another module!",
1788 &F, F.getParent(), Per, Per->getParent());
1791 if (F.isMaterializable()) {
1792 // Function has a body somewhere we can't see.
1793 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1794 MDs.empty() ? nullptr : MDs.front().second);
1795 } else if (F.isDeclaration()) {
1796 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1797 "invalid linkage type for function declaration", &F);
1798 Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1799 MDs.empty() ? nullptr : MDs.front().second);
1800 Assert(!F.hasPersonalityFn(),
1801 "Function declaration shouldn't have a personality routine", &F);
1803 // Verify that this function (which has a body) is not named "llvm.*". It
1804 // is not legal to define intrinsics.
1805 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1807 // Check the entry node
1808 const BasicBlock *Entry = &F.getEntryBlock();
1809 Assert(pred_empty(Entry),
1810 "Entry block to function must not have predecessors!", Entry);
1812 // The address of the entry block cannot be taken, unless it is dead.
1813 if (Entry->hasAddressTaken()) {
1814 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1815 "blockaddress may not be used with the entry block!", Entry);
1818 // Visit metadata attachments.
1819 for (const auto &I : MDs) {
1820 // Verify that the attachment is legal.
1824 case LLVMContext::MD_dbg:
1825 Assert(isa<DISubprogram>(I.second),
1826 "function !dbg attachment must be a subprogram", &F, I.second);
1830 // Verify the metadata itself.
1831 visitMDNode(*I.second);
1835 // If this function is actually an intrinsic, verify that it is only used in
1836 // direct call/invokes, never having its "address taken".
1837 // Only do this if the module is materialized, otherwise we don't have all the
1839 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
1841 if (F.hasAddressTaken(&U))
1842 Assert(0, "Invalid user of intrinsic instruction!", U);
1845 Assert(!F.hasDLLImportStorageClass() ||
1846 (F.isDeclaration() && F.hasExternalLinkage()) ||
1847 F.hasAvailableExternallyLinkage(),
1848 "Function is marked as dllimport, but not external.", &F);
1850 auto *N = F.getSubprogram();
1854 // Check that all !dbg attachments lead to back to N (or, at least, another
1855 // subprogram that describes the same function).
1857 // FIXME: Check this incrementally while visiting !dbg attachments.
1858 // FIXME: Only check when N is the canonical subprogram for F.
1859 SmallPtrSet<const MDNode *, 32> Seen;
1861 for (auto &I : BB) {
1862 // Be careful about using DILocation here since we might be dealing with
1863 // broken code (this is the Verifier after all).
1865 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1868 if (!Seen.insert(DL).second)
1871 DILocalScope *Scope = DL->getInlinedAtScope();
1872 if (Scope && !Seen.insert(Scope).second)
1875 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1877 // Scope and SP could be the same MDNode and we don't want to skip
1878 // validation in that case
1879 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
1882 // FIXME: Once N is canonical, check "SP == &N".
1883 Assert(SP->describes(&F),
1884 "!dbg attachment points at wrong subprogram for function", N, &F,
1889 // verifyBasicBlock - Verify that a basic block is well formed...
1891 void Verifier::visitBasicBlock(BasicBlock &BB) {
1892 InstsInThisBlock.clear();
1894 // Ensure that basic blocks have terminators!
1895 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1897 // Check constraints that this basic block imposes on all of the PHI nodes in
1899 if (isa<PHINode>(BB.front())) {
1900 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1901 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1902 std::sort(Preds.begin(), Preds.end());
1904 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1905 // Ensure that PHI nodes have at least one entry!
1906 Assert(PN->getNumIncomingValues() != 0,
1907 "PHI nodes must have at least one entry. If the block is dead, "
1908 "the PHI should be removed!",
1910 Assert(PN->getNumIncomingValues() == Preds.size(),
1911 "PHINode should have one entry for each predecessor of its "
1912 "parent basic block!",
1915 // Get and sort all incoming values in the PHI node...
1917 Values.reserve(PN->getNumIncomingValues());
1918 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1919 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1920 PN->getIncomingValue(i)));
1921 std::sort(Values.begin(), Values.end());
1923 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1924 // Check to make sure that if there is more than one entry for a
1925 // particular basic block in this PHI node, that the incoming values are
1928 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1929 Values[i].second == Values[i - 1].second,
1930 "PHI node has multiple entries for the same basic block with "
1931 "different incoming values!",
1932 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1934 // Check to make sure that the predecessors and PHI node entries are
1936 Assert(Values[i].first == Preds[i],
1937 "PHI node entries do not match predecessors!", PN,
1938 Values[i].first, Preds[i]);
1943 // Check that all instructions have their parent pointers set up correctly.
1946 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1950 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1951 // Ensure that terminators only exist at the end of the basic block.
1952 Assert(&I == I.getParent()->getTerminator(),
1953 "Terminator found in the middle of a basic block!", I.getParent());
1954 visitInstruction(I);
1957 void Verifier::visitBranchInst(BranchInst &BI) {
1958 if (BI.isConditional()) {
1959 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1960 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1962 visitTerminatorInst(BI);
1965 void Verifier::visitReturnInst(ReturnInst &RI) {
1966 Function *F = RI.getParent()->getParent();
1967 unsigned N = RI.getNumOperands();
1968 if (F->getReturnType()->isVoidTy())
1970 "Found return instr that returns non-void in Function of void "
1972 &RI, F->getReturnType());
1974 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1975 "Function return type does not match operand "
1976 "type of return inst!",
1977 &RI, F->getReturnType());
1979 // Check to make sure that the return value has necessary properties for
1981 visitTerminatorInst(RI);
1984 void Verifier::visitSwitchInst(SwitchInst &SI) {
1985 // Check to make sure that all of the constants in the switch instruction
1986 // have the same type as the switched-on value.
1987 Type *SwitchTy = SI.getCondition()->getType();
1988 SmallPtrSet<ConstantInt*, 32> Constants;
1989 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1990 Assert(i.getCaseValue()->getType() == SwitchTy,
1991 "Switch constants must all be same type as switch value!", &SI);
1992 Assert(Constants.insert(i.getCaseValue()).second,
1993 "Duplicate integer as switch case", &SI, i.getCaseValue());
1996 visitTerminatorInst(SI);
1999 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2000 Assert(BI.getAddress()->getType()->isPointerTy(),
2001 "Indirectbr operand must have pointer type!", &BI);
2002 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2003 Assert(BI.getDestination(i)->getType()->isLabelTy(),
2004 "Indirectbr destinations must all have pointer type!", &BI);
2006 visitTerminatorInst(BI);
2009 void Verifier::visitSelectInst(SelectInst &SI) {
2010 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2012 "Invalid operands for select instruction!", &SI);
2014 Assert(SI.getTrueValue()->getType() == SI.getType(),
2015 "Select values must have same type as select instruction!", &SI);
2016 visitInstruction(SI);
2019 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2020 /// a pass, if any exist, it's an error.
2022 void Verifier::visitUserOp1(Instruction &I) {
2023 Assert(0, "User-defined operators should not live outside of a pass!", &I);
2026 void Verifier::visitTruncInst(TruncInst &I) {
2027 // Get the source and destination types
2028 Type *SrcTy = I.getOperand(0)->getType();
2029 Type *DestTy = I.getType();
2031 // Get the size of the types in bits, we'll need this later
2032 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2033 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2035 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2036 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2037 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2038 "trunc source and destination must both be a vector or neither", &I);
2039 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2041 visitInstruction(I);
2044 void Verifier::visitZExtInst(ZExtInst &I) {
2045 // Get the source and destination types
2046 Type *SrcTy = I.getOperand(0)->getType();
2047 Type *DestTy = I.getType();
2049 // Get the size of the types in bits, we'll need this later
2050 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2051 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2052 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2053 "zext source and destination must both be a vector or neither", &I);
2054 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2055 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2057 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2059 visitInstruction(I);
2062 void Verifier::visitSExtInst(SExtInst &I) {
2063 // Get the source and destination types
2064 Type *SrcTy = I.getOperand(0)->getType();
2065 Type *DestTy = I.getType();
2067 // Get the size of the types in bits, we'll need this later
2068 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2069 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2071 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2072 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2073 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2074 "sext source and destination must both be a vector or neither", &I);
2075 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2077 visitInstruction(I);
2080 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2081 // Get the source and destination types
2082 Type *SrcTy = I.getOperand(0)->getType();
2083 Type *DestTy = I.getType();
2084 // Get the size of the types in bits, we'll need this later
2085 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2086 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2088 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2089 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2090 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2091 "fptrunc source and destination must both be a vector or neither", &I);
2092 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2094 visitInstruction(I);
2097 void Verifier::visitFPExtInst(FPExtInst &I) {
2098 // Get the source and destination types
2099 Type *SrcTy = I.getOperand(0)->getType();
2100 Type *DestTy = I.getType();
2102 // Get the size of the types in bits, we'll need this later
2103 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2104 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2106 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2107 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2108 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2109 "fpext source and destination must both be a vector or neither", &I);
2110 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2112 visitInstruction(I);
2115 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2116 // Get the source and destination types
2117 Type *SrcTy = I.getOperand(0)->getType();
2118 Type *DestTy = I.getType();
2120 bool SrcVec = SrcTy->isVectorTy();
2121 bool DstVec = DestTy->isVectorTy();
2123 Assert(SrcVec == DstVec,
2124 "UIToFP source and dest must both be vector or scalar", &I);
2125 Assert(SrcTy->isIntOrIntVectorTy(),
2126 "UIToFP source must be integer or integer vector", &I);
2127 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2130 if (SrcVec && DstVec)
2131 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2132 cast<VectorType>(DestTy)->getNumElements(),
2133 "UIToFP source and dest vector length mismatch", &I);
2135 visitInstruction(I);
2138 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2139 // Get the source and destination types
2140 Type *SrcTy = I.getOperand(0)->getType();
2141 Type *DestTy = I.getType();
2143 bool SrcVec = SrcTy->isVectorTy();
2144 bool DstVec = DestTy->isVectorTy();
2146 Assert(SrcVec == DstVec,
2147 "SIToFP source and dest must both be vector or scalar", &I);
2148 Assert(SrcTy->isIntOrIntVectorTy(),
2149 "SIToFP source must be integer or integer vector", &I);
2150 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2153 if (SrcVec && DstVec)
2154 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2155 cast<VectorType>(DestTy)->getNumElements(),
2156 "SIToFP source and dest vector length mismatch", &I);
2158 visitInstruction(I);
2161 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2162 // Get the source and destination types
2163 Type *SrcTy = I.getOperand(0)->getType();
2164 Type *DestTy = I.getType();
2166 bool SrcVec = SrcTy->isVectorTy();
2167 bool DstVec = DestTy->isVectorTy();
2169 Assert(SrcVec == DstVec,
2170 "FPToUI source and dest must both be vector or scalar", &I);
2171 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2173 Assert(DestTy->isIntOrIntVectorTy(),
2174 "FPToUI result must be integer or integer vector", &I);
2176 if (SrcVec && DstVec)
2177 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2178 cast<VectorType>(DestTy)->getNumElements(),
2179 "FPToUI source and dest vector length mismatch", &I);
2181 visitInstruction(I);
2184 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2185 // Get the source and destination types
2186 Type *SrcTy = I.getOperand(0)->getType();
2187 Type *DestTy = I.getType();
2189 bool SrcVec = SrcTy->isVectorTy();
2190 bool DstVec = DestTy->isVectorTy();
2192 Assert(SrcVec == DstVec,
2193 "FPToSI source and dest must both be vector or scalar", &I);
2194 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2196 Assert(DestTy->isIntOrIntVectorTy(),
2197 "FPToSI result must be integer or integer vector", &I);
2199 if (SrcVec && DstVec)
2200 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2201 cast<VectorType>(DestTy)->getNumElements(),
2202 "FPToSI source and dest vector length mismatch", &I);
2204 visitInstruction(I);
2207 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2208 // Get the source and destination types
2209 Type *SrcTy = I.getOperand(0)->getType();
2210 Type *DestTy = I.getType();
2212 Assert(SrcTy->getScalarType()->isPointerTy(),
2213 "PtrToInt source must be pointer", &I);
2214 Assert(DestTy->getScalarType()->isIntegerTy(),
2215 "PtrToInt result must be integral", &I);
2216 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2219 if (SrcTy->isVectorTy()) {
2220 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2221 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2222 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2223 "PtrToInt Vector width mismatch", &I);
2226 visitInstruction(I);
2229 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2230 // Get the source and destination types
2231 Type *SrcTy = I.getOperand(0)->getType();
2232 Type *DestTy = I.getType();
2234 Assert(SrcTy->getScalarType()->isIntegerTy(),
2235 "IntToPtr source must be an integral", &I);
2236 Assert(DestTy->getScalarType()->isPointerTy(),
2237 "IntToPtr result must be a pointer", &I);
2238 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2240 if (SrcTy->isVectorTy()) {
2241 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2242 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2243 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2244 "IntToPtr Vector width mismatch", &I);
2246 visitInstruction(I);
2249 void Verifier::visitBitCastInst(BitCastInst &I) {
2251 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2252 "Invalid bitcast", &I);
2253 visitInstruction(I);
2256 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2257 Type *SrcTy = I.getOperand(0)->getType();
2258 Type *DestTy = I.getType();
2260 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2262 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2264 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2265 "AddrSpaceCast must be between different address spaces", &I);
2266 if (SrcTy->isVectorTy())
2267 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2268 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2269 visitInstruction(I);
2272 /// visitPHINode - Ensure that a PHI node is well formed.
2274 void Verifier::visitPHINode(PHINode &PN) {
2275 // Ensure that the PHI nodes are all grouped together at the top of the block.
2276 // This can be tested by checking whether the instruction before this is
2277 // either nonexistent (because this is begin()) or is a PHI node. If not,
2278 // then there is some other instruction before a PHI.
2279 Assert(&PN == &PN.getParent()->front() ||
2280 isa<PHINode>(--BasicBlock::iterator(&PN)),
2281 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2283 // Check that a PHI doesn't yield a Token.
2284 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2286 // Check that all of the values of the PHI node have the same type as the
2287 // result, and that the incoming blocks are really basic blocks.
2288 for (Value *IncValue : PN.incoming_values()) {
2289 Assert(PN.getType() == IncValue->getType(),
2290 "PHI node operands are not the same type as the result!", &PN);
2293 // All other PHI node constraints are checked in the visitBasicBlock method.
2295 visitInstruction(PN);
2298 void Verifier::VerifyCallSite(CallSite CS) {
2299 Instruction *I = CS.getInstruction();
2301 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2302 "Called function must be a pointer!", I);
2303 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2305 Assert(FPTy->getElementType()->isFunctionTy(),
2306 "Called function is not pointer to function type!", I);
2308 Assert(FPTy->getElementType() == CS.getFunctionType(),
2309 "Called function is not the same type as the call!", I);
2311 FunctionType *FTy = CS.getFunctionType();
2313 // Verify that the correct number of arguments are being passed
2314 if (FTy->isVarArg())
2315 Assert(CS.arg_size() >= FTy->getNumParams(),
2316 "Called function requires more parameters than were provided!", I);
2318 Assert(CS.arg_size() == FTy->getNumParams(),
2319 "Incorrect number of arguments passed to called function!", I);
2321 // Verify that all arguments to the call match the function type.
2322 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2323 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2324 "Call parameter type does not match function signature!",
2325 CS.getArgument(i), FTy->getParamType(i), I);
2327 AttributeSet Attrs = CS.getAttributes();
2329 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2330 "Attribute after last parameter!", I);
2332 // Verify call attributes.
2333 VerifyFunctionAttrs(FTy, Attrs, I);
2335 // Conservatively check the inalloca argument.
2336 // We have a bug if we can find that there is an underlying alloca without
2338 if (CS.hasInAllocaArgument()) {
2339 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2340 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2341 Assert(AI->isUsedWithInAlloca(),
2342 "inalloca argument for call has mismatched alloca", AI, I);
2345 if (FTy->isVarArg()) {
2346 // FIXME? is 'nest' even legal here?
2347 bool SawNest = false;
2348 bool SawReturned = false;
2350 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2351 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2353 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2357 // Check attributes on the varargs part.
2358 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2359 Type *Ty = CS.getArgument(Idx-1)->getType();
2360 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2362 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2363 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2367 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2368 Assert(!SawReturned, "More than one parameter has attribute returned!",
2370 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2371 "Incompatible argument and return types for 'returned' "
2377 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2378 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2380 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2381 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2385 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2386 if (CS.getCalledFunction() == nullptr ||
2387 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2388 for (Type *ParamTy : FTy->params()) {
2389 Assert(!ParamTy->isMetadataTy(),
2390 "Function has metadata parameter but isn't an intrinsic", I);
2391 Assert(!ParamTy->isTokenTy(),
2392 "Function has token parameter but isn't an intrinsic", I);
2396 // Verify that indirect calls don't return tokens.
2397 if (CS.getCalledFunction() == nullptr)
2398 Assert(!FTy->getReturnType()->isTokenTy(),
2399 "Return type cannot be token for indirect call!");
2401 if (Function *F = CS.getCalledFunction())
2402 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2403 visitIntrinsicCallSite(ID, CS);
2405 // Verify that a callsite has at most one "deopt" and one "funclet" operand
2407 bool FoundDeoptBundle = false, FoundFuncletBundle = false;
2408 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2409 OperandBundleUse BU = CS.getOperandBundleAt(i);
2410 uint32_t Tag = BU.getTagID();
2411 if (Tag == LLVMContext::OB_deopt) {
2412 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2413 FoundDeoptBundle = true;
2415 if (Tag == LLVMContext::OB_funclet) {
2416 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2417 FoundFuncletBundle = true;
2418 Assert(BU.Inputs.size() == 1,
2419 "Expected exactly one funclet bundle operand", I);
2420 Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2421 "Funclet bundle operands should correspond to a FuncletPadInst",
2426 visitInstruction(*I);
2429 /// Two types are "congruent" if they are identical, or if they are both pointer
2430 /// types with different pointee types and the same address space.
2431 static bool isTypeCongruent(Type *L, Type *R) {
2434 PointerType *PL = dyn_cast<PointerType>(L);
2435 PointerType *PR = dyn_cast<PointerType>(R);
2438 return PL->getAddressSpace() == PR->getAddressSpace();
2441 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2442 static const Attribute::AttrKind ABIAttrs[] = {
2443 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2444 Attribute::InReg, Attribute::Returned};
2446 for (auto AK : ABIAttrs) {
2447 if (Attrs.hasAttribute(I + 1, AK))
2448 Copy.addAttribute(AK);
2450 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2451 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2455 void Verifier::verifyMustTailCall(CallInst &CI) {
2456 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2458 // - The caller and callee prototypes must match. Pointer types of
2459 // parameters or return types may differ in pointee type, but not
2461 Function *F = CI.getParent()->getParent();
2462 FunctionType *CallerTy = F->getFunctionType();
2463 FunctionType *CalleeTy = CI.getFunctionType();
2464 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2465 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2466 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2467 "cannot guarantee tail call due to mismatched varargs", &CI);
2468 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2469 "cannot guarantee tail call due to mismatched return types", &CI);
2470 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2472 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2473 "cannot guarantee tail call due to mismatched parameter types", &CI);
2476 // - The calling conventions of the caller and callee must match.
2477 Assert(F->getCallingConv() == CI.getCallingConv(),
2478 "cannot guarantee tail call due to mismatched calling conv", &CI);
2480 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2481 // returned, and inalloca, must match.
2482 AttributeSet CallerAttrs = F->getAttributes();
2483 AttributeSet CalleeAttrs = CI.getAttributes();
2484 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2485 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2486 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2487 Assert(CallerABIAttrs == CalleeABIAttrs,
2488 "cannot guarantee tail call due to mismatched ABI impacting "
2489 "function attributes",
2490 &CI, CI.getOperand(I));
2493 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2494 // or a pointer bitcast followed by a ret instruction.
2495 // - The ret instruction must return the (possibly bitcasted) value
2496 // produced by the call or void.
2497 Value *RetVal = &CI;
2498 Instruction *Next = CI.getNextNode();
2500 // Handle the optional bitcast.
2501 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2502 Assert(BI->getOperand(0) == RetVal,
2503 "bitcast following musttail call must use the call", BI);
2505 Next = BI->getNextNode();
2508 // Check the return.
2509 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2510 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2512 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2513 "musttail call result must be returned", Ret);
2516 void Verifier::visitCallInst(CallInst &CI) {
2517 VerifyCallSite(&CI);
2519 if (CI.isMustTailCall())
2520 verifyMustTailCall(CI);
2523 void Verifier::visitInvokeInst(InvokeInst &II) {
2524 VerifyCallSite(&II);
2526 // Verify that the first non-PHI instruction of the unwind destination is an
2527 // exception handling instruction.
2529 II.getUnwindDest()->isEHPad(),
2530 "The unwind destination does not have an exception handling instruction!",
2533 visitTerminatorInst(II);
2536 /// visitBinaryOperator - Check that both arguments to the binary operator are
2537 /// of the same type!
2539 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2540 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2541 "Both operands to a binary operator are not of the same type!", &B);
2543 switch (B.getOpcode()) {
2544 // Check that integer arithmetic operators are only used with
2545 // integral operands.
2546 case Instruction::Add:
2547 case Instruction::Sub:
2548 case Instruction::Mul:
2549 case Instruction::SDiv:
2550 case Instruction::UDiv:
2551 case Instruction::SRem:
2552 case Instruction::URem:
2553 Assert(B.getType()->isIntOrIntVectorTy(),
2554 "Integer arithmetic operators only work with integral types!", &B);
2555 Assert(B.getType() == B.getOperand(0)->getType(),
2556 "Integer arithmetic operators must have same type "
2557 "for operands and result!",
2560 // Check that floating-point arithmetic operators are only used with
2561 // floating-point operands.
2562 case Instruction::FAdd:
2563 case Instruction::FSub:
2564 case Instruction::FMul:
2565 case Instruction::FDiv:
2566 case Instruction::FRem:
2567 Assert(B.getType()->isFPOrFPVectorTy(),
2568 "Floating-point arithmetic operators only work with "
2569 "floating-point types!",
2571 Assert(B.getType() == B.getOperand(0)->getType(),
2572 "Floating-point arithmetic operators must have same type "
2573 "for operands and result!",
2576 // Check that logical operators are only used with integral operands.
2577 case Instruction::And:
2578 case Instruction::Or:
2579 case Instruction::Xor:
2580 Assert(B.getType()->isIntOrIntVectorTy(),
2581 "Logical operators only work with integral types!", &B);
2582 Assert(B.getType() == B.getOperand(0)->getType(),
2583 "Logical operators must have same type for operands and result!",
2586 case Instruction::Shl:
2587 case Instruction::LShr:
2588 case Instruction::AShr:
2589 Assert(B.getType()->isIntOrIntVectorTy(),
2590 "Shifts only work with integral types!", &B);
2591 Assert(B.getType() == B.getOperand(0)->getType(),
2592 "Shift return type must be same as operands!", &B);
2595 llvm_unreachable("Unknown BinaryOperator opcode!");
2598 visitInstruction(B);
2601 void Verifier::visitICmpInst(ICmpInst &IC) {
2602 // Check that the operands are the same type
2603 Type *Op0Ty = IC.getOperand(0)->getType();
2604 Type *Op1Ty = IC.getOperand(1)->getType();
2605 Assert(Op0Ty == Op1Ty,
2606 "Both operands to ICmp instruction are not of the same type!", &IC);
2607 // Check that the operands are the right type
2608 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2609 "Invalid operand types for ICmp instruction", &IC);
2610 // Check that the predicate is valid.
2611 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2612 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2613 "Invalid predicate in ICmp instruction!", &IC);
2615 visitInstruction(IC);
2618 void Verifier::visitFCmpInst(FCmpInst &FC) {
2619 // Check that the operands are the same type
2620 Type *Op0Ty = FC.getOperand(0)->getType();
2621 Type *Op1Ty = FC.getOperand(1)->getType();
2622 Assert(Op0Ty == Op1Ty,
2623 "Both operands to FCmp instruction are not of the same type!", &FC);
2624 // Check that the operands are the right type
2625 Assert(Op0Ty->isFPOrFPVectorTy(),
2626 "Invalid operand types for FCmp instruction", &FC);
2627 // Check that the predicate is valid.
2628 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2629 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2630 "Invalid predicate in FCmp instruction!", &FC);
2632 visitInstruction(FC);
2635 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2637 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2638 "Invalid extractelement operands!", &EI);
2639 visitInstruction(EI);
2642 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2643 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2645 "Invalid insertelement operands!", &IE);
2646 visitInstruction(IE);
2649 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2650 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2652 "Invalid shufflevector operands!", &SV);
2653 visitInstruction(SV);
2656 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2657 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2659 Assert(isa<PointerType>(TargetTy),
2660 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2661 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2662 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2664 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2665 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2667 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2668 GEP.getResultElementType() == ElTy,
2669 "GEP is not of right type for indices!", &GEP, ElTy);
2671 if (GEP.getType()->isVectorTy()) {
2672 // Additional checks for vector GEPs.
2673 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2674 if (GEP.getPointerOperandType()->isVectorTy())
2675 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2676 "Vector GEP result width doesn't match operand's", &GEP);
2677 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2678 Type *IndexTy = Idxs[i]->getType();
2679 if (IndexTy->isVectorTy()) {
2680 unsigned IndexWidth = IndexTy->getVectorNumElements();
2681 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2683 Assert(IndexTy->getScalarType()->isIntegerTy(),
2684 "All GEP indices should be of integer type");
2687 visitInstruction(GEP);
2690 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2691 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2694 void Verifier::visitRangeMetadata(Instruction& I,
2695 MDNode* Range, Type* Ty) {
2697 Range == I.getMetadata(LLVMContext::MD_range) &&
2698 "precondition violation");
2700 unsigned NumOperands = Range->getNumOperands();
2701 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2702 unsigned NumRanges = NumOperands / 2;
2703 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2705 ConstantRange LastRange(1); // Dummy initial value
2706 for (unsigned i = 0; i < NumRanges; ++i) {
2708 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2709 Assert(Low, "The lower limit must be an integer!", Low);
2711 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2712 Assert(High, "The upper limit must be an integer!", High);
2713 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2714 "Range types must match instruction type!", &I);
2716 APInt HighV = High->getValue();
2717 APInt LowV = Low->getValue();
2718 ConstantRange CurRange(LowV, HighV);
2719 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2720 "Range must not be empty!", Range);
2722 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2723 "Intervals are overlapping", Range);
2724 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2726 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2729 LastRange = ConstantRange(LowV, HighV);
2731 if (NumRanges > 2) {
2733 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2735 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2736 ConstantRange FirstRange(FirstLow, FirstHigh);
2737 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2738 "Intervals are overlapping", Range);
2739 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2744 void Verifier::checkAtomicMemAccessSize(const Module *M, Type *Ty,
2745 const Instruction *I) {
2746 unsigned Size = M->getDataLayout().getTypeSizeInBits(Ty);
2747 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
2748 Assert(!(Size & (Size - 1)),
2749 "atomic memory access' operand must have a power-of-two size", Ty, I);
2752 void Verifier::visitLoadInst(LoadInst &LI) {
2753 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2754 Assert(PTy, "Load operand must be a pointer.", &LI);
2755 Type *ElTy = LI.getType();
2756 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2757 "huge alignment values are unsupported", &LI);
2758 if (LI.isAtomic()) {
2759 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2760 "Load cannot have Release ordering", &LI);
2761 Assert(LI.getAlignment() != 0,
2762 "Atomic load must specify explicit alignment", &LI);
2763 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2764 ElTy->isFloatingPointTy(),
2765 "atomic load operand must have integer, pointer, or floating point "
2768 checkAtomicMemAccessSize(M, ElTy, &LI);
2770 Assert(LI.getSynchScope() == CrossThread,
2771 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2774 visitInstruction(LI);
2777 void Verifier::visitStoreInst(StoreInst &SI) {
2778 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2779 Assert(PTy, "Store operand must be a pointer.", &SI);
2780 Type *ElTy = PTy->getElementType();
2781 Assert(ElTy == SI.getOperand(0)->getType(),
2782 "Stored value type does not match pointer operand type!", &SI, ElTy);
2783 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2784 "huge alignment values are unsupported", &SI);
2785 if (SI.isAtomic()) {
2786 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2787 "Store cannot have Acquire ordering", &SI);
2788 Assert(SI.getAlignment() != 0,
2789 "Atomic store must specify explicit alignment", &SI);
2790 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2791 ElTy->isFloatingPointTy(),
2792 "atomic store operand must have integer, pointer, or floating point "
2795 checkAtomicMemAccessSize(M, ElTy, &SI);
2797 Assert(SI.getSynchScope() == CrossThread,
2798 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2800 visitInstruction(SI);
2803 void Verifier::visitAllocaInst(AllocaInst &AI) {
2804 SmallPtrSet<Type*, 4> Visited;
2805 PointerType *PTy = AI.getType();
2806 Assert(PTy->getAddressSpace() == 0,
2807 "Allocation instruction pointer not in the generic address space!",
2809 Assert(AI.getAllocatedType()->isSized(&Visited),
2810 "Cannot allocate unsized type", &AI);
2811 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2812 "Alloca array size must have integer type", &AI);
2813 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2814 "huge alignment values are unsupported", &AI);
2816 visitInstruction(AI);
2819 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2821 // FIXME: more conditions???
2822 Assert(CXI.getSuccessOrdering() != NotAtomic,
2823 "cmpxchg instructions must be atomic.", &CXI);
2824 Assert(CXI.getFailureOrdering() != NotAtomic,
2825 "cmpxchg instructions must be atomic.", &CXI);
2826 Assert(CXI.getSuccessOrdering() != Unordered,
2827 "cmpxchg instructions cannot be unordered.", &CXI);
2828 Assert(CXI.getFailureOrdering() != Unordered,
2829 "cmpxchg instructions cannot be unordered.", &CXI);
2830 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2831 "cmpxchg instructions be at least as constrained on success as fail",
2833 Assert(CXI.getFailureOrdering() != Release &&
2834 CXI.getFailureOrdering() != AcquireRelease,
2835 "cmpxchg failure ordering cannot include release semantics", &CXI);
2837 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2838 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2839 Type *ElTy = PTy->getElementType();
2840 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2842 checkAtomicMemAccessSize(M, ElTy, &CXI);
2843 Assert(ElTy == CXI.getOperand(1)->getType(),
2844 "Expected value type does not match pointer operand type!", &CXI,
2846 Assert(ElTy == CXI.getOperand(2)->getType(),
2847 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2848 visitInstruction(CXI);
2851 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2852 Assert(RMWI.getOrdering() != NotAtomic,
2853 "atomicrmw instructions must be atomic.", &RMWI);
2854 Assert(RMWI.getOrdering() != Unordered,
2855 "atomicrmw instructions cannot be unordered.", &RMWI);
2856 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2857 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2858 Type *ElTy = PTy->getElementType();
2859 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2861 checkAtomicMemAccessSize(M, ElTy, &RMWI);
2862 Assert(ElTy == RMWI.getOperand(1)->getType(),
2863 "Argument value type does not match pointer operand type!", &RMWI,
2865 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2866 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2867 "Invalid binary operation!", &RMWI);
2868 visitInstruction(RMWI);
2871 void Verifier::visitFenceInst(FenceInst &FI) {
2872 const AtomicOrdering Ordering = FI.getOrdering();
2873 Assert(Ordering == Acquire || Ordering == Release ||
2874 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2875 "fence instructions may only have "
2876 "acquire, release, acq_rel, or seq_cst ordering.",
2878 visitInstruction(FI);
2881 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2882 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2883 EVI.getIndices()) == EVI.getType(),
2884 "Invalid ExtractValueInst operands!", &EVI);
2886 visitInstruction(EVI);
2889 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2890 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2891 IVI.getIndices()) ==
2892 IVI.getOperand(1)->getType(),
2893 "Invalid InsertValueInst operands!", &IVI);
2895 visitInstruction(IVI);
2898 static Value *getParentPad(Value *EHPad) {
2899 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
2900 return FPI->getParentPad();
2902 return cast<CatchSwitchInst>(EHPad)->getParentPad();
2905 void Verifier::visitEHPadPredecessors(Instruction &I) {
2906 assert(I.isEHPad());
2908 BasicBlock *BB = I.getParent();
2909 Function *F = BB->getParent();
2911 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2913 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2914 // The landingpad instruction defines its parent as a landing pad block. The
2915 // landing pad block may be branched to only by the unwind edge of an
2917 for (BasicBlock *PredBB : predecessors(BB)) {
2918 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2919 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2920 "Block containing LandingPadInst must be jumped to "
2921 "only by the unwind edge of an invoke.",
2926 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2927 if (!pred_empty(BB))
2928 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
2929 "Block containg CatchPadInst must be jumped to "
2930 "only by its catchswitch.",
2935 // Verify that each pred has a legal terminator with a legal to/from EH
2936 // pad relationship.
2937 Instruction *ToPad = &I;
2938 Value *ToPadParent = getParentPad(ToPad);
2939 for (BasicBlock *PredBB : predecessors(BB)) {
2940 TerminatorInst *TI = PredBB->getTerminator();
2942 if (auto *II = dyn_cast<InvokeInst>(TI)) {
2943 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
2944 "EH pad must be jumped to via an unwind edge", ToPad, II);
2945 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
2946 FromPad = Bundle->Inputs[0];
2948 FromPad = ConstantTokenNone::get(II->getContext());
2949 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2950 FromPad = CRI->getCleanupPad();
2951 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
2952 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
2955 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
2958 // The edge may exit from zero or more nested pads.
2959 for (;; FromPad = getParentPad(FromPad)) {
2960 Assert(FromPad != ToPad,
2961 "EH pad cannot handle exceptions raised within it", FromPad, TI);
2962 if (FromPad == ToPadParent) {
2963 // This is a legal unwind edge.
2966 Assert(!isa<ConstantTokenNone>(FromPad),
2967 "A single unwind edge may only enter one EH pad", TI);
2972 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2973 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2975 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2976 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2978 visitEHPadPredecessors(LPI);
2980 if (!LandingPadResultTy)
2981 LandingPadResultTy = LPI.getType();
2983 Assert(LandingPadResultTy == LPI.getType(),
2984 "The landingpad instruction should have a consistent result type "
2985 "inside a function.",
2988 Function *F = LPI.getParent()->getParent();
2989 Assert(F->hasPersonalityFn(),
2990 "LandingPadInst needs to be in a function with a personality.", &LPI);
2992 // The landingpad instruction must be the first non-PHI instruction in the
2994 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2995 "LandingPadInst not the first non-PHI instruction in the block.",
2998 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2999 Constant *Clause = LPI.getClause(i);
3000 if (LPI.isCatch(i)) {
3001 Assert(isa<PointerType>(Clause->getType()),
3002 "Catch operand does not have pointer type!", &LPI);
3004 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3005 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3006 "Filter operand is not an array of constants!", &LPI);
3010 visitInstruction(LPI);
3013 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
3014 visitEHPadPredecessors(CPI);
3016 BasicBlock *BB = CPI.getParent();
3018 Function *F = BB->getParent();
3019 Assert(F->hasPersonalityFn(),
3020 "CatchPadInst needs to be in a function with a personality.", &CPI);
3022 Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3023 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3024 CPI.getParentPad());
3026 // The catchpad instruction must be the first non-PHI instruction in the
3028 Assert(BB->getFirstNonPHI() == &CPI,
3029 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
3031 visitInstruction(CPI);
3034 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3035 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3036 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3037 CatchReturn.getOperand(0));
3039 visitTerminatorInst(CatchReturn);
3042 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3043 visitEHPadPredecessors(CPI);
3045 BasicBlock *BB = CPI.getParent();
3047 Function *F = BB->getParent();
3048 Assert(F->hasPersonalityFn(),
3049 "CleanupPadInst needs to be in a function with a personality.", &CPI);
3051 // The cleanuppad instruction must be the first non-PHI instruction in the
3053 Assert(BB->getFirstNonPHI() == &CPI,
3054 "CleanupPadInst not the first non-PHI instruction in the block.",
3057 auto *ParentPad = CPI.getParentPad();
3058 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3059 "CleanupPadInst has an invalid parent.", &CPI);
3061 User *FirstUser = nullptr;
3062 BasicBlock *FirstUnwindDest = nullptr;
3063 for (User *U : CPI.users()) {
3064 BasicBlock *UnwindDest;
3065 if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(U)) {
3066 UnwindDest = CRI->getUnwindDest();
3067 } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) {
3069 } else if (CallSite(U)) {
3072 Assert(false, "bogus cleanuppad use", &CPI);
3077 FirstUnwindDest = UnwindDest;
3080 UnwindDest == FirstUnwindDest,
3081 "cleanupret instructions from the same cleanuppad must have the same "
3082 "unwind destination",
3087 visitInstruction(CPI);
3090 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
3091 visitEHPadPredecessors(CatchSwitch);
3093 BasicBlock *BB = CatchSwitch.getParent();
3095 Function *F = BB->getParent();
3096 Assert(F->hasPersonalityFn(),
3097 "CatchSwitchInst needs to be in a function with a personality.",
3100 // The catchswitch instruction must be the first non-PHI instruction in the
3102 Assert(BB->getFirstNonPHI() == &CatchSwitch,
3103 "CatchSwitchInst not the first non-PHI instruction in the block.",
3106 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
3107 Instruction *I = UnwindDest->getFirstNonPHI();
3108 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3109 "CatchSwitchInst must unwind to an EH block which is not a "
3114 auto *ParentPad = CatchSwitch.getParentPad();
3115 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3116 "CatchSwitchInst has an invalid parent.", ParentPad);
3118 Assert(CatchSwitch.getNumHandlers() != 0,
3119 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3121 for (BasicBlock *Handler : CatchSwitch.handlers()) {
3122 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3123 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
3126 visitTerminatorInst(CatchSwitch);
3129 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3130 Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3131 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3134 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3135 Instruction *I = UnwindDest->getFirstNonPHI();
3136 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3137 "CleanupReturnInst must unwind to an EH block which is not a "
3142 visitTerminatorInst(CRI);
3145 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3146 Instruction *Op = cast<Instruction>(I.getOperand(i));
3147 // If the we have an invalid invoke, don't try to compute the dominance.
3148 // We already reject it in the invoke specific checks and the dominance
3149 // computation doesn't handle multiple edges.
3150 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3151 if (II->getNormalDest() == II->getUnwindDest())
3155 const Use &U = I.getOperandUse(i);
3156 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3157 "Instruction does not dominate all uses!", Op, &I);
3160 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3161 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3162 "apply only to pointer types", &I);
3163 Assert(isa<LoadInst>(I),
3164 "dereferenceable, dereferenceable_or_null apply only to load"
3165 " instructions, use attributes for calls or invokes", &I);
3166 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3167 "take one operand!", &I);
3168 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3169 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3170 "dereferenceable_or_null metadata value must be an i64!", &I);
3173 /// verifyInstruction - Verify that an instruction is well formed.
3175 void Verifier::visitInstruction(Instruction &I) {
3176 BasicBlock *BB = I.getParent();
3177 Assert(BB, "Instruction not embedded in basic block!", &I);
3179 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
3180 for (User *U : I.users()) {
3181 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3182 "Only PHI nodes may reference their own value!", &I);
3186 // Check that void typed values don't have names
3187 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3188 "Instruction has a name, but provides a void value!", &I);
3190 // Check that the return value of the instruction is either void or a legal
3192 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3193 "Instruction returns a non-scalar type!", &I);
3195 // Check that the instruction doesn't produce metadata. Calls are already
3196 // checked against the callee type.
3197 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3198 "Invalid use of metadata!", &I);
3200 // Check that all uses of the instruction, if they are instructions
3201 // themselves, actually have parent basic blocks. If the use is not an
3202 // instruction, it is an error!
3203 for (Use &U : I.uses()) {
3204 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3205 Assert(Used->getParent() != nullptr,
3206 "Instruction referencing"
3207 " instruction not embedded in a basic block!",
3210 CheckFailed("Use of instruction is not an instruction!", U);
3215 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3216 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3218 // Check to make sure that only first-class-values are operands to
3220 if (!I.getOperand(i)->getType()->isFirstClassType()) {
3221 Assert(0, "Instruction operands must be first-class values!", &I);
3224 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3225 // Check to make sure that the "address of" an intrinsic function is never
3228 !F->isIntrinsic() ||
3229 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3230 "Cannot take the address of an intrinsic!", &I);
3232 !F->isIntrinsic() || isa<CallInst>(I) ||
3233 F->getIntrinsicID() == Intrinsic::donothing ||
3234 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3235 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3236 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3237 "Cannot invoke an intrinsinc other than"
3238 " donothing or patchpoint",
3240 Assert(F->getParent() == M, "Referencing function in another module!",
3241 &I, M, F, F->getParent());
3242 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3243 Assert(OpBB->getParent() == BB->getParent(),
3244 "Referring to a basic block in another function!", &I);
3245 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3246 Assert(OpArg->getParent() == BB->getParent(),
3247 "Referring to an argument in another function!", &I);
3248 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3249 Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent());
3250 } else if (isa<Instruction>(I.getOperand(i))) {
3251 verifyDominatesUse(I, i);
3252 } else if (isa<InlineAsm>(I.getOperand(i))) {
3253 Assert((i + 1 == e && isa<CallInst>(I)) ||
3254 (i + 3 == e && isa<InvokeInst>(I)),
3255 "Cannot take the address of an inline asm!", &I);
3256 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3257 if (CE->getType()->isPtrOrPtrVectorTy()) {
3258 // If we have a ConstantExpr pointer, we need to see if it came from an
3259 // illegal bitcast (inttoptr <constant int> )
3260 visitConstantExprsRecursively(CE);
3265 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3266 Assert(I.getType()->isFPOrFPVectorTy(),
3267 "fpmath requires a floating point result!", &I);
3268 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3269 if (ConstantFP *CFP0 =
3270 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3271 APFloat Accuracy = CFP0->getValueAPF();
3272 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3273 "fpmath accuracy not a positive number!", &I);
3275 Assert(false, "invalid fpmath accuracy!", &I);
3279 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3280 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3281 "Ranges are only for loads, calls and invokes!", &I);
3282 visitRangeMetadata(I, Range, I.getType());
3285 if (I.getMetadata(LLVMContext::MD_nonnull)) {
3286 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3288 Assert(isa<LoadInst>(I),
3289 "nonnull applies only to load instructions, use attributes"
3290 " for calls or invokes",
3294 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3295 visitDereferenceableMetadata(I, MD);
3297 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3298 visitDereferenceableMetadata(I, MD);
3300 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3301 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3303 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3304 "use attributes for calls or invokes", &I);
3305 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3306 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3307 Assert(CI && CI->getType()->isIntegerTy(64),
3308 "align metadata value must be an i64!", &I);
3309 uint64_t Align = CI->getZExtValue();
3310 Assert(isPowerOf2_64(Align),
3311 "align metadata value must be a power of 2!", &I);
3312 Assert(Align <= Value::MaximumAlignment,
3313 "alignment is larger that implementation defined limit", &I);
3316 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3317 Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3321 InstsInThisBlock.insert(&I);
3324 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3325 /// intrinsic argument or return value) matches the type constraints specified
3326 /// by the .td file (e.g. an "any integer" argument really is an integer).
3328 /// This return true on error but does not print a message.
3329 bool Verifier::VerifyIntrinsicType(Type *Ty,
3330 ArrayRef<Intrinsic::IITDescriptor> &Infos,
3331 SmallVectorImpl<Type*> &ArgTys) {
3332 using namespace Intrinsic;
3334 // If we ran out of descriptors, there are too many arguments.
3335 if (Infos.empty()) return true;
3336 IITDescriptor D = Infos.front();
3337 Infos = Infos.slice(1);
3340 case IITDescriptor::Void: return !Ty->isVoidTy();
3341 case IITDescriptor::VarArg: return true;
3342 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
3343 case IITDescriptor::Token: return !Ty->isTokenTy();
3344 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3345 case IITDescriptor::Half: return !Ty->isHalfTy();
3346 case IITDescriptor::Float: return !Ty->isFloatTy();
3347 case IITDescriptor::Double: return !Ty->isDoubleTy();
3348 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3349 case IITDescriptor::Vector: {
3350 VectorType *VT = dyn_cast<VectorType>(Ty);
3351 return !VT || VT->getNumElements() != D.Vector_Width ||
3352 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3354 case IITDescriptor::Pointer: {
3355 PointerType *PT = dyn_cast<PointerType>(Ty);
3356 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3357 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3360 case IITDescriptor::Struct: {
3361 StructType *ST = dyn_cast<StructType>(Ty);
3362 if (!ST || ST->getNumElements() != D.Struct_NumElements)
3365 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3366 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3371 case IITDescriptor::Argument:
3372 // Two cases here - If this is the second occurrence of an argument, verify
3373 // that the later instance matches the previous instance.
3374 if (D.getArgumentNumber() < ArgTys.size())
3375 return Ty != ArgTys[D.getArgumentNumber()];
3377 // Otherwise, if this is the first instance of an argument, record it and
3378 // verify the "Any" kind.
3379 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3380 ArgTys.push_back(Ty);
3382 switch (D.getArgumentKind()) {
3383 case IITDescriptor::AK_Any: return false; // Success
3384 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3385 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
3386 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
3387 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3389 llvm_unreachable("all argument kinds not covered");
3391 case IITDescriptor::ExtendArgument: {
3392 // This may only be used when referring to a previous vector argument.
3393 if (D.getArgumentNumber() >= ArgTys.size())
3396 Type *NewTy = ArgTys[D.getArgumentNumber()];
3397 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3398 NewTy = VectorType::getExtendedElementVectorType(VTy);
3399 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3400 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3406 case IITDescriptor::TruncArgument: {
3407 // This may only be used when referring to a previous vector argument.
3408 if (D.getArgumentNumber() >= ArgTys.size())
3411 Type *NewTy = ArgTys[D.getArgumentNumber()];
3412 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3413 NewTy = VectorType::getTruncatedElementVectorType(VTy);
3414 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3415 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3421 case IITDescriptor::HalfVecArgument:
3422 // This may only be used when referring to a previous vector argument.
3423 return D.getArgumentNumber() >= ArgTys.size() ||
3424 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3425 VectorType::getHalfElementsVectorType(
3426 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3427 case IITDescriptor::SameVecWidthArgument: {
3428 if (D.getArgumentNumber() >= ArgTys.size())
3430 VectorType * ReferenceType =
3431 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3432 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3433 if (!ThisArgType || !ReferenceType ||
3434 (ReferenceType->getVectorNumElements() !=
3435 ThisArgType->getVectorNumElements()))
3437 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3440 case IITDescriptor::PtrToArgument: {
3441 if (D.getArgumentNumber() >= ArgTys.size())
3443 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3444 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3445 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3447 case IITDescriptor::VecOfPtrsToElt: {
3448 if (D.getArgumentNumber() >= ArgTys.size())
3450 VectorType * ReferenceType =
3451 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3452 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3453 if (!ThisArgVecTy || !ReferenceType ||
3454 (ReferenceType->getVectorNumElements() !=
3455 ThisArgVecTy->getVectorNumElements()))
3457 PointerType *ThisArgEltTy =
3458 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3461 return ThisArgEltTy->getElementType() !=
3462 ReferenceType->getVectorElementType();
3465 llvm_unreachable("unhandled");
3468 /// \brief Verify if the intrinsic has variable arguments.
3469 /// This method is intended to be called after all the fixed arguments have been
3472 /// This method returns true on error and does not print an error message.
3474 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3475 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3476 using namespace Intrinsic;
3478 // If there are no descriptors left, then it can't be a vararg.
3482 // There should be only one descriptor remaining at this point.
3483 if (Infos.size() != 1)
3486 // Check and verify the descriptor.
3487 IITDescriptor D = Infos.front();
3488 Infos = Infos.slice(1);
3489 if (D.Kind == IITDescriptor::VarArg)
3495 /// Allow intrinsics to be verified in different ways.
3496 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3497 Function *IF = CS.getCalledFunction();
3498 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3501 // Verify that the intrinsic prototype lines up with what the .td files
3503 FunctionType *IFTy = IF->getFunctionType();
3504 bool IsVarArg = IFTy->isVarArg();
3506 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3507 getIntrinsicInfoTableEntries(ID, Table);
3508 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3510 SmallVector<Type *, 4> ArgTys;
3511 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3512 "Intrinsic has incorrect return type!", IF);
3513 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3514 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3515 "Intrinsic has incorrect argument type!", IF);
3517 // Verify if the intrinsic call matches the vararg property.
3519 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3520 "Intrinsic was not defined with variable arguments!", IF);
3522 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3523 "Callsite was not defined with variable arguments!", IF);
3525 // All descriptors should be absorbed by now.
3526 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3528 // Now that we have the intrinsic ID and the actual argument types (and we
3529 // know they are legal for the intrinsic!) get the intrinsic name through the
3530 // usual means. This allows us to verify the mangling of argument types into
3532 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3533 Assert(ExpectedName == IF->getName(),
3534 "Intrinsic name not mangled correctly for type arguments! "
3539 // If the intrinsic takes MDNode arguments, verify that they are either global
3540 // or are local to *this* function.
3541 for (Value *V : CS.args())
3542 if (auto *MD = dyn_cast<MetadataAsValue>(V))
3543 visitMetadataAsValue(*MD, CS.getCaller());
3548 case Intrinsic::ctlz: // llvm.ctlz
3549 case Intrinsic::cttz: // llvm.cttz
3550 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3551 "is_zero_undef argument of bit counting intrinsics must be a "
3555 case Intrinsic::dbg_declare: // llvm.dbg.declare
3556 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3557 "invalid llvm.dbg.declare intrinsic call 1", CS);
3558 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3560 case Intrinsic::dbg_value: // llvm.dbg.value
3561 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3563 case Intrinsic::memcpy:
3564 case Intrinsic::memmove:
3565 case Intrinsic::memset: {
3566 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3568 "alignment argument of memory intrinsics must be a constant int",
3570 const APInt &AlignVal = AlignCI->getValue();
3571 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3572 "alignment argument of memory intrinsics must be a power of 2", CS);
3573 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3574 "isvolatile argument of memory intrinsics must be a constant int",
3578 case Intrinsic::gcroot:
3579 case Intrinsic::gcwrite:
3580 case Intrinsic::gcread:
3581 if (ID == Intrinsic::gcroot) {
3583 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3584 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3585 Assert(isa<Constant>(CS.getArgOperand(1)),
3586 "llvm.gcroot parameter #2 must be a constant.", CS);
3587 if (!AI->getAllocatedType()->isPointerTy()) {
3588 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3589 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3590 "or argument #2 must be a non-null constant.",
3595 Assert(CS.getParent()->getParent()->hasGC(),
3596 "Enclosing function does not use GC.", CS);
3598 case Intrinsic::init_trampoline:
3599 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3600 "llvm.init_trampoline parameter #2 must resolve to a function.",
3603 case Intrinsic::prefetch:
3604 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3605 isa<ConstantInt>(CS.getArgOperand(2)) &&
3606 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3607 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3608 "invalid arguments to llvm.prefetch", CS);
3610 case Intrinsic::stackprotector:
3611 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3612 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3614 case Intrinsic::lifetime_start:
3615 case Intrinsic::lifetime_end:
3616 case Intrinsic::invariant_start:
3617 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3618 "size argument of memory use markers must be a constant integer",
3621 case Intrinsic::invariant_end:
3622 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3623 "llvm.invariant.end parameter #2 must be a constant integer", CS);
3626 case Intrinsic::localescape: {
3627 BasicBlock *BB = CS.getParent();
3628 Assert(BB == &BB->getParent()->front(),
3629 "llvm.localescape used outside of entry block", CS);
3630 Assert(!SawFrameEscape,
3631 "multiple calls to llvm.localescape in one function", CS);
3632 for (Value *Arg : CS.args()) {
3633 if (isa<ConstantPointerNull>(Arg))
3634 continue; // Null values are allowed as placeholders.
3635 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3636 Assert(AI && AI->isStaticAlloca(),
3637 "llvm.localescape only accepts static allocas", CS);
3639 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3640 SawFrameEscape = true;
3643 case Intrinsic::localrecover: {
3644 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3645 Function *Fn = dyn_cast<Function>(FnArg);
3646 Assert(Fn && !Fn->isDeclaration(),
3647 "llvm.localrecover first "
3648 "argument must be function defined in this module",
3650 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3651 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3653 auto &Entry = FrameEscapeInfo[Fn];
3654 Entry.second = unsigned(
3655 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3659 case Intrinsic::experimental_gc_statepoint:
3660 Assert(!CS.isInlineAsm(),
3661 "gc.statepoint support for inline assembly unimplemented", CS);
3662 Assert(CS.getParent()->getParent()->hasGC(),
3663 "Enclosing function does not use GC.", CS);
3665 VerifyStatepoint(CS);
3667 case Intrinsic::experimental_gc_result: {
3668 Assert(CS.getParent()->getParent()->hasGC(),
3669 "Enclosing function does not use GC.", CS);
3670 // Are we tied to a statepoint properly?
3671 CallSite StatepointCS(CS.getArgOperand(0));
3672 const Function *StatepointFn =
3673 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3674 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3675 StatepointFn->getIntrinsicID() ==
3676 Intrinsic::experimental_gc_statepoint,
3677 "gc.result operand #1 must be from a statepoint", CS,
3678 CS.getArgOperand(0));
3680 // Assert that result type matches wrapped callee.
3681 const Value *Target = StatepointCS.getArgument(2);
3682 auto *PT = cast<PointerType>(Target->getType());
3683 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3684 Assert(CS.getType() == TargetFuncType->getReturnType(),
3685 "gc.result result type does not match wrapped callee", CS);
3688 case Intrinsic::experimental_gc_relocate: {
3689 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3691 Assert(isa<PointerType>(CS.getType()->getScalarType()),
3692 "gc.relocate must return a pointer or a vector of pointers", CS);
3694 // Check that this relocate is correctly tied to the statepoint
3696 // This is case for relocate on the unwinding path of an invoke statepoint
3697 if (LandingPadInst *LandingPad =
3698 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
3700 const BasicBlock *InvokeBB =
3701 LandingPad->getParent()->getUniquePredecessor();
3703 // Landingpad relocates should have only one predecessor with invoke
3704 // statepoint terminator
3705 Assert(InvokeBB, "safepoints should have unique landingpads",
3706 LandingPad->getParent());
3707 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3709 Assert(isStatepoint(InvokeBB->getTerminator()),
3710 "gc relocate should be linked to a statepoint", InvokeBB);
3713 // In all other cases relocate should be tied to the statepoint directly.
3714 // This covers relocates on a normal return path of invoke statepoint and
3715 // relocates of a call statepoint
3716 auto Token = CS.getArgOperand(0);
3717 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3718 "gc relocate is incorrectly tied to the statepoint", CS, Token);
3721 // Verify rest of the relocate arguments
3723 ImmutableCallSite StatepointCS(
3724 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
3726 // Both the base and derived must be piped through the safepoint
3727 Value* Base = CS.getArgOperand(1);
3728 Assert(isa<ConstantInt>(Base),
3729 "gc.relocate operand #2 must be integer offset", CS);
3731 Value* Derived = CS.getArgOperand(2);
3732 Assert(isa<ConstantInt>(Derived),
3733 "gc.relocate operand #3 must be integer offset", CS);
3735 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3736 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3738 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3739 "gc.relocate: statepoint base index out of bounds", CS);
3740 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3741 "gc.relocate: statepoint derived index out of bounds", CS);
3743 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3744 // section of the statepoint's argument
3745 Assert(StatepointCS.arg_size() > 0,
3746 "gc.statepoint: insufficient arguments");
3747 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3748 "gc.statement: number of call arguments must be constant integer");
3749 const unsigned NumCallArgs =
3750 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3751 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3752 "gc.statepoint: mismatch in number of call arguments");
3753 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3754 "gc.statepoint: number of transition arguments must be "
3755 "a constant integer");
3756 const int NumTransitionArgs =
3757 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3759 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3760 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3761 "gc.statepoint: number of deoptimization arguments must be "
3762 "a constant integer");
3763 const int NumDeoptArgs =
3764 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3765 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3766 const int GCParamArgsEnd = StatepointCS.arg_size();
3767 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3768 "gc.relocate: statepoint base index doesn't fall within the "
3769 "'gc parameters' section of the statepoint call",
3771 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3772 "gc.relocate: statepoint derived index doesn't fall within the "
3773 "'gc parameters' section of the statepoint call",
3776 // Relocated value must be either a pointer type or vector-of-pointer type,
3777 // but gc_relocate does not need to return the same pointer type as the
3778 // relocated pointer. It can be casted to the correct type later if it's
3779 // desired. However, they must have the same address space and 'vectorness'
3780 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
3781 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(),
3782 "gc.relocate: relocated value must be a gc pointer", CS);
3784 auto ResultType = CS.getType();
3785 auto DerivedType = Relocate.getDerivedPtr()->getType();
3786 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
3787 "gc.relocate: vector relocates to vector and pointer to pointer", CS);
3788 Assert(ResultType->getPointerAddressSpace() ==
3789 DerivedType->getPointerAddressSpace(),
3790 "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3793 case Intrinsic::eh_exceptioncode:
3794 case Intrinsic::eh_exceptionpointer: {
3795 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3796 "eh.exceptionpointer argument must be a catchpad", CS);
3802 /// \brief Carefully grab the subprogram from a local scope.
3804 /// This carefully grabs the subprogram from a local scope, avoiding the
3805 /// built-in assertions that would typically fire.
3806 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3810 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3813 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3814 return getSubprogram(LB->getRawScope());
3816 // Just return null; broken scope chains are checked elsewhere.
3817 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3821 template <class DbgIntrinsicTy>
3822 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3823 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3824 Assert(isa<ValueAsMetadata>(MD) ||
3825 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3826 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3827 Assert(isa<DILocalVariable>(DII.getRawVariable()),
3828 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3829 DII.getRawVariable());
3830 Assert(isa<DIExpression>(DII.getRawExpression()),
3831 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3832 DII.getRawExpression());
3834 // Ignore broken !dbg attachments; they're checked elsewhere.
3835 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3836 if (!isa<DILocation>(N))
3839 BasicBlock *BB = DII.getParent();
3840 Function *F = BB ? BB->getParent() : nullptr;
3842 // The scopes for variables and !dbg attachments must agree.
3843 DILocalVariable *Var = DII.getVariable();
3844 DILocation *Loc = DII.getDebugLoc();
3845 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3848 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3849 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3850 if (!VarSP || !LocSP)
3851 return; // Broken scope chains are checked elsewhere.
3853 Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3854 " variable and !dbg attachment",
3855 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3856 Loc->getScope()->getSubprogram());
3859 template <class MapTy>
3860 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3861 // Be careful of broken types (checked elsewhere).
3862 const Metadata *RawType = V.getRawType();
3864 // Try to get the size directly.
3865 if (auto *T = dyn_cast<DIType>(RawType))
3866 if (uint64_t Size = T->getSizeInBits())
3869 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3870 // Look at the base type.
3871 RawType = DT->getRawBaseType();
3875 if (auto *S = dyn_cast<MDString>(RawType)) {
3876 // Don't error on missing types (checked elsewhere).
3877 RawType = Map.lookup(S);
3881 // Missing type or size.
3889 template <class MapTy>
3890 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3891 const MapTy &TypeRefs) {
3894 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3895 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
3896 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
3898 auto *DDI = cast<DbgDeclareInst>(&I);
3899 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
3900 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
3903 // We don't know whether this intrinsic verified correctly.
3904 if (!V || !E || !E->isValid())
3907 // Nothing to do if this isn't a bit piece expression.
3908 if (!E->isBitPiece())
3911 // The frontend helps out GDB by emitting the members of local anonymous
3912 // unions as artificial local variables with shared storage. When SROA splits
3913 // the storage for artificial local variables that are smaller than the entire
3914 // union, the overhang piece will be outside of the allotted space for the
3915 // variable and this check fails.
3916 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
3917 if (V->isArtificial())
3920 // If there's no size, the type is broken, but that should be checked
3922 uint64_t VarSize = getVariableSize(*V, TypeRefs);
3926 unsigned PieceSize = E->getBitPieceSize();
3927 unsigned PieceOffset = E->getBitPieceOffset();
3928 Assert(PieceSize + PieceOffset <= VarSize,
3929 "piece is larger than or outside of variable", &I, V, E);
3930 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3933 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3934 // This is in its own function so we get an error for each bad type ref (not
3936 Assert(false, "unresolved type ref", S, N);
3939 void Verifier::verifyTypeRefs() {
3940 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3944 // Visit all the compile units again to map the type references.
3945 SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
3946 for (auto *CU : CUs->operands())
3947 if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
3948 for (DIType *Op : Ts)
3949 if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
3950 if (auto *S = T->getRawIdentifier()) {
3951 UnresolvedTypeRefs.erase(S);
3952 TypeRefs.insert(std::make_pair(S, T));
3955 // Verify debug info intrinsic bit piece expressions. This needs a second
3956 // pass through the intructions, since we haven't built TypeRefs yet when
3957 // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
3958 // later/now would queue up some that could be later deleted.
3959 for (const Function &F : *M)
3960 for (const BasicBlock &BB : F)
3961 for (const Instruction &I : BB)
3962 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
3963 verifyBitPieceExpression(*DII, TypeRefs);
3965 // Return early if all typerefs were resolved.
3966 if (UnresolvedTypeRefs.empty())
3969 // Sort the unresolved references by name so the output is deterministic.
3970 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3971 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3972 UnresolvedTypeRefs.end());
3973 std::sort(Unresolved.begin(), Unresolved.end(),
3974 [](const TypeRef &LHS, const TypeRef &RHS) {
3975 return LHS.first->getString() < RHS.first->getString();
3978 // Visit the unresolved refs (printing out the errors).
3979 for (const TypeRef &TR : Unresolved)
3980 visitUnresolvedTypeRef(TR.first, TR.second);
3983 //===----------------------------------------------------------------------===//
3984 // Implement the public interfaces to this file...
3985 //===----------------------------------------------------------------------===//
3987 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3988 Function &F = const_cast<Function &>(f);
3989 assert(!F.isDeclaration() && "Cannot verify external functions");
3991 raw_null_ostream NullStr;
3992 Verifier V(OS ? *OS : NullStr);
3994 // Note that this function's return value is inverted from what you would
3995 // expect of a function called "verify".
3996 return !V.verify(F);
3999 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
4000 raw_null_ostream NullStr;
4001 Verifier V(OS ? *OS : NullStr);
4003 bool Broken = false;
4004 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
4005 if (!I->isDeclaration() && !I->isMaterializable())
4006 Broken |= !V.verify(*I);
4008 // Note that this function's return value is inverted from what you would
4009 // expect of a function called "verify".
4010 return !V.verify(M) || Broken;
4014 struct VerifierLegacyPass : public FunctionPass {
4020 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
4021 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
4023 explicit VerifierLegacyPass(bool FatalErrors)
4024 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
4025 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
4028 bool runOnFunction(Function &F) override {
4029 if (!V.verify(F) && FatalErrors)
4030 report_fatal_error("Broken function found, compilation aborted!");
4035 bool doFinalization(Module &M) override {
4036 if (!V.verify(M) && FatalErrors)
4037 report_fatal_error("Broken module found, compilation aborted!");
4042 void getAnalysisUsage(AnalysisUsage &AU) const override {
4043 AU.setPreservesAll();
4048 char VerifierLegacyPass::ID = 0;
4049 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
4051 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
4052 return new VerifierLegacyPass(FatalErrors);
4055 PreservedAnalyses VerifierPass::run(Module &M) {
4056 if (verifyModule(M, &dbgs()) && FatalErrors)
4057 report_fatal_error("Broken module found, compilation aborted!");
4059 return PreservedAnalyses::all();
4062 PreservedAnalyses VerifierPass::run(Function &F) {
4063 if (verifyFunction(F, &dbgs()) && FatalErrors)
4064 report_fatal_error("Broken function found, compilation aborted!");
4066 return PreservedAnalyses::all();