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;
208 explicit Verifier(raw_ostream &OS)
209 : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
210 SawFrameEscape(false) {}
212 bool verify(const Function &F) {
214 Context = &M->getContext();
216 // First ensure the function is well-enough formed to compute dominance
219 OS << "Function '" << F.getName()
220 << "' does not contain an entry block!\n";
223 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
224 if (I->empty() || !I->back().isTerminator()) {
225 OS << "Basic Block in function '" << F.getName()
226 << "' does not have terminator!\n";
227 I->printAsOperand(OS, true);
233 // Now directly compute a dominance tree. We don't rely on the pass
234 // manager to provide this as it isolates us from a potentially
235 // out-of-date dominator tree and makes it significantly more complex to
236 // run this code outside of a pass manager.
237 // FIXME: It's really gross that we have to cast away constness here.
238 DT.recalculate(const_cast<Function &>(F));
241 // FIXME: We strip const here because the inst visitor strips const.
242 visit(const_cast<Function &>(F));
243 InstsInThisBlock.clear();
244 LandingPadResultTy = nullptr;
245 SawFrameEscape = false;
250 bool verify(const Module &M) {
252 Context = &M.getContext();
255 // Scan through, checking all of the external function's linkage now...
256 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
257 visitGlobalValue(*I);
259 // Check to make sure function prototypes are okay.
260 if (I->isDeclaration())
264 // Now that we've visited every function, verify that we never asked to
265 // recover a frame index that wasn't escaped.
266 verifyFrameRecoverIndices();
268 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
270 visitGlobalVariable(*I);
272 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
274 visitGlobalAlias(*I);
276 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
277 E = M.named_metadata_end();
279 visitNamedMDNode(*I);
281 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
282 visitComdat(SMEC.getValue());
285 visitModuleIdents(M);
287 // Verify type referneces last.
294 // Verification methods...
295 void visitGlobalValue(const GlobalValue &GV);
296 void visitGlobalVariable(const GlobalVariable &GV);
297 void visitGlobalAlias(const GlobalAlias &GA);
298 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
299 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
300 const GlobalAlias &A, const Constant &C);
301 void visitNamedMDNode(const NamedMDNode &NMD);
302 void visitMDNode(const MDNode &MD);
303 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
304 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
305 void visitComdat(const Comdat &C);
306 void visitModuleIdents(const Module &M);
307 void visitModuleFlags(const Module &M);
308 void visitModuleFlag(const MDNode *Op,
309 DenseMap<const MDString *, const MDNode *> &SeenIDs,
310 SmallVectorImpl<const MDNode *> &Requirements);
311 void visitFunction(const Function &F);
312 void visitBasicBlock(BasicBlock &BB);
313 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
314 void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
316 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
317 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
318 #include "llvm/IR/Metadata.def"
319 void visitDIScope(const DIScope &N);
320 void visitDIVariable(const DIVariable &N);
321 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
322 void visitDITemplateParameter(const DITemplateParameter &N);
324 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
326 /// \brief Check for a valid string-based type reference.
328 /// Checks if \c MD is a string-based type reference. If it is, keeps track
329 /// of it (and its user, \c N) for error messages later.
330 bool isValidUUID(const MDNode &N, const Metadata *MD);
332 /// \brief Check for a valid type reference.
334 /// Checks for subclasses of \a DIType, or \a isValidUUID().
335 bool isTypeRef(const MDNode &N, const Metadata *MD);
337 /// \brief Check for a valid scope reference.
339 /// Checks for subclasses of \a DIScope, or \a isValidUUID().
340 bool isScopeRef(const MDNode &N, const Metadata *MD);
342 /// \brief Check for a valid debug info reference.
344 /// Checks for subclasses of \a DINode, or \a isValidUUID().
345 bool isDIRef(const MDNode &N, const Metadata *MD);
347 // InstVisitor overrides...
348 using InstVisitor<Verifier>::visit;
349 void visit(Instruction &I);
351 void visitTruncInst(TruncInst &I);
352 void visitZExtInst(ZExtInst &I);
353 void visitSExtInst(SExtInst &I);
354 void visitFPTruncInst(FPTruncInst &I);
355 void visitFPExtInst(FPExtInst &I);
356 void visitFPToUIInst(FPToUIInst &I);
357 void visitFPToSIInst(FPToSIInst &I);
358 void visitUIToFPInst(UIToFPInst &I);
359 void visitSIToFPInst(SIToFPInst &I);
360 void visitIntToPtrInst(IntToPtrInst &I);
361 void visitPtrToIntInst(PtrToIntInst &I);
362 void visitBitCastInst(BitCastInst &I);
363 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
364 void visitPHINode(PHINode &PN);
365 void visitBinaryOperator(BinaryOperator &B);
366 void visitICmpInst(ICmpInst &IC);
367 void visitFCmpInst(FCmpInst &FC);
368 void visitExtractElementInst(ExtractElementInst &EI);
369 void visitInsertElementInst(InsertElementInst &EI);
370 void visitShuffleVectorInst(ShuffleVectorInst &EI);
371 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
372 void visitCallInst(CallInst &CI);
373 void visitInvokeInst(InvokeInst &II);
374 void visitGetElementPtrInst(GetElementPtrInst &GEP);
375 void visitLoadInst(LoadInst &LI);
376 void visitStoreInst(StoreInst &SI);
377 void verifyDominatesUse(Instruction &I, unsigned i);
378 void visitInstruction(Instruction &I);
379 void visitTerminatorInst(TerminatorInst &I);
380 void visitBranchInst(BranchInst &BI);
381 void visitReturnInst(ReturnInst &RI);
382 void visitSwitchInst(SwitchInst &SI);
383 void visitIndirectBrInst(IndirectBrInst &BI);
384 void visitSelectInst(SelectInst &SI);
385 void visitUserOp1(Instruction &I);
386 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
387 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
388 template <class DbgIntrinsicTy>
389 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
390 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
391 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
392 void visitFenceInst(FenceInst &FI);
393 void visitAllocaInst(AllocaInst &AI);
394 void visitExtractValueInst(ExtractValueInst &EVI);
395 void visitInsertValueInst(InsertValueInst &IVI);
396 void visitEHPadPredecessors(Instruction &I);
397 void visitLandingPadInst(LandingPadInst &LPI);
398 void visitCatchPadInst(CatchPadInst &CPI);
399 void visitCatchEndPadInst(CatchEndPadInst &CEPI);
400 void visitCleanupPadInst(CleanupPadInst &CPI);
401 void visitCleanupEndPadInst(CleanupEndPadInst &CEPI);
402 void visitCleanupReturnInst(CleanupReturnInst &CRI);
403 void visitTerminatePadInst(TerminatePadInst &TPI);
405 void VerifyCallSite(CallSite CS);
406 void verifyMustTailCall(CallInst &CI);
407 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
408 unsigned ArgNo, std::string &Suffix);
409 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
410 SmallVectorImpl<Type *> &ArgTys);
411 bool VerifyIntrinsicIsVarArg(bool isVarArg,
412 ArrayRef<Intrinsic::IITDescriptor> &Infos);
413 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
414 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
416 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
417 bool isReturnValue, const Value *V);
418 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
420 void VerifyFunctionMetadata(
421 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
423 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
424 void VerifyStatepoint(ImmutableCallSite CS);
425 void verifyFrameRecoverIndices();
427 // Module-level debug info verification...
428 void verifyTypeRefs();
429 template <class MapTy>
430 void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
431 const MapTy &TypeRefs);
432 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
434 } // End anonymous namespace
436 // Assert - We know that cond should be true, if not print an error message.
437 #define Assert(C, ...) \
438 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
440 void Verifier::visit(Instruction &I) {
441 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
442 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
443 InstVisitor<Verifier>::visit(I);
447 void Verifier::visitGlobalValue(const GlobalValue &GV) {
448 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
449 GV.hasExternalWeakLinkage(),
450 "Global is external, but doesn't have external or weak linkage!", &GV);
452 Assert(GV.getAlignment() <= Value::MaximumAlignment,
453 "huge alignment values are unsupported", &GV);
454 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
455 "Only global variables can have appending linkage!", &GV);
457 if (GV.hasAppendingLinkage()) {
458 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
459 Assert(GVar && GVar->getValueType()->isArrayTy(),
460 "Only global arrays can have appending linkage!", GVar);
463 if (GV.isDeclarationForLinker())
464 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
467 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
468 if (GV.hasInitializer()) {
469 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
470 "Global variable initializer type does not match global "
474 // If the global has common linkage, it must have a zero initializer and
475 // cannot be constant.
476 if (GV.hasCommonLinkage()) {
477 Assert(GV.getInitializer()->isNullValue(),
478 "'common' global must have a zero initializer!", &GV);
479 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
481 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
484 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
485 "invalid linkage type for global declaration", &GV);
488 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
489 GV.getName() == "llvm.global_dtors")) {
490 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
491 "invalid linkage for intrinsic global variable", &GV);
492 // Don't worry about emitting an error for it not being an array,
493 // visitGlobalValue will complain on appending non-array.
494 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
495 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
496 PointerType *FuncPtrTy =
497 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
498 // FIXME: Reject the 2-field form in LLVM 4.0.
500 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
501 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
502 STy->getTypeAtIndex(1) == FuncPtrTy,
503 "wrong type for intrinsic global variable", &GV);
504 if (STy->getNumElements() == 3) {
505 Type *ETy = STy->getTypeAtIndex(2);
506 Assert(ETy->isPointerTy() &&
507 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
508 "wrong type for intrinsic global variable", &GV);
513 if (GV.hasName() && (GV.getName() == "llvm.used" ||
514 GV.getName() == "llvm.compiler.used")) {
515 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
516 "invalid linkage for intrinsic global variable", &GV);
517 Type *GVType = GV.getValueType();
518 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
519 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
520 Assert(PTy, "wrong type for intrinsic global variable", &GV);
521 if (GV.hasInitializer()) {
522 const Constant *Init = GV.getInitializer();
523 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
524 Assert(InitArray, "wrong initalizer for intrinsic global variable",
526 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
527 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
528 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
530 "invalid llvm.used member", V);
531 Assert(V->hasName(), "members of llvm.used must be named", V);
537 Assert(!GV.hasDLLImportStorageClass() ||
538 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
539 GV.hasAvailableExternallyLinkage(),
540 "Global is marked as dllimport, but not external", &GV);
542 if (!GV.hasInitializer()) {
543 visitGlobalValue(GV);
547 // Walk any aggregate initializers looking for bitcasts between address spaces
548 SmallPtrSet<const Value *, 4> Visited;
549 SmallVector<const Value *, 4> WorkStack;
550 WorkStack.push_back(cast<Value>(GV.getInitializer()));
552 while (!WorkStack.empty()) {
553 const Value *V = WorkStack.pop_back_val();
554 if (!Visited.insert(V).second)
557 if (const User *U = dyn_cast<User>(V)) {
558 WorkStack.append(U->op_begin(), U->op_end());
561 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
562 VerifyConstantExprBitcastType(CE);
568 visitGlobalValue(GV);
571 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
572 SmallPtrSet<const GlobalAlias*, 4> Visited;
574 visitAliaseeSubExpr(Visited, GA, C);
577 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
578 const GlobalAlias &GA, const Constant &C) {
579 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
580 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
583 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
584 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
586 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
589 // Only continue verifying subexpressions of GlobalAliases.
590 // Do not recurse into global initializers.
595 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
596 VerifyConstantExprBitcastType(CE);
598 for (const Use &U : C.operands()) {
600 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
601 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
602 else if (const auto *C2 = dyn_cast<Constant>(V))
603 visitAliaseeSubExpr(Visited, GA, *C2);
607 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
608 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
609 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
610 "weak_odr, or external linkage!",
612 const Constant *Aliasee = GA.getAliasee();
613 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
614 Assert(GA.getType() == Aliasee->getType(),
615 "Alias and aliasee types should match!", &GA);
617 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
618 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
620 visitAliaseeSubExpr(GA, *Aliasee);
622 visitGlobalValue(GA);
625 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
626 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
627 MDNode *MD = NMD.getOperand(i);
629 if (NMD.getName() == "llvm.dbg.cu") {
630 Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
640 void Verifier::visitMDNode(const MDNode &MD) {
641 // Only visit each node once. Metadata can be mutually recursive, so this
642 // avoids infinite recursion here, as well as being an optimization.
643 if (!MDNodes.insert(&MD).second)
646 switch (MD.getMetadataID()) {
648 llvm_unreachable("Invalid MDNode subclass");
649 case Metadata::MDTupleKind:
651 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
652 case Metadata::CLASS##Kind: \
653 visit##CLASS(cast<CLASS>(MD)); \
655 #include "llvm/IR/Metadata.def"
658 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
659 Metadata *Op = MD.getOperand(i);
662 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
664 if (auto *N = dyn_cast<MDNode>(Op)) {
668 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
669 visitValueAsMetadata(*V, nullptr);
674 // Check these last, so we diagnose problems in operands first.
675 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
676 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
679 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
680 Assert(MD.getValue(), "Expected valid value", &MD);
681 Assert(!MD.getValue()->getType()->isMetadataTy(),
682 "Unexpected metadata round-trip through values", &MD, MD.getValue());
684 auto *L = dyn_cast<LocalAsMetadata>(&MD);
688 Assert(F, "function-local metadata used outside a function", L);
690 // If this was an instruction, bb, or argument, verify that it is in the
691 // function that we expect.
692 Function *ActualF = nullptr;
693 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
694 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
695 ActualF = I->getParent()->getParent();
696 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
697 ActualF = BB->getParent();
698 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
699 ActualF = A->getParent();
700 assert(ActualF && "Unimplemented function local metadata case!");
702 Assert(ActualF == F, "function-local metadata used in wrong function", L);
705 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
706 Metadata *MD = MDV.getMetadata();
707 if (auto *N = dyn_cast<MDNode>(MD)) {
712 // Only visit each node once. Metadata can be mutually recursive, so this
713 // avoids infinite recursion here, as well as being an optimization.
714 if (!MDNodes.insert(MD).second)
717 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
718 visitValueAsMetadata(*V, F);
721 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
722 auto *S = dyn_cast<MDString>(MD);
725 if (S->getString().empty())
728 // Keep track of names of types referenced via UUID so we can check that they
730 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
734 /// \brief Check if a value can be a reference to a type.
735 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
736 return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
739 /// \brief Check if a value can be a ScopeRef.
740 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
741 return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
744 /// \brief Check if a value can be a debug info ref.
745 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
746 return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
750 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
751 for (Metadata *MD : N.operands()) {
764 bool isValidMetadataArray(const MDTuple &N) {
765 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
769 bool isValidMetadataNullArray(const MDTuple &N) {
770 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
773 void Verifier::visitDILocation(const DILocation &N) {
774 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
775 "location requires a valid scope", &N, N.getRawScope());
776 if (auto *IA = N.getRawInlinedAt())
777 Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
780 void Verifier::visitGenericDINode(const GenericDINode &N) {
781 Assert(N.getTag(), "invalid tag", &N);
784 void Verifier::visitDIScope(const DIScope &N) {
785 if (auto *F = N.getRawFile())
786 Assert(isa<DIFile>(F), "invalid file", &N, F);
789 void Verifier::visitDISubrange(const DISubrange &N) {
790 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
791 Assert(N.getCount() >= -1, "invalid subrange count", &N);
794 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
795 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
798 void Verifier::visitDIBasicType(const DIBasicType &N) {
799 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
800 N.getTag() == dwarf::DW_TAG_unspecified_type,
804 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
805 // Common scope checks.
808 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
809 N.getTag() == dwarf::DW_TAG_pointer_type ||
810 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
811 N.getTag() == dwarf::DW_TAG_reference_type ||
812 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
813 N.getTag() == dwarf::DW_TAG_const_type ||
814 N.getTag() == dwarf::DW_TAG_volatile_type ||
815 N.getTag() == dwarf::DW_TAG_restrict_type ||
816 N.getTag() == dwarf::DW_TAG_member ||
817 N.getTag() == dwarf::DW_TAG_inheritance ||
818 N.getTag() == dwarf::DW_TAG_friend,
820 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
821 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
825 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
826 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
830 static bool hasConflictingReferenceFlags(unsigned Flags) {
831 return (Flags & DINode::FlagLValueReference) &&
832 (Flags & DINode::FlagRValueReference);
835 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
836 auto *Params = dyn_cast<MDTuple>(&RawParams);
837 Assert(Params, "invalid template params", &N, &RawParams);
838 for (Metadata *Op : Params->operands()) {
839 Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
844 void Verifier::visitDICompositeType(const DICompositeType &N) {
845 // Common scope checks.
848 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
849 N.getTag() == dwarf::DW_TAG_structure_type ||
850 N.getTag() == dwarf::DW_TAG_union_type ||
851 N.getTag() == dwarf::DW_TAG_enumeration_type ||
852 N.getTag() == dwarf::DW_TAG_class_type,
855 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
856 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
859 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
860 "invalid composite elements", &N, N.getRawElements());
861 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
862 N.getRawVTableHolder());
863 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
864 "invalid composite elements", &N, N.getRawElements());
865 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
867 if (auto *Params = N.getRawTemplateParams())
868 visitTemplateParams(N, *Params);
870 if (N.getTag() == dwarf::DW_TAG_class_type ||
871 N.getTag() == dwarf::DW_TAG_union_type) {
872 Assert(N.getFile() && !N.getFile()->getFilename().empty(),
873 "class/union requires a filename", &N, N.getFile());
877 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
878 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
879 if (auto *Types = N.getRawTypeArray()) {
880 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
881 for (Metadata *Ty : N.getTypeArray()->operands()) {
882 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
885 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
889 void Verifier::visitDIFile(const DIFile &N) {
890 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
893 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
894 Assert(N.isDistinct(), "compile units must be distinct", &N);
895 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
897 // Don't bother verifying the compilation directory or producer string
898 // as those could be empty.
899 Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
901 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
904 if (auto *Array = N.getRawEnumTypes()) {
905 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
906 for (Metadata *Op : N.getEnumTypes()->operands()) {
907 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
908 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
909 "invalid enum type", &N, N.getEnumTypes(), Op);
912 if (auto *Array = N.getRawRetainedTypes()) {
913 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
914 for (Metadata *Op : N.getRetainedTypes()->operands()) {
915 Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
918 if (auto *Array = N.getRawSubprograms()) {
919 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
920 for (Metadata *Op : N.getSubprograms()->operands()) {
921 Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
924 if (auto *Array = N.getRawGlobalVariables()) {
925 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
926 for (Metadata *Op : N.getGlobalVariables()->operands()) {
927 Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
931 if (auto *Array = N.getRawImportedEntities()) {
932 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
933 for (Metadata *Op : N.getImportedEntities()->operands()) {
934 Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
940 void Verifier::visitDISubprogram(const DISubprogram &N) {
941 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
942 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
943 if (auto *T = N.getRawType())
944 Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
945 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
946 N.getRawContainingType());
947 if (auto *Params = N.getRawTemplateParams())
948 visitTemplateParams(N, *Params);
949 if (auto *S = N.getRawDeclaration()) {
950 Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
951 "invalid subprogram declaration", &N, S);
953 if (auto *RawVars = N.getRawVariables()) {
954 auto *Vars = dyn_cast<MDTuple>(RawVars);
955 Assert(Vars, "invalid variable list", &N, RawVars);
956 for (Metadata *Op : Vars->operands()) {
957 Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
961 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
964 if (N.isDefinition())
965 Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
968 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
969 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
970 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
971 "invalid local scope", &N, N.getRawScope());
974 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
975 visitDILexicalBlockBase(N);
977 Assert(N.getLine() || !N.getColumn(),
978 "cannot have column info without line info", &N);
981 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
982 visitDILexicalBlockBase(N);
985 void Verifier::visitDINamespace(const DINamespace &N) {
986 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
987 if (auto *S = N.getRawScope())
988 Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
991 void Verifier::visitDIModule(const DIModule &N) {
992 Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
993 Assert(!N.getName().empty(), "anonymous module", &N);
996 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
997 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1000 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1001 visitDITemplateParameter(N);
1003 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1007 void Verifier::visitDITemplateValueParameter(
1008 const DITemplateValueParameter &N) {
1009 visitDITemplateParameter(N);
1011 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1012 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1013 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1017 void Verifier::visitDIVariable(const DIVariable &N) {
1018 if (auto *S = N.getRawScope())
1019 Assert(isa<DIScope>(S), "invalid scope", &N, S);
1020 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1021 if (auto *F = N.getRawFile())
1022 Assert(isa<DIFile>(F), "invalid file", &N, F);
1025 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1026 // Checks common to all variables.
1029 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1030 Assert(!N.getName().empty(), "missing global variable name", &N);
1031 if (auto *V = N.getRawVariable()) {
1032 Assert(isa<ConstantAsMetadata>(V) &&
1033 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1034 "invalid global varaible ref", &N, V);
1036 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1037 Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1042 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1043 // Checks common to all variables.
1046 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1047 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1048 "local variable requires a valid scope", &N, N.getRawScope());
1051 void Verifier::visitDIExpression(const DIExpression &N) {
1052 Assert(N.isValid(), "invalid expression", &N);
1055 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1056 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1057 if (auto *T = N.getRawType())
1058 Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1059 if (auto *F = N.getRawFile())
1060 Assert(isa<DIFile>(F), "invalid file", &N, F);
1063 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1064 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1065 N.getTag() == dwarf::DW_TAG_imported_declaration,
1067 if (auto *S = N.getRawScope())
1068 Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1069 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1073 void Verifier::visitComdat(const Comdat &C) {
1074 // The Module is invalid if the GlobalValue has private linkage. Entities
1075 // with private linkage don't have entries in the symbol table.
1076 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1077 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1081 void Verifier::visitModuleIdents(const Module &M) {
1082 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1086 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1087 // Scan each llvm.ident entry and make sure that this requirement is met.
1088 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1089 const MDNode *N = Idents->getOperand(i);
1090 Assert(N->getNumOperands() == 1,
1091 "incorrect number of operands in llvm.ident metadata", N);
1092 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1093 ("invalid value for llvm.ident metadata entry operand"
1094 "(the operand should be a string)"),
1099 void Verifier::visitModuleFlags(const Module &M) {
1100 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1103 // Scan each flag, and track the flags and requirements.
1104 DenseMap<const MDString*, const MDNode*> SeenIDs;
1105 SmallVector<const MDNode*, 16> Requirements;
1106 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1107 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1110 // Validate that the requirements in the module are valid.
1111 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1112 const MDNode *Requirement = Requirements[I];
1113 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1114 const Metadata *ReqValue = Requirement->getOperand(1);
1116 const MDNode *Op = SeenIDs.lookup(Flag);
1118 CheckFailed("invalid requirement on flag, flag is not present in module",
1123 if (Op->getOperand(2) != ReqValue) {
1124 CheckFailed(("invalid requirement on flag, "
1125 "flag does not have the required value"),
1133 Verifier::visitModuleFlag(const MDNode *Op,
1134 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1135 SmallVectorImpl<const MDNode *> &Requirements) {
1136 // Each module flag should have three arguments, the merge behavior (a
1137 // constant int), the flag ID (an MDString), and the value.
1138 Assert(Op->getNumOperands() == 3,
1139 "incorrect number of operands in module flag", Op);
1140 Module::ModFlagBehavior MFB;
1141 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1143 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1144 "invalid behavior operand in module flag (expected constant integer)",
1147 "invalid behavior operand in module flag (unexpected constant)",
1150 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1151 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1154 // Sanity check the values for behaviors with additional requirements.
1157 case Module::Warning:
1158 case Module::Override:
1159 // These behavior types accept any value.
1162 case Module::Require: {
1163 // The value should itself be an MDNode with two operands, a flag ID (an
1164 // MDString), and a value.
1165 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1166 Assert(Value && Value->getNumOperands() == 2,
1167 "invalid value for 'require' module flag (expected metadata pair)",
1169 Assert(isa<MDString>(Value->getOperand(0)),
1170 ("invalid value for 'require' module flag "
1171 "(first value operand should be a string)"),
1172 Value->getOperand(0));
1174 // Append it to the list of requirements, to check once all module flags are
1176 Requirements.push_back(Value);
1180 case Module::Append:
1181 case Module::AppendUnique: {
1182 // These behavior types require the operand be an MDNode.
1183 Assert(isa<MDNode>(Op->getOperand(2)),
1184 "invalid value for 'append'-type module flag "
1185 "(expected a metadata node)",
1191 // Unless this is a "requires" flag, check the ID is unique.
1192 if (MFB != Module::Require) {
1193 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1195 "module flag identifiers must be unique (or of 'require' type)", ID);
1199 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1200 bool isFunction, const Value *V) {
1201 unsigned Slot = ~0U;
1202 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1203 if (Attrs.getSlotIndex(I) == Idx) {
1208 assert(Slot != ~0U && "Attribute set inconsistency!");
1210 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1212 if (I->isStringAttribute())
1215 if (I->getKindAsEnum() == Attribute::NoReturn ||
1216 I->getKindAsEnum() == Attribute::NoUnwind ||
1217 I->getKindAsEnum() == Attribute::NoInline ||
1218 I->getKindAsEnum() == Attribute::AlwaysInline ||
1219 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1220 I->getKindAsEnum() == Attribute::StackProtect ||
1221 I->getKindAsEnum() == Attribute::StackProtectReq ||
1222 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1223 I->getKindAsEnum() == Attribute::SafeStack ||
1224 I->getKindAsEnum() == Attribute::NoRedZone ||
1225 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1226 I->getKindAsEnum() == Attribute::Naked ||
1227 I->getKindAsEnum() == Attribute::InlineHint ||
1228 I->getKindAsEnum() == Attribute::StackAlignment ||
1229 I->getKindAsEnum() == Attribute::UWTable ||
1230 I->getKindAsEnum() == Attribute::NonLazyBind ||
1231 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1232 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1233 I->getKindAsEnum() == Attribute::SanitizeThread ||
1234 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1235 I->getKindAsEnum() == Attribute::MinSize ||
1236 I->getKindAsEnum() == Attribute::NoDuplicate ||
1237 I->getKindAsEnum() == Attribute::Builtin ||
1238 I->getKindAsEnum() == Attribute::NoBuiltin ||
1239 I->getKindAsEnum() == Attribute::Cold ||
1240 I->getKindAsEnum() == Attribute::OptimizeNone ||
1241 I->getKindAsEnum() == Attribute::JumpTable ||
1242 I->getKindAsEnum() == Attribute::Convergent ||
1243 I->getKindAsEnum() == Attribute::ArgMemOnly ||
1244 I->getKindAsEnum() == Attribute::NoRecurse) {
1246 CheckFailed("Attribute '" + I->getAsString() +
1247 "' only applies to functions!", V);
1250 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1251 I->getKindAsEnum() == Attribute::ReadNone) {
1253 CheckFailed("Attribute '" + I->getAsString() +
1254 "' does not apply to function returns");
1257 } else if (isFunction) {
1258 CheckFailed("Attribute '" + I->getAsString() +
1259 "' does not apply to functions!", V);
1265 // VerifyParameterAttrs - Check the given attributes for an argument or return
1266 // value of the specified type. The value V is printed in error messages.
1267 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1268 bool isReturnValue, const Value *V) {
1269 if (!Attrs.hasAttributes(Idx))
1272 VerifyAttributeTypes(Attrs, Idx, false, V);
1275 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1276 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1277 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1278 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1279 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1280 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1281 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1282 "'returned' do not apply to return values!",
1285 // Check for mutually incompatible attributes. Only inreg is compatible with
1287 unsigned AttrCount = 0;
1288 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1289 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1290 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1291 Attrs.hasAttribute(Idx, Attribute::InReg);
1292 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1293 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1294 "and 'sret' are incompatible!",
1297 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1298 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1300 "'inalloca and readonly' are incompatible!",
1303 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1304 Attrs.hasAttribute(Idx, Attribute::Returned)),
1306 "'sret and returned' are incompatible!",
1309 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1310 Attrs.hasAttribute(Idx, Attribute::SExt)),
1312 "'zeroext and signext' are incompatible!",
1315 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1316 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1318 "'readnone and readonly' are incompatible!",
1321 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1322 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1324 "'noinline and alwaysinline' are incompatible!",
1327 Assert(!AttrBuilder(Attrs, Idx)
1328 .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1329 "Wrong types for attribute: " +
1330 AttributeSet::get(*Context, Idx,
1331 AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1334 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1335 SmallPtrSet<Type*, 4> Visited;
1336 if (!PTy->getElementType()->isSized(&Visited)) {
1337 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1338 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1339 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1343 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1344 "Attribute 'byval' only applies to parameters with pointer type!",
1349 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1350 // The value V is printed in error messages.
1351 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1353 if (Attrs.isEmpty())
1356 bool SawNest = false;
1357 bool SawReturned = false;
1358 bool SawSRet = false;
1360 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1361 unsigned Idx = Attrs.getSlotIndex(i);
1365 Ty = FT->getReturnType();
1366 else if (Idx-1 < FT->getNumParams())
1367 Ty = FT->getParamType(Idx-1);
1369 break; // VarArgs attributes, verified elsewhere.
1371 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1376 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1377 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1381 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1382 Assert(!SawReturned, "More than one parameter has attribute returned!",
1384 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1386 "argument and return types for 'returned' attribute",
1391 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1392 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1393 Assert(Idx == 1 || Idx == 2,
1394 "Attribute 'sret' is not on first or second parameter!", V);
1398 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1399 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1404 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1407 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1410 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1411 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1412 "Attributes 'readnone and readonly' are incompatible!", V);
1415 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1416 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1417 Attribute::AlwaysInline)),
1418 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1420 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1421 Attribute::OptimizeNone)) {
1422 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1423 "Attribute 'optnone' requires 'noinline'!", V);
1425 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1426 Attribute::OptimizeForSize),
1427 "Attributes 'optsize and optnone' are incompatible!", V);
1429 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1430 "Attributes 'minsize and optnone' are incompatible!", V);
1433 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1434 Attribute::JumpTable)) {
1435 const GlobalValue *GV = cast<GlobalValue>(V);
1436 Assert(GV->hasUnnamedAddr(),
1437 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1441 void Verifier::VerifyFunctionMetadata(
1442 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1446 for (unsigned i = 0; i < MDs.size(); i++) {
1447 if (MDs[i].first == LLVMContext::MD_prof) {
1448 MDNode *MD = MDs[i].second;
1449 Assert(MD->getNumOperands() == 2,
1450 "!prof annotations should have exactly 2 operands", MD);
1452 // Check first operand.
1453 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1455 Assert(isa<MDString>(MD->getOperand(0)),
1456 "expected string with name of the !prof annotation", MD);
1457 MDString *MDS = cast<MDString>(MD->getOperand(0));
1458 StringRef ProfName = MDS->getString();
1459 Assert(ProfName.equals("function_entry_count"),
1460 "first operand should be 'function_entry_count'", MD);
1462 // Check second operand.
1463 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1465 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1466 "expected integer argument to function_entry_count", MD);
1471 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1472 if (CE->getOpcode() != Instruction::BitCast)
1475 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1477 "Invalid bitcast", CE);
1480 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1481 if (Attrs.getNumSlots() == 0)
1484 unsigned LastSlot = Attrs.getNumSlots() - 1;
1485 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1486 if (LastIndex <= Params
1487 || (LastIndex == AttributeSet::FunctionIndex
1488 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1494 /// \brief Verify that statepoint intrinsic is well formed.
1495 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1496 assert(CS.getCalledFunction() &&
1497 CS.getCalledFunction()->getIntrinsicID() ==
1498 Intrinsic::experimental_gc_statepoint);
1500 const Instruction &CI = *CS.getInstruction();
1502 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1503 !CS.onlyAccessesArgMemory(),
1504 "gc.statepoint must read and write all memory to preserve "
1505 "reordering restrictions required by safepoint semantics",
1508 const Value *IDV = CS.getArgument(0);
1509 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1512 const Value *NumPatchBytesV = CS.getArgument(1);
1513 Assert(isa<ConstantInt>(NumPatchBytesV),
1514 "gc.statepoint number of patchable bytes must be a constant integer",
1516 const int64_t NumPatchBytes =
1517 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1518 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1519 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1523 const Value *Target = CS.getArgument(2);
1524 auto *PT = dyn_cast<PointerType>(Target->getType());
1525 Assert(PT && PT->getElementType()->isFunctionTy(),
1526 "gc.statepoint callee must be of function pointer type", &CI, Target);
1527 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1529 const Value *NumCallArgsV = CS.getArgument(3);
1530 Assert(isa<ConstantInt>(NumCallArgsV),
1531 "gc.statepoint number of arguments to underlying call "
1532 "must be constant integer",
1534 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1535 Assert(NumCallArgs >= 0,
1536 "gc.statepoint number of arguments to underlying call "
1539 const int NumParams = (int)TargetFuncType->getNumParams();
1540 if (TargetFuncType->isVarArg()) {
1541 Assert(NumCallArgs >= NumParams,
1542 "gc.statepoint mismatch in number of vararg call args", &CI);
1544 // TODO: Remove this limitation
1545 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1546 "gc.statepoint doesn't support wrapping non-void "
1547 "vararg functions yet",
1550 Assert(NumCallArgs == NumParams,
1551 "gc.statepoint mismatch in number of call args", &CI);
1553 const Value *FlagsV = CS.getArgument(4);
1554 Assert(isa<ConstantInt>(FlagsV),
1555 "gc.statepoint flags must be constant integer", &CI);
1556 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1557 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1558 "unknown flag used in gc.statepoint flags argument", &CI);
1560 // Verify that the types of the call parameter arguments match
1561 // the type of the wrapped callee.
1562 for (int i = 0; i < NumParams; i++) {
1563 Type *ParamType = TargetFuncType->getParamType(i);
1564 Type *ArgType = CS.getArgument(5 + i)->getType();
1565 Assert(ArgType == ParamType,
1566 "gc.statepoint call argument does not match wrapped "
1571 const int EndCallArgsInx = 4 + NumCallArgs;
1573 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1574 Assert(isa<ConstantInt>(NumTransitionArgsV),
1575 "gc.statepoint number of transition arguments "
1576 "must be constant integer",
1578 const int NumTransitionArgs =
1579 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1580 Assert(NumTransitionArgs >= 0,
1581 "gc.statepoint number of transition arguments must be positive", &CI);
1582 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1584 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1585 Assert(isa<ConstantInt>(NumDeoptArgsV),
1586 "gc.statepoint number of deoptimization arguments "
1587 "must be constant integer",
1589 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1590 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1594 const int ExpectedNumArgs =
1595 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1596 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1597 "gc.statepoint too few arguments according to length fields", &CI);
1599 // Check that the only uses of this gc.statepoint are gc.result or
1600 // gc.relocate calls which are tied to this statepoint and thus part
1601 // of the same statepoint sequence
1602 for (const User *U : CI.users()) {
1603 const CallInst *Call = dyn_cast<const CallInst>(U);
1604 Assert(Call, "illegal use of statepoint token", &CI, U);
1605 if (!Call) continue;
1606 Assert(isGCRelocate(Call) || isGCResult(Call),
1607 "gc.result or gc.relocate are the only value uses"
1608 "of a gc.statepoint",
1610 if (isGCResult(Call)) {
1611 Assert(Call->getArgOperand(0) == &CI,
1612 "gc.result connected to wrong gc.statepoint", &CI, Call);
1613 } else if (isGCRelocate(Call)) {
1614 Assert(Call->getArgOperand(0) == &CI,
1615 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1619 // Note: It is legal for a single derived pointer to be listed multiple
1620 // times. It's non-optimal, but it is legal. It can also happen after
1621 // insertion if we strip a bitcast away.
1622 // Note: It is really tempting to check that each base is relocated and
1623 // that a derived pointer is never reused as a base pointer. This turns
1624 // out to be problematic since optimizations run after safepoint insertion
1625 // can recognize equality properties that the insertion logic doesn't know
1626 // about. See example statepoint.ll in the verifier subdirectory
1629 void Verifier::verifyFrameRecoverIndices() {
1630 for (auto &Counts : FrameEscapeInfo) {
1631 Function *F = Counts.first;
1632 unsigned EscapedObjectCount = Counts.second.first;
1633 unsigned MaxRecoveredIndex = Counts.second.second;
1634 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1635 "all indices passed to llvm.localrecover must be less than the "
1636 "number of arguments passed ot llvm.localescape in the parent "
1642 // visitFunction - Verify that a function is ok.
1644 void Verifier::visitFunction(const Function &F) {
1645 // Check function arguments.
1646 FunctionType *FT = F.getFunctionType();
1647 unsigned NumArgs = F.arg_size();
1649 Assert(Context == &F.getContext(),
1650 "Function context does not match Module context!", &F);
1652 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1653 Assert(FT->getNumParams() == NumArgs,
1654 "# formal arguments must match # of arguments for function type!", &F,
1656 Assert(F.getReturnType()->isFirstClassType() ||
1657 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1658 "Functions cannot return aggregate values!", &F);
1660 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1661 "Invalid struct return type!", &F);
1663 AttributeSet Attrs = F.getAttributes();
1665 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1666 "Attribute after last parameter!", &F);
1668 // Check function attributes.
1669 VerifyFunctionAttrs(FT, Attrs, &F);
1671 // On function declarations/definitions, we do not support the builtin
1672 // attribute. We do not check this in VerifyFunctionAttrs since that is
1673 // checking for Attributes that can/can not ever be on functions.
1674 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1675 "Attribute 'builtin' can only be applied to a callsite.", &F);
1677 // Check that this function meets the restrictions on this calling convention.
1678 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1679 // restrictions can be lifted.
1680 switch (F.getCallingConv()) {
1682 case CallingConv::C:
1684 case CallingConv::Fast:
1685 case CallingConv::Cold:
1686 case CallingConv::Intel_OCL_BI:
1687 case CallingConv::PTX_Kernel:
1688 case CallingConv::PTX_Device:
1689 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1690 "perfect forwarding!",
1695 bool isLLVMdotName = F.getName().size() >= 5 &&
1696 F.getName().substr(0, 5) == "llvm.";
1698 // Check that the argument values match the function type for this function...
1700 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1702 Assert(I->getType() == FT->getParamType(i),
1703 "Argument value does not match function argument type!", I,
1704 FT->getParamType(i));
1705 Assert(I->getType()->isFirstClassType(),
1706 "Function arguments must have first-class types!", I);
1707 if (!isLLVMdotName) {
1708 Assert(!I->getType()->isMetadataTy(),
1709 "Function takes metadata but isn't an intrinsic", I, &F);
1710 Assert(!I->getType()->isTokenTy(),
1711 "Function takes token but isn't an intrinsic", I, &F);
1716 Assert(!F.getReturnType()->isTokenTy(),
1717 "Functions returns a token but isn't an intrinsic", &F);
1719 // Get the function metadata attachments.
1720 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1721 F.getAllMetadata(MDs);
1722 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1723 VerifyFunctionMetadata(MDs);
1725 // Check validity of the personality function
1726 if (F.hasPersonalityFn()) {
1727 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1729 Assert(Per->getParent() == F.getParent(),
1730 "Referencing personality function in another module!",
1731 &F, F.getParent(), Per, Per->getParent());
1734 if (F.isMaterializable()) {
1735 // Function has a body somewhere we can't see.
1736 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1737 MDs.empty() ? nullptr : MDs.front().second);
1738 } else if (F.isDeclaration()) {
1739 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1740 "invalid linkage type for function declaration", &F);
1741 Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1742 MDs.empty() ? nullptr : MDs.front().second);
1743 Assert(!F.hasPersonalityFn(),
1744 "Function declaration shouldn't have a personality routine", &F);
1746 // Verify that this function (which has a body) is not named "llvm.*". It
1747 // is not legal to define intrinsics.
1748 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1750 // Check the entry node
1751 const BasicBlock *Entry = &F.getEntryBlock();
1752 Assert(pred_empty(Entry),
1753 "Entry block to function must not have predecessors!", Entry);
1755 // The address of the entry block cannot be taken, unless it is dead.
1756 if (Entry->hasAddressTaken()) {
1757 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1758 "blockaddress may not be used with the entry block!", Entry);
1761 // Visit metadata attachments.
1762 for (const auto &I : MDs) {
1763 // Verify that the attachment is legal.
1767 case LLVMContext::MD_dbg:
1768 Assert(isa<DISubprogram>(I.second),
1769 "function !dbg attachment must be a subprogram", &F, I.second);
1773 // Verify the metadata itself.
1774 visitMDNode(*I.second);
1778 // If this function is actually an intrinsic, verify that it is only used in
1779 // direct call/invokes, never having its "address taken".
1780 if (F.getIntrinsicID()) {
1782 if (F.hasAddressTaken(&U))
1783 Assert(0, "Invalid user of intrinsic instruction!", U);
1786 Assert(!F.hasDLLImportStorageClass() ||
1787 (F.isDeclaration() && F.hasExternalLinkage()) ||
1788 F.hasAvailableExternallyLinkage(),
1789 "Function is marked as dllimport, but not external.", &F);
1791 auto *N = F.getSubprogram();
1795 // Check that all !dbg attachments lead to back to N (or, at least, another
1796 // subprogram that describes the same function).
1798 // FIXME: Check this incrementally while visiting !dbg attachments.
1799 // FIXME: Only check when N is the canonical subprogram for F.
1800 SmallPtrSet<const MDNode *, 32> Seen;
1802 for (auto &I : BB) {
1803 // Be careful about using DILocation here since we might be dealing with
1804 // broken code (this is the Verifier after all).
1806 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1809 if (!Seen.insert(DL).second)
1812 DILocalScope *Scope = DL->getInlinedAtScope();
1813 if (Scope && !Seen.insert(Scope).second)
1816 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1818 // Scope and SP could be the same MDNode and we don't want to skip
1819 // validation in that case
1820 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
1823 // FIXME: Once N is canonical, check "SP == &N".
1824 Assert(SP->describes(&F),
1825 "!dbg attachment points at wrong subprogram for function", N, &F,
1830 // verifyBasicBlock - Verify that a basic block is well formed...
1832 void Verifier::visitBasicBlock(BasicBlock &BB) {
1833 InstsInThisBlock.clear();
1835 // Ensure that basic blocks have terminators!
1836 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1838 // Check constraints that this basic block imposes on all of the PHI nodes in
1840 if (isa<PHINode>(BB.front())) {
1841 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1842 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1843 std::sort(Preds.begin(), Preds.end());
1845 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1846 // Ensure that PHI nodes have at least one entry!
1847 Assert(PN->getNumIncomingValues() != 0,
1848 "PHI nodes must have at least one entry. If the block is dead, "
1849 "the PHI should be removed!",
1851 Assert(PN->getNumIncomingValues() == Preds.size(),
1852 "PHINode should have one entry for each predecessor of its "
1853 "parent basic block!",
1856 // Get and sort all incoming values in the PHI node...
1858 Values.reserve(PN->getNumIncomingValues());
1859 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1860 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1861 PN->getIncomingValue(i)));
1862 std::sort(Values.begin(), Values.end());
1864 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1865 // Check to make sure that if there is more than one entry for a
1866 // particular basic block in this PHI node, that the incoming values are
1869 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1870 Values[i].second == Values[i - 1].second,
1871 "PHI node has multiple entries for the same basic block with "
1872 "different incoming values!",
1873 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1875 // Check to make sure that the predecessors and PHI node entries are
1877 Assert(Values[i].first == Preds[i],
1878 "PHI node entries do not match predecessors!", PN,
1879 Values[i].first, Preds[i]);
1884 // Check that all instructions have their parent pointers set up correctly.
1887 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1891 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1892 // Ensure that terminators only exist at the end of the basic block.
1893 Assert(&I == I.getParent()->getTerminator(),
1894 "Terminator found in the middle of a basic block!", I.getParent());
1895 visitInstruction(I);
1898 void Verifier::visitBranchInst(BranchInst &BI) {
1899 if (BI.isConditional()) {
1900 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1901 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1903 visitTerminatorInst(BI);
1906 void Verifier::visitReturnInst(ReturnInst &RI) {
1907 Function *F = RI.getParent()->getParent();
1908 unsigned N = RI.getNumOperands();
1909 if (F->getReturnType()->isVoidTy())
1911 "Found return instr that returns non-void in Function of void "
1913 &RI, F->getReturnType());
1915 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1916 "Function return type does not match operand "
1917 "type of return inst!",
1918 &RI, F->getReturnType());
1920 // Check to make sure that the return value has necessary properties for
1922 visitTerminatorInst(RI);
1925 void Verifier::visitSwitchInst(SwitchInst &SI) {
1926 // Check to make sure that all of the constants in the switch instruction
1927 // have the same type as the switched-on value.
1928 Type *SwitchTy = SI.getCondition()->getType();
1929 SmallPtrSet<ConstantInt*, 32> Constants;
1930 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1931 Assert(i.getCaseValue()->getType() == SwitchTy,
1932 "Switch constants must all be same type as switch value!", &SI);
1933 Assert(Constants.insert(i.getCaseValue()).second,
1934 "Duplicate integer as switch case", &SI, i.getCaseValue());
1937 visitTerminatorInst(SI);
1940 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1941 Assert(BI.getAddress()->getType()->isPointerTy(),
1942 "Indirectbr operand must have pointer type!", &BI);
1943 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1944 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1945 "Indirectbr destinations must all have pointer type!", &BI);
1947 visitTerminatorInst(BI);
1950 void Verifier::visitSelectInst(SelectInst &SI) {
1951 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1953 "Invalid operands for select instruction!", &SI);
1955 Assert(SI.getTrueValue()->getType() == SI.getType(),
1956 "Select values must have same type as select instruction!", &SI);
1957 visitInstruction(SI);
1960 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1961 /// a pass, if any exist, it's an error.
1963 void Verifier::visitUserOp1(Instruction &I) {
1964 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1967 void Verifier::visitTruncInst(TruncInst &I) {
1968 // Get the source and destination types
1969 Type *SrcTy = I.getOperand(0)->getType();
1970 Type *DestTy = I.getType();
1972 // Get the size of the types in bits, we'll need this later
1973 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1974 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1976 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1977 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1978 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1979 "trunc source and destination must both be a vector or neither", &I);
1980 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1982 visitInstruction(I);
1985 void Verifier::visitZExtInst(ZExtInst &I) {
1986 // Get the source and destination types
1987 Type *SrcTy = I.getOperand(0)->getType();
1988 Type *DestTy = I.getType();
1990 // Get the size of the types in bits, we'll need this later
1991 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1992 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1993 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1994 "zext source and destination must both be a vector or neither", &I);
1995 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1996 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1998 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2000 visitInstruction(I);
2003 void Verifier::visitSExtInst(SExtInst &I) {
2004 // Get the source and destination types
2005 Type *SrcTy = I.getOperand(0)->getType();
2006 Type *DestTy = I.getType();
2008 // Get the size of the types in bits, we'll need this later
2009 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2010 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2012 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2013 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2014 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2015 "sext source and destination must both be a vector or neither", &I);
2016 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2018 visitInstruction(I);
2021 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2022 // Get the source and destination types
2023 Type *SrcTy = I.getOperand(0)->getType();
2024 Type *DestTy = I.getType();
2025 // Get the size of the types in bits, we'll need this later
2026 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2027 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2029 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2030 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2031 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2032 "fptrunc source and destination must both be a vector or neither", &I);
2033 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2035 visitInstruction(I);
2038 void Verifier::visitFPExtInst(FPExtInst &I) {
2039 // Get the source and destination types
2040 Type *SrcTy = I.getOperand(0)->getType();
2041 Type *DestTy = I.getType();
2043 // Get the size of the types in bits, we'll need this later
2044 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2045 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2047 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2048 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2049 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2050 "fpext source and destination must both be a vector or neither", &I);
2051 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2053 visitInstruction(I);
2056 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2057 // Get the source and destination types
2058 Type *SrcTy = I.getOperand(0)->getType();
2059 Type *DestTy = I.getType();
2061 bool SrcVec = SrcTy->isVectorTy();
2062 bool DstVec = DestTy->isVectorTy();
2064 Assert(SrcVec == DstVec,
2065 "UIToFP source and dest must both be vector or scalar", &I);
2066 Assert(SrcTy->isIntOrIntVectorTy(),
2067 "UIToFP source must be integer or integer vector", &I);
2068 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2071 if (SrcVec && DstVec)
2072 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2073 cast<VectorType>(DestTy)->getNumElements(),
2074 "UIToFP source and dest vector length mismatch", &I);
2076 visitInstruction(I);
2079 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2080 // Get the source and destination types
2081 Type *SrcTy = I.getOperand(0)->getType();
2082 Type *DestTy = I.getType();
2084 bool SrcVec = SrcTy->isVectorTy();
2085 bool DstVec = DestTy->isVectorTy();
2087 Assert(SrcVec == DstVec,
2088 "SIToFP source and dest must both be vector or scalar", &I);
2089 Assert(SrcTy->isIntOrIntVectorTy(),
2090 "SIToFP source must be integer or integer vector", &I);
2091 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2094 if (SrcVec && DstVec)
2095 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2096 cast<VectorType>(DestTy)->getNumElements(),
2097 "SIToFP source and dest vector length mismatch", &I);
2099 visitInstruction(I);
2102 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2103 // Get the source and destination types
2104 Type *SrcTy = I.getOperand(0)->getType();
2105 Type *DestTy = I.getType();
2107 bool SrcVec = SrcTy->isVectorTy();
2108 bool DstVec = DestTy->isVectorTy();
2110 Assert(SrcVec == DstVec,
2111 "FPToUI source and dest must both be vector or scalar", &I);
2112 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2114 Assert(DestTy->isIntOrIntVectorTy(),
2115 "FPToUI result must be integer or integer vector", &I);
2117 if (SrcVec && DstVec)
2118 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2119 cast<VectorType>(DestTy)->getNumElements(),
2120 "FPToUI source and dest vector length mismatch", &I);
2122 visitInstruction(I);
2125 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2126 // Get the source and destination types
2127 Type *SrcTy = I.getOperand(0)->getType();
2128 Type *DestTy = I.getType();
2130 bool SrcVec = SrcTy->isVectorTy();
2131 bool DstVec = DestTy->isVectorTy();
2133 Assert(SrcVec == DstVec,
2134 "FPToSI source and dest must both be vector or scalar", &I);
2135 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2137 Assert(DestTy->isIntOrIntVectorTy(),
2138 "FPToSI result must be integer or integer vector", &I);
2140 if (SrcVec && DstVec)
2141 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2142 cast<VectorType>(DestTy)->getNumElements(),
2143 "FPToSI source and dest vector length mismatch", &I);
2145 visitInstruction(I);
2148 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2149 // Get the source and destination types
2150 Type *SrcTy = I.getOperand(0)->getType();
2151 Type *DestTy = I.getType();
2153 Assert(SrcTy->getScalarType()->isPointerTy(),
2154 "PtrToInt source must be pointer", &I);
2155 Assert(DestTy->getScalarType()->isIntegerTy(),
2156 "PtrToInt result must be integral", &I);
2157 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2160 if (SrcTy->isVectorTy()) {
2161 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2162 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2163 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2164 "PtrToInt Vector width mismatch", &I);
2167 visitInstruction(I);
2170 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2171 // Get the source and destination types
2172 Type *SrcTy = I.getOperand(0)->getType();
2173 Type *DestTy = I.getType();
2175 Assert(SrcTy->getScalarType()->isIntegerTy(),
2176 "IntToPtr source must be an integral", &I);
2177 Assert(DestTy->getScalarType()->isPointerTy(),
2178 "IntToPtr result must be a pointer", &I);
2179 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2181 if (SrcTy->isVectorTy()) {
2182 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2183 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2184 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2185 "IntToPtr Vector width mismatch", &I);
2187 visitInstruction(I);
2190 void Verifier::visitBitCastInst(BitCastInst &I) {
2192 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2193 "Invalid bitcast", &I);
2194 visitInstruction(I);
2197 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2198 Type *SrcTy = I.getOperand(0)->getType();
2199 Type *DestTy = I.getType();
2201 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2203 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2205 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2206 "AddrSpaceCast must be between different address spaces", &I);
2207 if (SrcTy->isVectorTy())
2208 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2209 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2210 visitInstruction(I);
2213 /// visitPHINode - Ensure that a PHI node is well formed.
2215 void Verifier::visitPHINode(PHINode &PN) {
2216 // Ensure that the PHI nodes are all grouped together at the top of the block.
2217 // This can be tested by checking whether the instruction before this is
2218 // either nonexistent (because this is begin()) or is a PHI node. If not,
2219 // then there is some other instruction before a PHI.
2220 Assert(&PN == &PN.getParent()->front() ||
2221 isa<PHINode>(--BasicBlock::iterator(&PN)),
2222 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2224 // Check that a PHI doesn't yield a Token.
2225 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2227 // Check that all of the values of the PHI node have the same type as the
2228 // result, and that the incoming blocks are really basic blocks.
2229 for (Value *IncValue : PN.incoming_values()) {
2230 Assert(PN.getType() == IncValue->getType(),
2231 "PHI node operands are not the same type as the result!", &PN);
2234 // All other PHI node constraints are checked in the visitBasicBlock method.
2236 visitInstruction(PN);
2239 void Verifier::VerifyCallSite(CallSite CS) {
2240 Instruction *I = CS.getInstruction();
2242 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2243 "Called function must be a pointer!", I);
2244 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2246 Assert(FPTy->getElementType()->isFunctionTy(),
2247 "Called function is not pointer to function type!", I);
2249 Assert(FPTy->getElementType() == CS.getFunctionType(),
2250 "Called function is not the same type as the call!", I);
2252 FunctionType *FTy = CS.getFunctionType();
2254 // Verify that the correct number of arguments are being passed
2255 if (FTy->isVarArg())
2256 Assert(CS.arg_size() >= FTy->getNumParams(),
2257 "Called function requires more parameters than were provided!", I);
2259 Assert(CS.arg_size() == FTy->getNumParams(),
2260 "Incorrect number of arguments passed to called function!", I);
2262 // Verify that all arguments to the call match the function type.
2263 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2264 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2265 "Call parameter type does not match function signature!",
2266 CS.getArgument(i), FTy->getParamType(i), I);
2268 AttributeSet Attrs = CS.getAttributes();
2270 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2271 "Attribute after last parameter!", I);
2273 // Verify call attributes.
2274 VerifyFunctionAttrs(FTy, Attrs, I);
2276 // Conservatively check the inalloca argument.
2277 // We have a bug if we can find that there is an underlying alloca without
2279 if (CS.hasInAllocaArgument()) {
2280 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2281 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2282 Assert(AI->isUsedWithInAlloca(),
2283 "inalloca argument for call has mismatched alloca", AI, I);
2286 if (FTy->isVarArg()) {
2287 // FIXME? is 'nest' even legal here?
2288 bool SawNest = false;
2289 bool SawReturned = false;
2291 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2292 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2294 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2298 // Check attributes on the varargs part.
2299 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2300 Type *Ty = CS.getArgument(Idx-1)->getType();
2301 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2303 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2304 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2308 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2309 Assert(!SawReturned, "More than one parameter has attribute returned!",
2311 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2312 "Incompatible argument and return types for 'returned' "
2318 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2319 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2321 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2322 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2326 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2327 if (CS.getCalledFunction() == nullptr ||
2328 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2329 for (Type *ParamTy : FTy->params()) {
2330 Assert(!ParamTy->isMetadataTy(),
2331 "Function has metadata parameter but isn't an intrinsic", I);
2332 Assert(!ParamTy->isTokenTy(),
2333 "Function has token parameter but isn't an intrinsic", I);
2337 // Verify that indirect calls don't return tokens.
2338 if (CS.getCalledFunction() == nullptr)
2339 Assert(!FTy->getReturnType()->isTokenTy(),
2340 "Return type cannot be token for indirect call!");
2342 if (Function *F = CS.getCalledFunction())
2343 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2344 visitIntrinsicCallSite(ID, CS);
2346 // Verify that a callsite has at most one "deopt" operand bundle.
2347 bool FoundDeoptBundle = false;
2348 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2349 if (CS.getOperandBundleAt(i).getTagID() == LLVMContext::OB_deopt) {
2350 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2351 FoundDeoptBundle = true;
2355 visitInstruction(*I);
2358 /// Two types are "congruent" if they are identical, or if they are both pointer
2359 /// types with different pointee types and the same address space.
2360 static bool isTypeCongruent(Type *L, Type *R) {
2363 PointerType *PL = dyn_cast<PointerType>(L);
2364 PointerType *PR = dyn_cast<PointerType>(R);
2367 return PL->getAddressSpace() == PR->getAddressSpace();
2370 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2371 static const Attribute::AttrKind ABIAttrs[] = {
2372 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2373 Attribute::InReg, Attribute::Returned};
2375 for (auto AK : ABIAttrs) {
2376 if (Attrs.hasAttribute(I + 1, AK))
2377 Copy.addAttribute(AK);
2379 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2380 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2384 void Verifier::verifyMustTailCall(CallInst &CI) {
2385 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2387 // - The caller and callee prototypes must match. Pointer types of
2388 // parameters or return types may differ in pointee type, but not
2390 Function *F = CI.getParent()->getParent();
2391 FunctionType *CallerTy = F->getFunctionType();
2392 FunctionType *CalleeTy = CI.getFunctionType();
2393 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2394 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2395 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2396 "cannot guarantee tail call due to mismatched varargs", &CI);
2397 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2398 "cannot guarantee tail call due to mismatched return types", &CI);
2399 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2401 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2402 "cannot guarantee tail call due to mismatched parameter types", &CI);
2405 // - The calling conventions of the caller and callee must match.
2406 Assert(F->getCallingConv() == CI.getCallingConv(),
2407 "cannot guarantee tail call due to mismatched calling conv", &CI);
2409 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2410 // returned, and inalloca, must match.
2411 AttributeSet CallerAttrs = F->getAttributes();
2412 AttributeSet CalleeAttrs = CI.getAttributes();
2413 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2414 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2415 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2416 Assert(CallerABIAttrs == CalleeABIAttrs,
2417 "cannot guarantee tail call due to mismatched ABI impacting "
2418 "function attributes",
2419 &CI, CI.getOperand(I));
2422 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2423 // or a pointer bitcast followed by a ret instruction.
2424 // - The ret instruction must return the (possibly bitcasted) value
2425 // produced by the call or void.
2426 Value *RetVal = &CI;
2427 Instruction *Next = CI.getNextNode();
2429 // Handle the optional bitcast.
2430 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2431 Assert(BI->getOperand(0) == RetVal,
2432 "bitcast following musttail call must use the call", BI);
2434 Next = BI->getNextNode();
2437 // Check the return.
2438 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2439 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2441 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2442 "musttail call result must be returned", Ret);
2445 void Verifier::visitCallInst(CallInst &CI) {
2446 VerifyCallSite(&CI);
2448 if (CI.isMustTailCall())
2449 verifyMustTailCall(CI);
2452 void Verifier::visitInvokeInst(InvokeInst &II) {
2453 VerifyCallSite(&II);
2455 // Verify that the first non-PHI instruction of the unwind destination is an
2456 // exception handling instruction.
2458 II.getUnwindDest()->isEHPad(),
2459 "The unwind destination does not have an exception handling instruction!",
2462 visitTerminatorInst(II);
2465 /// visitBinaryOperator - Check that both arguments to the binary operator are
2466 /// of the same type!
2468 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2469 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2470 "Both operands to a binary operator are not of the same type!", &B);
2472 switch (B.getOpcode()) {
2473 // Check that integer arithmetic operators are only used with
2474 // integral operands.
2475 case Instruction::Add:
2476 case Instruction::Sub:
2477 case Instruction::Mul:
2478 case Instruction::SDiv:
2479 case Instruction::UDiv:
2480 case Instruction::SRem:
2481 case Instruction::URem:
2482 Assert(B.getType()->isIntOrIntVectorTy(),
2483 "Integer arithmetic operators only work with integral types!", &B);
2484 Assert(B.getType() == B.getOperand(0)->getType(),
2485 "Integer arithmetic operators must have same type "
2486 "for operands and result!",
2489 // Check that floating-point arithmetic operators are only used with
2490 // floating-point operands.
2491 case Instruction::FAdd:
2492 case Instruction::FSub:
2493 case Instruction::FMul:
2494 case Instruction::FDiv:
2495 case Instruction::FRem:
2496 Assert(B.getType()->isFPOrFPVectorTy(),
2497 "Floating-point arithmetic operators only work with "
2498 "floating-point types!",
2500 Assert(B.getType() == B.getOperand(0)->getType(),
2501 "Floating-point arithmetic operators must have same type "
2502 "for operands and result!",
2505 // Check that logical operators are only used with integral operands.
2506 case Instruction::And:
2507 case Instruction::Or:
2508 case Instruction::Xor:
2509 Assert(B.getType()->isIntOrIntVectorTy(),
2510 "Logical operators only work with integral types!", &B);
2511 Assert(B.getType() == B.getOperand(0)->getType(),
2512 "Logical operators must have same type for operands and result!",
2515 case Instruction::Shl:
2516 case Instruction::LShr:
2517 case Instruction::AShr:
2518 Assert(B.getType()->isIntOrIntVectorTy(),
2519 "Shifts only work with integral types!", &B);
2520 Assert(B.getType() == B.getOperand(0)->getType(),
2521 "Shift return type must be same as operands!", &B);
2524 llvm_unreachable("Unknown BinaryOperator opcode!");
2527 visitInstruction(B);
2530 void Verifier::visitICmpInst(ICmpInst &IC) {
2531 // Check that the operands are the same type
2532 Type *Op0Ty = IC.getOperand(0)->getType();
2533 Type *Op1Ty = IC.getOperand(1)->getType();
2534 Assert(Op0Ty == Op1Ty,
2535 "Both operands to ICmp instruction are not of the same type!", &IC);
2536 // Check that the operands are the right type
2537 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2538 "Invalid operand types for ICmp instruction", &IC);
2539 // Check that the predicate is valid.
2540 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2541 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2542 "Invalid predicate in ICmp instruction!", &IC);
2544 visitInstruction(IC);
2547 void Verifier::visitFCmpInst(FCmpInst &FC) {
2548 // Check that the operands are the same type
2549 Type *Op0Ty = FC.getOperand(0)->getType();
2550 Type *Op1Ty = FC.getOperand(1)->getType();
2551 Assert(Op0Ty == Op1Ty,
2552 "Both operands to FCmp instruction are not of the same type!", &FC);
2553 // Check that the operands are the right type
2554 Assert(Op0Ty->isFPOrFPVectorTy(),
2555 "Invalid operand types for FCmp instruction", &FC);
2556 // Check that the predicate is valid.
2557 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2558 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2559 "Invalid predicate in FCmp instruction!", &FC);
2561 visitInstruction(FC);
2564 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2566 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2567 "Invalid extractelement operands!", &EI);
2568 visitInstruction(EI);
2571 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2572 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2574 "Invalid insertelement operands!", &IE);
2575 visitInstruction(IE);
2578 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2579 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2581 "Invalid shufflevector operands!", &SV);
2582 visitInstruction(SV);
2585 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2586 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2588 Assert(isa<PointerType>(TargetTy),
2589 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2590 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2591 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2593 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2594 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2596 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2597 GEP.getResultElementType() == ElTy,
2598 "GEP is not of right type for indices!", &GEP, ElTy);
2600 if (GEP.getType()->isVectorTy()) {
2601 // Additional checks for vector GEPs.
2602 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2603 if (GEP.getPointerOperandType()->isVectorTy())
2604 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2605 "Vector GEP result width doesn't match operand's", &GEP);
2606 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2607 Type *IndexTy = Idxs[i]->getType();
2608 if (IndexTy->isVectorTy()) {
2609 unsigned IndexWidth = IndexTy->getVectorNumElements();
2610 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2612 Assert(IndexTy->getScalarType()->isIntegerTy(),
2613 "All GEP indices should be of integer type");
2616 visitInstruction(GEP);
2619 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2620 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2623 void Verifier::visitRangeMetadata(Instruction& I,
2624 MDNode* Range, Type* Ty) {
2626 Range == I.getMetadata(LLVMContext::MD_range) &&
2627 "precondition violation");
2629 unsigned NumOperands = Range->getNumOperands();
2630 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2631 unsigned NumRanges = NumOperands / 2;
2632 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2634 ConstantRange LastRange(1); // Dummy initial value
2635 for (unsigned i = 0; i < NumRanges; ++i) {
2637 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2638 Assert(Low, "The lower limit must be an integer!", Low);
2640 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2641 Assert(High, "The upper limit must be an integer!", High);
2642 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2643 "Range types must match instruction type!", &I);
2645 APInt HighV = High->getValue();
2646 APInt LowV = Low->getValue();
2647 ConstantRange CurRange(LowV, HighV);
2648 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2649 "Range must not be empty!", Range);
2651 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2652 "Intervals are overlapping", Range);
2653 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2655 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2658 LastRange = ConstantRange(LowV, HighV);
2660 if (NumRanges > 2) {
2662 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2664 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2665 ConstantRange FirstRange(FirstLow, FirstHigh);
2666 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2667 "Intervals are overlapping", Range);
2668 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2673 void Verifier::visitLoadInst(LoadInst &LI) {
2674 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2675 Assert(PTy, "Load operand must be a pointer.", &LI);
2676 Type *ElTy = LI.getType();
2677 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2678 "huge alignment values are unsupported", &LI);
2679 if (LI.isAtomic()) {
2680 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2681 "Load cannot have Release ordering", &LI);
2682 Assert(LI.getAlignment() != 0,
2683 "Atomic load must specify explicit alignment", &LI);
2684 if (!ElTy->isPointerTy()) {
2685 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2687 unsigned Size = ElTy->getPrimitiveSizeInBits();
2688 Assert(Size >= 8 && !(Size & (Size - 1)),
2689 "atomic load operand must be power-of-two byte-sized integer", &LI,
2693 Assert(LI.getSynchScope() == CrossThread,
2694 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2697 visitInstruction(LI);
2700 void Verifier::visitStoreInst(StoreInst &SI) {
2701 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2702 Assert(PTy, "Store operand must be a pointer.", &SI);
2703 Type *ElTy = PTy->getElementType();
2704 Assert(ElTy == SI.getOperand(0)->getType(),
2705 "Stored value type does not match pointer operand type!", &SI, ElTy);
2706 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2707 "huge alignment values are unsupported", &SI);
2708 if (SI.isAtomic()) {
2709 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2710 "Store cannot have Acquire ordering", &SI);
2711 Assert(SI.getAlignment() != 0,
2712 "Atomic store must specify explicit alignment", &SI);
2713 if (!ElTy->isPointerTy()) {
2714 Assert(ElTy->isIntegerTy(),
2715 "atomic store operand must have integer type!", &SI, ElTy);
2716 unsigned Size = ElTy->getPrimitiveSizeInBits();
2717 Assert(Size >= 8 && !(Size & (Size - 1)),
2718 "atomic store operand must be power-of-two byte-sized integer",
2722 Assert(SI.getSynchScope() == CrossThread,
2723 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2725 visitInstruction(SI);
2728 void Verifier::visitAllocaInst(AllocaInst &AI) {
2729 SmallPtrSet<Type*, 4> Visited;
2730 PointerType *PTy = AI.getType();
2731 Assert(PTy->getAddressSpace() == 0,
2732 "Allocation instruction pointer not in the generic address space!",
2734 Assert(AI.getAllocatedType()->isSized(&Visited),
2735 "Cannot allocate unsized type", &AI);
2736 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2737 "Alloca array size must have integer type", &AI);
2738 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2739 "huge alignment values are unsupported", &AI);
2741 visitInstruction(AI);
2744 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2746 // FIXME: more conditions???
2747 Assert(CXI.getSuccessOrdering() != NotAtomic,
2748 "cmpxchg instructions must be atomic.", &CXI);
2749 Assert(CXI.getFailureOrdering() != NotAtomic,
2750 "cmpxchg instructions must be atomic.", &CXI);
2751 Assert(CXI.getSuccessOrdering() != Unordered,
2752 "cmpxchg instructions cannot be unordered.", &CXI);
2753 Assert(CXI.getFailureOrdering() != Unordered,
2754 "cmpxchg instructions cannot be unordered.", &CXI);
2755 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2756 "cmpxchg instructions be at least as constrained on success as fail",
2758 Assert(CXI.getFailureOrdering() != Release &&
2759 CXI.getFailureOrdering() != AcquireRelease,
2760 "cmpxchg failure ordering cannot include release semantics", &CXI);
2762 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2763 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2764 Type *ElTy = PTy->getElementType();
2765 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2767 unsigned Size = ElTy->getPrimitiveSizeInBits();
2768 Assert(Size >= 8 && !(Size & (Size - 1)),
2769 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2770 Assert(ElTy == CXI.getOperand(1)->getType(),
2771 "Expected value type does not match pointer operand type!", &CXI,
2773 Assert(ElTy == CXI.getOperand(2)->getType(),
2774 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2775 visitInstruction(CXI);
2778 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2779 Assert(RMWI.getOrdering() != NotAtomic,
2780 "atomicrmw instructions must be atomic.", &RMWI);
2781 Assert(RMWI.getOrdering() != Unordered,
2782 "atomicrmw instructions cannot be unordered.", &RMWI);
2783 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2784 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2785 Type *ElTy = PTy->getElementType();
2786 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2788 unsigned Size = ElTy->getPrimitiveSizeInBits();
2789 Assert(Size >= 8 && !(Size & (Size - 1)),
2790 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2792 Assert(ElTy == RMWI.getOperand(1)->getType(),
2793 "Argument value type does not match pointer operand type!", &RMWI,
2795 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2796 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2797 "Invalid binary operation!", &RMWI);
2798 visitInstruction(RMWI);
2801 void Verifier::visitFenceInst(FenceInst &FI) {
2802 const AtomicOrdering Ordering = FI.getOrdering();
2803 Assert(Ordering == Acquire || Ordering == Release ||
2804 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2805 "fence instructions may only have "
2806 "acquire, release, acq_rel, or seq_cst ordering.",
2808 visitInstruction(FI);
2811 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2812 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2813 EVI.getIndices()) == EVI.getType(),
2814 "Invalid ExtractValueInst operands!", &EVI);
2816 visitInstruction(EVI);
2819 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2820 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2821 IVI.getIndices()) ==
2822 IVI.getOperand(1)->getType(),
2823 "Invalid InsertValueInst operands!", &IVI);
2825 visitInstruction(IVI);
2828 void Verifier::visitEHPadPredecessors(Instruction &I) {
2829 assert(I.isEHPad());
2831 BasicBlock *BB = I.getParent();
2832 Function *F = BB->getParent();
2834 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2836 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2837 // The landingpad instruction defines its parent as a landing pad block. The
2838 // landing pad block may be branched to only by the unwind edge of an
2840 for (BasicBlock *PredBB : predecessors(BB)) {
2841 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2842 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2843 "Block containing LandingPadInst must be jumped to "
2844 "only by the unwind edge of an invoke.",
2850 for (BasicBlock *PredBB : predecessors(BB)) {
2851 TerminatorInst *TI = PredBB->getTerminator();
2852 if (auto *II = dyn_cast<InvokeInst>(TI))
2853 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
2854 "EH pad must be jumped to via an unwind edge", &I, II);
2855 else if (auto *CPI = dyn_cast<CatchPadInst>(TI))
2856 Assert(CPI->getUnwindDest() == BB && CPI->getNormalDest() != BB,
2857 "EH pad must be jumped to via an unwind edge", &I, CPI);
2858 else if (isa<CatchEndPadInst>(TI))
2860 else if (isa<CleanupReturnInst>(TI))
2862 else if (isa<CleanupEndPadInst>(TI))
2864 else if (isa<TerminatePadInst>(TI))
2867 Assert(false, "EH pad must be jumped to via an unwind edge", &I, TI);
2871 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2872 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2874 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2875 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2877 visitEHPadPredecessors(LPI);
2879 if (!LandingPadResultTy)
2880 LandingPadResultTy = LPI.getType();
2882 Assert(LandingPadResultTy == LPI.getType(),
2883 "The landingpad instruction should have a consistent result type "
2884 "inside a function.",
2887 Function *F = LPI.getParent()->getParent();
2888 Assert(F->hasPersonalityFn(),
2889 "LandingPadInst needs to be in a function with a personality.", &LPI);
2891 // The landingpad instruction must be the first non-PHI instruction in the
2893 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2894 "LandingPadInst not the first non-PHI instruction in the block.",
2897 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2898 Constant *Clause = LPI.getClause(i);
2899 if (LPI.isCatch(i)) {
2900 Assert(isa<PointerType>(Clause->getType()),
2901 "Catch operand does not have pointer type!", &LPI);
2903 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2904 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2905 "Filter operand is not an array of constants!", &LPI);
2909 visitInstruction(LPI);
2912 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
2913 visitEHPadPredecessors(CPI);
2915 BasicBlock *BB = CPI.getParent();
2916 Function *F = BB->getParent();
2917 Assert(F->hasPersonalityFn(),
2918 "CatchPadInst needs to be in a function with a personality.", &CPI);
2920 // The catchpad instruction must be the first non-PHI instruction in the
2922 Assert(BB->getFirstNonPHI() == &CPI,
2923 "CatchPadInst not the first non-PHI instruction in the block.",
2926 if (!BB->getSinglePredecessor())
2927 for (BasicBlock *PredBB : predecessors(BB)) {
2928 Assert(!isa<CatchPadInst>(PredBB->getTerminator()),
2929 "CatchPadInst with CatchPadInst predecessor cannot have any other "
2934 BasicBlock *UnwindDest = CPI.getUnwindDest();
2935 Instruction *I = UnwindDest->getFirstNonPHI();
2937 isa<CatchPadInst>(I) || isa<CatchEndPadInst>(I),
2938 "CatchPadInst must unwind to a CatchPadInst or a CatchEndPadInst.",
2941 visitTerminatorInst(CPI);
2944 void Verifier::visitCatchEndPadInst(CatchEndPadInst &CEPI) {
2945 visitEHPadPredecessors(CEPI);
2947 BasicBlock *BB = CEPI.getParent();
2948 Function *F = BB->getParent();
2949 Assert(F->hasPersonalityFn(),
2950 "CatchEndPadInst needs to be in a function with a personality.",
2953 // The catchendpad instruction must be the first non-PHI instruction in the
2955 Assert(BB->getFirstNonPHI() == &CEPI,
2956 "CatchEndPadInst not the first non-PHI instruction in the block.",
2959 unsigned CatchPadsSeen = 0;
2960 for (BasicBlock *PredBB : predecessors(BB))
2961 if (isa<CatchPadInst>(PredBB->getTerminator()))
2964 Assert(CatchPadsSeen <= 1, "CatchEndPadInst must have no more than one "
2965 "CatchPadInst predecessor.",
2968 if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
2969 Instruction *I = UnwindDest->getFirstNonPHI();
2971 I->isEHPad() && !isa<LandingPadInst>(I),
2972 "CatchEndPad must unwind to an EH block which is not a landingpad.",
2976 visitTerminatorInst(CEPI);
2979 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
2980 visitEHPadPredecessors(CPI);
2982 BasicBlock *BB = CPI.getParent();
2984 Function *F = BB->getParent();
2985 Assert(F->hasPersonalityFn(),
2986 "CleanupPadInst needs to be in a function with a personality.", &CPI);
2988 // The cleanuppad instruction must be the first non-PHI instruction in the
2990 Assert(BB->getFirstNonPHI() == &CPI,
2991 "CleanupPadInst not the first non-PHI instruction in the block.",
2994 User *FirstUser = nullptr;
2995 BasicBlock *FirstUnwindDest = nullptr;
2996 for (User *U : CPI.users()) {
2997 BasicBlock *UnwindDest;
2998 if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(U)) {
2999 UnwindDest = CRI->getUnwindDest();
3001 UnwindDest = cast<CleanupEndPadInst>(U)->getUnwindDest();
3006 FirstUnwindDest = UnwindDest;
3008 Assert(UnwindDest == FirstUnwindDest,
3009 "Cleanuprets/cleanupendpads from the same cleanuppad must "
3010 "have the same unwind destination",
3015 visitInstruction(CPI);
3018 void Verifier::visitCleanupEndPadInst(CleanupEndPadInst &CEPI) {
3019 visitEHPadPredecessors(CEPI);
3021 BasicBlock *BB = CEPI.getParent();
3022 Function *F = BB->getParent();
3023 Assert(F->hasPersonalityFn(),
3024 "CleanupEndPadInst needs to be in a function with a personality.",
3027 // The cleanupendpad instruction must be the first non-PHI instruction in the
3029 Assert(BB->getFirstNonPHI() == &CEPI,
3030 "CleanupEndPadInst not the first non-PHI instruction in the block.",
3033 if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
3034 Instruction *I = UnwindDest->getFirstNonPHI();
3036 I->isEHPad() && !isa<LandingPadInst>(I),
3037 "CleanupEndPad must unwind to an EH block which is not a landingpad.",
3041 visitTerminatorInst(CEPI);
3044 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3045 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3046 Instruction *I = UnwindDest->getFirstNonPHI();
3047 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3048 "CleanupReturnInst must unwind to an EH block which is not a "
3053 visitTerminatorInst(CRI);
3056 void Verifier::visitTerminatePadInst(TerminatePadInst &TPI) {
3057 visitEHPadPredecessors(TPI);
3059 BasicBlock *BB = TPI.getParent();
3060 Function *F = BB->getParent();
3061 Assert(F->hasPersonalityFn(),
3062 "TerminatePadInst needs to be in a function with a personality.",
3065 // The terminatepad instruction must be the first non-PHI instruction in the
3067 Assert(BB->getFirstNonPHI() == &TPI,
3068 "TerminatePadInst not the first non-PHI instruction in the block.",
3071 if (BasicBlock *UnwindDest = TPI.getUnwindDest()) {
3072 Instruction *I = UnwindDest->getFirstNonPHI();
3073 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3074 "TerminatePadInst must unwind to an EH block which is not a "
3079 visitTerminatorInst(TPI);
3082 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3083 Instruction *Op = cast<Instruction>(I.getOperand(i));
3084 // If the we have an invalid invoke, don't try to compute the dominance.
3085 // We already reject it in the invoke specific checks and the dominance
3086 // computation doesn't handle multiple edges.
3087 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3088 if (II->getNormalDest() == II->getUnwindDest())
3092 const Use &U = I.getOperandUse(i);
3093 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3094 "Instruction does not dominate all uses!", Op, &I);
3097 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3098 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3099 "apply only to pointer types", &I);
3100 Assert(isa<LoadInst>(I),
3101 "dereferenceable, dereferenceable_or_null apply only to load"
3102 " instructions, use attributes for calls or invokes", &I);
3103 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3104 "take one operand!", &I);
3105 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3106 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3107 "dereferenceable_or_null metadata value must be an i64!", &I);
3110 /// verifyInstruction - Verify that an instruction is well formed.
3112 void Verifier::visitInstruction(Instruction &I) {
3113 BasicBlock *BB = I.getParent();
3114 Assert(BB, "Instruction not embedded in basic block!", &I);
3116 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
3117 for (User *U : I.users()) {
3118 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3119 "Only PHI nodes may reference their own value!", &I);
3123 // Check that void typed values don't have names
3124 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3125 "Instruction has a name, but provides a void value!", &I);
3127 // Check that the return value of the instruction is either void or a legal
3129 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3130 "Instruction returns a non-scalar type!", &I);
3132 // Check that the instruction doesn't produce metadata. Calls are already
3133 // checked against the callee type.
3134 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3135 "Invalid use of metadata!", &I);
3137 // Check that all uses of the instruction, if they are instructions
3138 // themselves, actually have parent basic blocks. If the use is not an
3139 // instruction, it is an error!
3140 for (Use &U : I.uses()) {
3141 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3142 Assert(Used->getParent() != nullptr,
3143 "Instruction referencing"
3144 " instruction not embedded in a basic block!",
3147 CheckFailed("Use of instruction is not an instruction!", U);
3152 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3153 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3155 // Check to make sure that only first-class-values are operands to
3157 if (!I.getOperand(i)->getType()->isFirstClassType()) {
3158 Assert(0, "Instruction operands must be first-class values!", &I);
3161 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3162 // Check to make sure that the "address of" an intrinsic function is never
3165 !F->isIntrinsic() ||
3166 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3167 "Cannot take the address of an intrinsic!", &I);
3169 !F->isIntrinsic() || isa<CallInst>(I) ||
3170 F->getIntrinsicID() == Intrinsic::donothing ||
3171 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3172 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3173 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3174 "Cannot invoke an intrinsinc other than"
3175 " donothing or patchpoint",
3177 Assert(F->getParent() == M, "Referencing function in another module!",
3178 &I, M, F, F->getParent());
3179 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3180 Assert(OpBB->getParent() == BB->getParent(),
3181 "Referring to a basic block in another function!", &I);
3182 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3183 Assert(OpArg->getParent() == BB->getParent(),
3184 "Referring to an argument in another function!", &I);
3185 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3186 Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent());
3187 } else if (isa<Instruction>(I.getOperand(i))) {
3188 verifyDominatesUse(I, i);
3189 } else if (isa<InlineAsm>(I.getOperand(i))) {
3190 Assert((i + 1 == e && isa<CallInst>(I)) ||
3191 (i + 3 == e && isa<InvokeInst>(I)),
3192 "Cannot take the address of an inline asm!", &I);
3193 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3194 if (CE->getType()->isPtrOrPtrVectorTy()) {
3195 // If we have a ConstantExpr pointer, we need to see if it came from an
3196 // illegal bitcast (inttoptr <constant int> )
3197 SmallVector<const ConstantExpr *, 4> Stack;
3198 SmallPtrSet<const ConstantExpr *, 4> Visited;
3199 Stack.push_back(CE);
3201 while (!Stack.empty()) {
3202 const ConstantExpr *V = Stack.pop_back_val();
3203 if (!Visited.insert(V).second)
3206 VerifyConstantExprBitcastType(V);
3208 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
3209 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
3210 Stack.push_back(Op);
3217 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3218 Assert(I.getType()->isFPOrFPVectorTy(),
3219 "fpmath requires a floating point result!", &I);
3220 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3221 if (ConstantFP *CFP0 =
3222 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3223 APFloat Accuracy = CFP0->getValueAPF();
3224 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3225 "fpmath accuracy not a positive number!", &I);
3227 Assert(false, "invalid fpmath accuracy!", &I);
3231 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3232 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3233 "Ranges are only for loads, calls and invokes!", &I);
3234 visitRangeMetadata(I, Range, I.getType());
3237 if (I.getMetadata(LLVMContext::MD_nonnull)) {
3238 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3240 Assert(isa<LoadInst>(I),
3241 "nonnull applies only to load instructions, use attributes"
3242 " for calls or invokes",
3246 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3247 visitDereferenceableMetadata(I, MD);
3249 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3250 visitDereferenceableMetadata(I, MD);
3252 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3253 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3255 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3256 "use attributes for calls or invokes", &I);
3257 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3258 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3259 Assert(CI && CI->getType()->isIntegerTy(64),
3260 "align metadata value must be an i64!", &I);
3261 uint64_t Align = CI->getZExtValue();
3262 Assert(isPowerOf2_64(Align),
3263 "align metadata value must be a power of 2!", &I);
3264 Assert(Align <= Value::MaximumAlignment,
3265 "alignment is larger that implementation defined limit", &I);
3268 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3269 Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3273 InstsInThisBlock.insert(&I);
3276 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3277 /// intrinsic argument or return value) matches the type constraints specified
3278 /// by the .td file (e.g. an "any integer" argument really is an integer).
3280 /// This return true on error but does not print a message.
3281 bool Verifier::VerifyIntrinsicType(Type *Ty,
3282 ArrayRef<Intrinsic::IITDescriptor> &Infos,
3283 SmallVectorImpl<Type*> &ArgTys) {
3284 using namespace Intrinsic;
3286 // If we ran out of descriptors, there are too many arguments.
3287 if (Infos.empty()) return true;
3288 IITDescriptor D = Infos.front();
3289 Infos = Infos.slice(1);
3292 case IITDescriptor::Void: return !Ty->isVoidTy();
3293 case IITDescriptor::VarArg: return true;
3294 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
3295 case IITDescriptor::Token: return !Ty->isTokenTy();
3296 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3297 case IITDescriptor::Half: return !Ty->isHalfTy();
3298 case IITDescriptor::Float: return !Ty->isFloatTy();
3299 case IITDescriptor::Double: return !Ty->isDoubleTy();
3300 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3301 case IITDescriptor::Vector: {
3302 VectorType *VT = dyn_cast<VectorType>(Ty);
3303 return !VT || VT->getNumElements() != D.Vector_Width ||
3304 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3306 case IITDescriptor::Pointer: {
3307 PointerType *PT = dyn_cast<PointerType>(Ty);
3308 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3309 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3312 case IITDescriptor::Struct: {
3313 StructType *ST = dyn_cast<StructType>(Ty);
3314 if (!ST || ST->getNumElements() != D.Struct_NumElements)
3317 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3318 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3323 case IITDescriptor::Argument:
3324 // Two cases here - If this is the second occurrence of an argument, verify
3325 // that the later instance matches the previous instance.
3326 if (D.getArgumentNumber() < ArgTys.size())
3327 return Ty != ArgTys[D.getArgumentNumber()];
3329 // Otherwise, if this is the first instance of an argument, record it and
3330 // verify the "Any" kind.
3331 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3332 ArgTys.push_back(Ty);
3334 switch (D.getArgumentKind()) {
3335 case IITDescriptor::AK_Any: return false; // Success
3336 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3337 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
3338 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
3339 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3341 llvm_unreachable("all argument kinds not covered");
3343 case IITDescriptor::ExtendArgument: {
3344 // This may only be used when referring to a previous vector argument.
3345 if (D.getArgumentNumber() >= ArgTys.size())
3348 Type *NewTy = ArgTys[D.getArgumentNumber()];
3349 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3350 NewTy = VectorType::getExtendedElementVectorType(VTy);
3351 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3352 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3358 case IITDescriptor::TruncArgument: {
3359 // This may only be used when referring to a previous vector argument.
3360 if (D.getArgumentNumber() >= ArgTys.size())
3363 Type *NewTy = ArgTys[D.getArgumentNumber()];
3364 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3365 NewTy = VectorType::getTruncatedElementVectorType(VTy);
3366 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3367 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3373 case IITDescriptor::HalfVecArgument:
3374 // This may only be used when referring to a previous vector argument.
3375 return D.getArgumentNumber() >= ArgTys.size() ||
3376 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3377 VectorType::getHalfElementsVectorType(
3378 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3379 case IITDescriptor::SameVecWidthArgument: {
3380 if (D.getArgumentNumber() >= ArgTys.size())
3382 VectorType * ReferenceType =
3383 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3384 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3385 if (!ThisArgType || !ReferenceType ||
3386 (ReferenceType->getVectorNumElements() !=
3387 ThisArgType->getVectorNumElements()))
3389 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3392 case IITDescriptor::PtrToArgument: {
3393 if (D.getArgumentNumber() >= ArgTys.size())
3395 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3396 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3397 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3399 case IITDescriptor::VecOfPtrsToElt: {
3400 if (D.getArgumentNumber() >= ArgTys.size())
3402 VectorType * ReferenceType =
3403 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3404 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3405 if (!ThisArgVecTy || !ReferenceType ||
3406 (ReferenceType->getVectorNumElements() !=
3407 ThisArgVecTy->getVectorNumElements()))
3409 PointerType *ThisArgEltTy =
3410 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3413 return ThisArgEltTy->getElementType() !=
3414 ReferenceType->getVectorElementType();
3417 llvm_unreachable("unhandled");
3420 /// \brief Verify if the intrinsic has variable arguments.
3421 /// This method is intended to be called after all the fixed arguments have been
3424 /// This method returns true on error and does not print an error message.
3426 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3427 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3428 using namespace Intrinsic;
3430 // If there are no descriptors left, then it can't be a vararg.
3434 // There should be only one descriptor remaining at this point.
3435 if (Infos.size() != 1)
3438 // Check and verify the descriptor.
3439 IITDescriptor D = Infos.front();
3440 Infos = Infos.slice(1);
3441 if (D.Kind == IITDescriptor::VarArg)
3447 /// Allow intrinsics to be verified in different ways.
3448 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3449 Function *IF = CS.getCalledFunction();
3450 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3453 // Verify that the intrinsic prototype lines up with what the .td files
3455 FunctionType *IFTy = IF->getFunctionType();
3456 bool IsVarArg = IFTy->isVarArg();
3458 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3459 getIntrinsicInfoTableEntries(ID, Table);
3460 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3462 SmallVector<Type *, 4> ArgTys;
3463 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3464 "Intrinsic has incorrect return type!", IF);
3465 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3466 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3467 "Intrinsic has incorrect argument type!", IF);
3469 // Verify if the intrinsic call matches the vararg property.
3471 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3472 "Intrinsic was not defined with variable arguments!", IF);
3474 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3475 "Callsite was not defined with variable arguments!", IF);
3477 // All descriptors should be absorbed by now.
3478 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3480 // Now that we have the intrinsic ID and the actual argument types (and we
3481 // know they are legal for the intrinsic!) get the intrinsic name through the
3482 // usual means. This allows us to verify the mangling of argument types into
3484 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3485 Assert(ExpectedName == IF->getName(),
3486 "Intrinsic name not mangled correctly for type arguments! "
3491 // If the intrinsic takes MDNode arguments, verify that they are either global
3492 // or are local to *this* function.
3493 for (Value *V : CS.args())
3494 if (auto *MD = dyn_cast<MetadataAsValue>(V))
3495 visitMetadataAsValue(*MD, CS.getCaller());
3500 case Intrinsic::ctlz: // llvm.ctlz
3501 case Intrinsic::cttz: // llvm.cttz
3502 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3503 "is_zero_undef argument of bit counting intrinsics must be a "
3507 case Intrinsic::dbg_declare: // llvm.dbg.declare
3508 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3509 "invalid llvm.dbg.declare intrinsic call 1", CS);
3510 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3512 case Intrinsic::dbg_value: // llvm.dbg.value
3513 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3515 case Intrinsic::memcpy:
3516 case Intrinsic::memmove:
3517 case Intrinsic::memset: {
3518 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3520 "alignment argument of memory intrinsics must be a constant int",
3522 const APInt &AlignVal = AlignCI->getValue();
3523 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3524 "alignment argument of memory intrinsics must be a power of 2", CS);
3525 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3526 "isvolatile argument of memory intrinsics must be a constant int",
3530 case Intrinsic::gcroot:
3531 case Intrinsic::gcwrite:
3532 case Intrinsic::gcread:
3533 if (ID == Intrinsic::gcroot) {
3535 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3536 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3537 Assert(isa<Constant>(CS.getArgOperand(1)),
3538 "llvm.gcroot parameter #2 must be a constant.", CS);
3539 if (!AI->getAllocatedType()->isPointerTy()) {
3540 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3541 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3542 "or argument #2 must be a non-null constant.",
3547 Assert(CS.getParent()->getParent()->hasGC(),
3548 "Enclosing function does not use GC.", CS);
3550 case Intrinsic::init_trampoline:
3551 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3552 "llvm.init_trampoline parameter #2 must resolve to a function.",
3555 case Intrinsic::prefetch:
3556 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3557 isa<ConstantInt>(CS.getArgOperand(2)) &&
3558 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3559 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3560 "invalid arguments to llvm.prefetch", CS);
3562 case Intrinsic::stackprotector:
3563 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3564 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3566 case Intrinsic::lifetime_start:
3567 case Intrinsic::lifetime_end:
3568 case Intrinsic::invariant_start:
3569 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3570 "size argument of memory use markers must be a constant integer",
3573 case Intrinsic::invariant_end:
3574 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3575 "llvm.invariant.end parameter #2 must be a constant integer", CS);
3578 case Intrinsic::localescape: {
3579 BasicBlock *BB = CS.getParent();
3580 Assert(BB == &BB->getParent()->front(),
3581 "llvm.localescape used outside of entry block", CS);
3582 Assert(!SawFrameEscape,
3583 "multiple calls to llvm.localescape in one function", CS);
3584 for (Value *Arg : CS.args()) {
3585 if (isa<ConstantPointerNull>(Arg))
3586 continue; // Null values are allowed as placeholders.
3587 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3588 Assert(AI && AI->isStaticAlloca(),
3589 "llvm.localescape only accepts static allocas", CS);
3591 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3592 SawFrameEscape = true;
3595 case Intrinsic::localrecover: {
3596 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3597 Function *Fn = dyn_cast<Function>(FnArg);
3598 Assert(Fn && !Fn->isDeclaration(),
3599 "llvm.localrecover first "
3600 "argument must be function defined in this module",
3602 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3603 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3605 auto &Entry = FrameEscapeInfo[Fn];
3606 Entry.second = unsigned(
3607 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3611 case Intrinsic::experimental_gc_statepoint:
3612 Assert(!CS.isInlineAsm(),
3613 "gc.statepoint support for inline assembly unimplemented", CS);
3614 Assert(CS.getParent()->getParent()->hasGC(),
3615 "Enclosing function does not use GC.", CS);
3617 VerifyStatepoint(CS);
3619 case Intrinsic::experimental_gc_result_int:
3620 case Intrinsic::experimental_gc_result_float:
3621 case Intrinsic::experimental_gc_result_ptr:
3622 case Intrinsic::experimental_gc_result: {
3623 Assert(CS.getParent()->getParent()->hasGC(),
3624 "Enclosing function does not use GC.", CS);
3625 // Are we tied to a statepoint properly?
3626 CallSite StatepointCS(CS.getArgOperand(0));
3627 const Function *StatepointFn =
3628 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3629 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3630 StatepointFn->getIntrinsicID() ==
3631 Intrinsic::experimental_gc_statepoint,
3632 "gc.result operand #1 must be from a statepoint", CS,
3633 CS.getArgOperand(0));
3635 // Assert that result type matches wrapped callee.
3636 const Value *Target = StatepointCS.getArgument(2);
3637 auto *PT = cast<PointerType>(Target->getType());
3638 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3639 Assert(CS.getType() == TargetFuncType->getReturnType(),
3640 "gc.result result type does not match wrapped callee", CS);
3643 case Intrinsic::experimental_gc_relocate: {
3644 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3646 // Check that this relocate is correctly tied to the statepoint
3648 // This is case for relocate on the unwinding path of an invoke statepoint
3649 if (ExtractValueInst *ExtractValue =
3650 dyn_cast<ExtractValueInst>(CS.getArgOperand(0))) {
3651 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3652 "gc relocate on unwind path incorrectly linked to the statepoint",
3655 const BasicBlock *InvokeBB =
3656 ExtractValue->getParent()->getUniquePredecessor();
3658 // Landingpad relocates should have only one predecessor with invoke
3659 // statepoint terminator
3660 Assert(InvokeBB, "safepoints should have unique landingpads",
3661 ExtractValue->getParent());
3662 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3664 Assert(isStatepoint(InvokeBB->getTerminator()),
3665 "gc relocate should be linked to a statepoint", InvokeBB);
3668 // In all other cases relocate should be tied to the statepoint directly.
3669 // This covers relocates on a normal return path of invoke statepoint and
3670 // relocates of a call statepoint
3671 auto Token = CS.getArgOperand(0);
3672 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3673 "gc relocate is incorrectly tied to the statepoint", CS, Token);
3676 // Verify rest of the relocate arguments
3678 GCRelocateOperands Ops(CS);
3679 ImmutableCallSite StatepointCS(Ops.getStatepoint());
3681 // Both the base and derived must be piped through the safepoint
3682 Value* Base = CS.getArgOperand(1);
3683 Assert(isa<ConstantInt>(Base),
3684 "gc.relocate operand #2 must be integer offset", CS);
3686 Value* Derived = CS.getArgOperand(2);
3687 Assert(isa<ConstantInt>(Derived),
3688 "gc.relocate operand #3 must be integer offset", CS);
3690 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3691 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3693 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3694 "gc.relocate: statepoint base index out of bounds", CS);
3695 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3696 "gc.relocate: statepoint derived index out of bounds", CS);
3698 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3699 // section of the statepoint's argument
3700 Assert(StatepointCS.arg_size() > 0,
3701 "gc.statepoint: insufficient arguments");
3702 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3703 "gc.statement: number of call arguments must be constant integer");
3704 const unsigned NumCallArgs =
3705 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3706 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3707 "gc.statepoint: mismatch in number of call arguments");
3708 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3709 "gc.statepoint: number of transition arguments must be "
3710 "a constant integer");
3711 const int NumTransitionArgs =
3712 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3714 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3715 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3716 "gc.statepoint: number of deoptimization arguments must be "
3717 "a constant integer");
3718 const int NumDeoptArgs =
3719 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3720 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3721 const int GCParamArgsEnd = StatepointCS.arg_size();
3722 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3723 "gc.relocate: statepoint base index doesn't fall within the "
3724 "'gc parameters' section of the statepoint call",
3726 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3727 "gc.relocate: statepoint derived index doesn't fall within the "
3728 "'gc parameters' section of the statepoint call",
3731 // Relocated value must be a pointer type, but gc_relocate does not need to return the
3732 // same pointer type as the relocated pointer. It can be casted to the correct type later
3733 // if it's desired. However, they must have the same address space.
3734 GCRelocateOperands Operands(CS);
3735 Assert(Operands.getDerivedPtr()->getType()->isPointerTy(),
3736 "gc.relocate: relocated value must be a gc pointer", CS);
3738 // gc_relocate return type must be a pointer type, and is verified earlier in
3739 // VerifyIntrinsicType().
3740 Assert(cast<PointerType>(CS.getType())->getAddressSpace() ==
3741 cast<PointerType>(Operands.getDerivedPtr()->getType())->getAddressSpace(),
3742 "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3745 case Intrinsic::eh_exceptioncode:
3746 case Intrinsic::eh_exceptionpointer: {
3747 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3748 "eh.exceptionpointer argument must be a catchpad", CS);
3754 /// \brief Carefully grab the subprogram from a local scope.
3756 /// This carefully grabs the subprogram from a local scope, avoiding the
3757 /// built-in assertions that would typically fire.
3758 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3762 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3765 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3766 return getSubprogram(LB->getRawScope());
3768 // Just return null; broken scope chains are checked elsewhere.
3769 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3773 template <class DbgIntrinsicTy>
3774 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3775 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3776 Assert(isa<ValueAsMetadata>(MD) ||
3777 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3778 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3779 Assert(isa<DILocalVariable>(DII.getRawVariable()),
3780 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3781 DII.getRawVariable());
3782 Assert(isa<DIExpression>(DII.getRawExpression()),
3783 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3784 DII.getRawExpression());
3786 // Ignore broken !dbg attachments; they're checked elsewhere.
3787 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3788 if (!isa<DILocation>(N))
3791 BasicBlock *BB = DII.getParent();
3792 Function *F = BB ? BB->getParent() : nullptr;
3794 // The scopes for variables and !dbg attachments must agree.
3795 DILocalVariable *Var = DII.getVariable();
3796 DILocation *Loc = DII.getDebugLoc();
3797 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3800 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3801 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3802 if (!VarSP || !LocSP)
3803 return; // Broken scope chains are checked elsewhere.
3805 Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3806 " variable and !dbg attachment",
3807 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3808 Loc->getScope()->getSubprogram());
3811 template <class MapTy>
3812 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3813 // Be careful of broken types (checked elsewhere).
3814 const Metadata *RawType = V.getRawType();
3816 // Try to get the size directly.
3817 if (auto *T = dyn_cast<DIType>(RawType))
3818 if (uint64_t Size = T->getSizeInBits())
3821 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3822 // Look at the base type.
3823 RawType = DT->getRawBaseType();
3827 if (auto *S = dyn_cast<MDString>(RawType)) {
3828 // Don't error on missing types (checked elsewhere).
3829 RawType = Map.lookup(S);
3833 // Missing type or size.
3841 template <class MapTy>
3842 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3843 const MapTy &TypeRefs) {
3846 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3847 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
3848 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
3850 auto *DDI = cast<DbgDeclareInst>(&I);
3851 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
3852 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
3855 // We don't know whether this intrinsic verified correctly.
3856 if (!V || !E || !E->isValid())
3859 // Nothing to do if this isn't a bit piece expression.
3860 if (!E->isBitPiece())
3863 // The frontend helps out GDB by emitting the members of local anonymous
3864 // unions as artificial local variables with shared storage. When SROA splits
3865 // the storage for artificial local variables that are smaller than the entire
3866 // union, the overhang piece will be outside of the allotted space for the
3867 // variable and this check fails.
3868 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
3869 if (V->isArtificial())
3872 // If there's no size, the type is broken, but that should be checked
3874 uint64_t VarSize = getVariableSize(*V, TypeRefs);
3878 unsigned PieceSize = E->getBitPieceSize();
3879 unsigned PieceOffset = E->getBitPieceOffset();
3880 Assert(PieceSize + PieceOffset <= VarSize,
3881 "piece is larger than or outside of variable", &I, V, E);
3882 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3885 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3886 // This is in its own function so we get an error for each bad type ref (not
3888 Assert(false, "unresolved type ref", S, N);
3891 void Verifier::verifyTypeRefs() {
3892 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3896 // Visit all the compile units again to map the type references.
3897 SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
3898 for (auto *CU : CUs->operands())
3899 if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
3900 for (DIType *Op : Ts)
3901 if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
3902 if (auto *S = T->getRawIdentifier()) {
3903 UnresolvedTypeRefs.erase(S);
3904 TypeRefs.insert(std::make_pair(S, T));
3907 // Verify debug info intrinsic bit piece expressions. This needs a second
3908 // pass through the intructions, since we haven't built TypeRefs yet when
3909 // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
3910 // later/now would queue up some that could be later deleted.
3911 for (const Function &F : *M)
3912 for (const BasicBlock &BB : F)
3913 for (const Instruction &I : BB)
3914 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
3915 verifyBitPieceExpression(*DII, TypeRefs);
3917 // Return early if all typerefs were resolved.
3918 if (UnresolvedTypeRefs.empty())
3921 // Sort the unresolved references by name so the output is deterministic.
3922 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3923 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3924 UnresolvedTypeRefs.end());
3925 std::sort(Unresolved.begin(), Unresolved.end(),
3926 [](const TypeRef &LHS, const TypeRef &RHS) {
3927 return LHS.first->getString() < RHS.first->getString();
3930 // Visit the unresolved refs (printing out the errors).
3931 for (const TypeRef &TR : Unresolved)
3932 visitUnresolvedTypeRef(TR.first, TR.second);
3935 //===----------------------------------------------------------------------===//
3936 // Implement the public interfaces to this file...
3937 //===----------------------------------------------------------------------===//
3939 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3940 Function &F = const_cast<Function &>(f);
3941 assert(!F.isDeclaration() && "Cannot verify external functions");
3943 raw_null_ostream NullStr;
3944 Verifier V(OS ? *OS : NullStr);
3946 // Note that this function's return value is inverted from what you would
3947 // expect of a function called "verify".
3948 return !V.verify(F);
3951 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3952 raw_null_ostream NullStr;
3953 Verifier V(OS ? *OS : NullStr);
3955 bool Broken = false;
3956 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3957 if (!I->isDeclaration() && !I->isMaterializable())
3958 Broken |= !V.verify(*I);
3960 // Note that this function's return value is inverted from what you would
3961 // expect of a function called "verify".
3962 return !V.verify(M) || Broken;
3966 struct VerifierLegacyPass : public FunctionPass {
3972 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3973 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3975 explicit VerifierLegacyPass(bool FatalErrors)
3976 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3977 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3980 bool runOnFunction(Function &F) override {
3981 if (!V.verify(F) && FatalErrors)
3982 report_fatal_error("Broken function found, compilation aborted!");
3987 bool doFinalization(Module &M) override {
3988 if (!V.verify(M) && FatalErrors)
3989 report_fatal_error("Broken module found, compilation aborted!");
3994 void getAnalysisUsage(AnalysisUsage &AU) const override {
3995 AU.setPreservesAll();
4000 char VerifierLegacyPass::ID = 0;
4001 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
4003 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
4004 return new VerifierLegacyPass(FatalErrors);
4007 PreservedAnalyses VerifierPass::run(Module &M) {
4008 if (verifyModule(M, &dbgs()) && FatalErrors)
4009 report_fatal_error("Broken module found, compilation aborted!");
4011 return PreservedAnalyses::all();
4014 PreservedAnalyses VerifierPass::run(Function &F) {
4015 if (verifyFunction(F, &dbgs()) && FatalErrors)
4016 report_fatal_error("Broken function found, compilation aborted!");
4018 return PreservedAnalyses::all();