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 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
91 explicit VerifierSupport(raw_ostream &OS)
92 : OS(OS), M(nullptr), Broken(false) {}
95 void Write(const Value *V) {
98 if (isa<Instruction>(V)) {
101 V->printAsOperand(OS, true, M);
106 void Write(const Metadata *MD) {
113 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
117 void Write(const NamedMDNode *NMD) {
124 void Write(Type *T) {
130 void Write(const Comdat *C) {
136 template <typename T1, typename... Ts>
137 void WriteTs(const T1 &V1, const Ts &... Vs) {
142 template <typename... Ts> void WriteTs() {}
145 /// \brief A check failed, so printout out the condition and the message.
147 /// This provides a nice place to put a breakpoint if you want to see why
148 /// something is not correct.
149 void CheckFailed(const Twine &Message) {
150 OS << Message << '\n';
154 /// \brief A check failed (with values to print).
156 /// This calls the Message-only version so that the above is easier to set a
158 template <typename T1, typename... Ts>
159 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
160 CheckFailed(Message);
165 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
166 friend class InstVisitor<Verifier>;
168 LLVMContext *Context;
171 /// \brief When verifying a basic block, keep track of all of the
172 /// instructions we have seen so far.
174 /// This allows us to do efficient dominance checks for the case when an
175 /// instruction has an operand that is an instruction in the same block.
176 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
178 /// \brief Keep track of the metadata nodes that have been checked already.
179 SmallPtrSet<const Metadata *, 32> MDNodes;
181 /// \brief Track unresolved string-based type references.
182 SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
184 /// \brief Track queue of bit piece expressions to verify.
185 SmallVector<const DbgInfoIntrinsic *, 32> QueuedBitPieceExpressions;
187 /// \brief The personality function referenced by the LandingPadInsts.
188 /// All LandingPadInsts within the same function must use the same
189 /// personality function.
190 const Value *PersonalityFn;
192 /// \brief Whether we've seen a call to @llvm.frameescape in this function
196 /// Stores the count of how many objects were passed to llvm.frameescape for a
197 /// given function and the largest index passed to llvm.framerecover.
198 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
201 explicit Verifier(raw_ostream &OS)
202 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
203 SawFrameEscape(false) {}
205 bool verify(const Function &F) {
207 Context = &M->getContext();
209 // First ensure the function is well-enough formed to compute dominance
212 OS << "Function '" << F.getName()
213 << "' does not contain an entry block!\n";
216 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
217 if (I->empty() || !I->back().isTerminator()) {
218 OS << "Basic Block in function '" << F.getName()
219 << "' does not have terminator!\n";
220 I->printAsOperand(OS, true);
226 // Now directly compute a dominance tree. We don't rely on the pass
227 // manager to provide this as it isolates us from a potentially
228 // out-of-date dominator tree and makes it significantly more complex to
229 // run this code outside of a pass manager.
230 // FIXME: It's really gross that we have to cast away constness here.
231 DT.recalculate(const_cast<Function &>(F));
234 // FIXME: We strip const here because the inst visitor strips const.
235 visit(const_cast<Function &>(F));
236 InstsInThisBlock.clear();
237 PersonalityFn = nullptr;
238 SawFrameEscape = false;
243 bool verify(const Module &M) {
245 Context = &M.getContext();
248 // Scan through, checking all of the external function's linkage now...
249 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
250 visitGlobalValue(*I);
252 // Check to make sure function prototypes are okay.
253 if (I->isDeclaration())
257 // Now that we've visited every function, verify that we never asked to
258 // recover a frame index that wasn't escaped.
259 verifyFrameRecoverIndices();
261 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
263 visitGlobalVariable(*I);
265 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
267 visitGlobalAlias(*I);
269 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
270 E = M.named_metadata_end();
272 visitNamedMDNode(*I);
274 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
275 visitComdat(SMEC.getValue());
278 visitModuleIdents(M);
280 // Verify type referneces last.
287 // Verification methods...
288 void visitGlobalValue(const GlobalValue &GV);
289 void visitGlobalVariable(const GlobalVariable &GV);
290 void visitGlobalAlias(const GlobalAlias &GA);
291 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
292 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
293 const GlobalAlias &A, const Constant &C);
294 void visitNamedMDNode(const NamedMDNode &NMD);
295 void visitMDNode(const MDNode &MD);
296 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
297 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
298 void visitComdat(const Comdat &C);
299 void visitModuleIdents(const Module &M);
300 void visitModuleFlags(const Module &M);
301 void visitModuleFlag(const MDNode *Op,
302 DenseMap<const MDString *, const MDNode *> &SeenIDs,
303 SmallVectorImpl<const MDNode *> &Requirements);
304 void visitFunction(const Function &F);
305 void visitBasicBlock(BasicBlock &BB);
306 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
308 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
309 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
310 #include "llvm/IR/Metadata.def"
311 void visitMDScope(const MDScope &N);
312 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
313 void visitMDVariable(const MDVariable &N);
314 void visitMDLexicalBlockBase(const MDLexicalBlockBase &N);
315 void visitMDTemplateParameter(const MDTemplateParameter &N);
317 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
319 /// \brief Check for a valid string-based type reference.
321 /// Checks if \c MD is a string-based type reference. If it is, keeps track
322 /// of it (and its user, \c N) for error messages later.
323 bool isValidUUID(const MDNode &N, const Metadata *MD);
325 /// \brief Check for a valid type reference.
327 /// Checks for subclasses of \a MDType, or \a isValidUUID().
328 bool isTypeRef(const MDNode &N, const Metadata *MD);
330 /// \brief Check for a valid scope reference.
332 /// Checks for subclasses of \a MDScope, or \a isValidUUID().
333 bool isScopeRef(const MDNode &N, const Metadata *MD);
335 /// \brief Check for a valid debug info reference.
337 /// Checks for subclasses of \a DebugNode, or \a isValidUUID().
338 bool isDIRef(const MDNode &N, const Metadata *MD);
340 // InstVisitor overrides...
341 using InstVisitor<Verifier>::visit;
342 void visit(Instruction &I);
344 void visitTruncInst(TruncInst &I);
345 void visitZExtInst(ZExtInst &I);
346 void visitSExtInst(SExtInst &I);
347 void visitFPTruncInst(FPTruncInst &I);
348 void visitFPExtInst(FPExtInst &I);
349 void visitFPToUIInst(FPToUIInst &I);
350 void visitFPToSIInst(FPToSIInst &I);
351 void visitUIToFPInst(UIToFPInst &I);
352 void visitSIToFPInst(SIToFPInst &I);
353 void visitIntToPtrInst(IntToPtrInst &I);
354 void visitPtrToIntInst(PtrToIntInst &I);
355 void visitBitCastInst(BitCastInst &I);
356 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
357 void visitPHINode(PHINode &PN);
358 void visitBinaryOperator(BinaryOperator &B);
359 void visitICmpInst(ICmpInst &IC);
360 void visitFCmpInst(FCmpInst &FC);
361 void visitExtractElementInst(ExtractElementInst &EI);
362 void visitInsertElementInst(InsertElementInst &EI);
363 void visitShuffleVectorInst(ShuffleVectorInst &EI);
364 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
365 void visitCallInst(CallInst &CI);
366 void visitInvokeInst(InvokeInst &II);
367 void visitGetElementPtrInst(GetElementPtrInst &GEP);
368 void visitLoadInst(LoadInst &LI);
369 void visitStoreInst(StoreInst &SI);
370 void verifyDominatesUse(Instruction &I, unsigned i);
371 void visitInstruction(Instruction &I);
372 void visitTerminatorInst(TerminatorInst &I);
373 void visitBranchInst(BranchInst &BI);
374 void visitReturnInst(ReturnInst &RI);
375 void visitSwitchInst(SwitchInst &SI);
376 void visitIndirectBrInst(IndirectBrInst &BI);
377 void visitSelectInst(SelectInst &SI);
378 void visitUserOp1(Instruction &I);
379 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
380 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
381 template <class DbgIntrinsicTy>
382 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
383 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
384 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
385 void visitFenceInst(FenceInst &FI);
386 void visitAllocaInst(AllocaInst &AI);
387 void visitExtractValueInst(ExtractValueInst &EVI);
388 void visitInsertValueInst(InsertValueInst &IVI);
389 void visitLandingPadInst(LandingPadInst &LPI);
391 void VerifyCallSite(CallSite CS);
392 void verifyMustTailCall(CallInst &CI);
393 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
394 unsigned ArgNo, std::string &Suffix);
395 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
396 SmallVectorImpl<Type *> &ArgTys);
397 bool VerifyIntrinsicIsVarArg(bool isVarArg,
398 ArrayRef<Intrinsic::IITDescriptor> &Infos);
399 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
400 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
402 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
403 bool isReturnValue, const Value *V);
404 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
407 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
408 void VerifyStatepoint(ImmutableCallSite CS);
409 void verifyFrameRecoverIndices();
411 // Module-level debug info verification...
412 void verifyTypeRefs();
413 template <class MapTy>
414 void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
415 const MapTy &TypeRefs);
416 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
418 } // End anonymous namespace
420 // Assert - We know that cond should be true, if not print an error message.
421 #define Assert(C, ...) \
422 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
424 void Verifier::visit(Instruction &I) {
425 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
426 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
427 InstVisitor<Verifier>::visit(I);
431 void Verifier::visitGlobalValue(const GlobalValue &GV) {
432 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
433 GV.hasExternalWeakLinkage(),
434 "Global is external, but doesn't have external or weak linkage!", &GV);
436 Assert(GV.getAlignment() <= Value::MaximumAlignment,
437 "huge alignment values are unsupported", &GV);
438 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
439 "Only global variables can have appending linkage!", &GV);
441 if (GV.hasAppendingLinkage()) {
442 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
443 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
444 "Only global arrays can have appending linkage!", GVar);
448 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
449 if (GV.hasInitializer()) {
450 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
451 "Global variable initializer type does not match global "
455 // If the global has common linkage, it must have a zero initializer and
456 // cannot be constant.
457 if (GV.hasCommonLinkage()) {
458 Assert(GV.getInitializer()->isNullValue(),
459 "'common' global must have a zero initializer!", &GV);
460 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
462 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
465 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
466 "invalid linkage type for global declaration", &GV);
469 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
470 GV.getName() == "llvm.global_dtors")) {
471 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
472 "invalid linkage for intrinsic global variable", &GV);
473 // Don't worry about emitting an error for it not being an array,
474 // visitGlobalValue will complain on appending non-array.
475 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
476 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
477 PointerType *FuncPtrTy =
478 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
479 // FIXME: Reject the 2-field form in LLVM 4.0.
481 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
482 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
483 STy->getTypeAtIndex(1) == FuncPtrTy,
484 "wrong type for intrinsic global variable", &GV);
485 if (STy->getNumElements() == 3) {
486 Type *ETy = STy->getTypeAtIndex(2);
487 Assert(ETy->isPointerTy() &&
488 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
489 "wrong type for intrinsic global variable", &GV);
494 if (GV.hasName() && (GV.getName() == "llvm.used" ||
495 GV.getName() == "llvm.compiler.used")) {
496 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
497 "invalid linkage for intrinsic global variable", &GV);
498 Type *GVType = GV.getType()->getElementType();
499 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
500 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
501 Assert(PTy, "wrong type for intrinsic global variable", &GV);
502 if (GV.hasInitializer()) {
503 const Constant *Init = GV.getInitializer();
504 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
505 Assert(InitArray, "wrong initalizer for intrinsic global variable",
507 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
508 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
509 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
511 "invalid llvm.used member", V);
512 Assert(V->hasName(), "members of llvm.used must be named", V);
518 Assert(!GV.hasDLLImportStorageClass() ||
519 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
520 GV.hasAvailableExternallyLinkage(),
521 "Global is marked as dllimport, but not external", &GV);
523 if (!GV.hasInitializer()) {
524 visitGlobalValue(GV);
528 // Walk any aggregate initializers looking for bitcasts between address spaces
529 SmallPtrSet<const Value *, 4> Visited;
530 SmallVector<const Value *, 4> WorkStack;
531 WorkStack.push_back(cast<Value>(GV.getInitializer()));
533 while (!WorkStack.empty()) {
534 const Value *V = WorkStack.pop_back_val();
535 if (!Visited.insert(V).second)
538 if (const User *U = dyn_cast<User>(V)) {
539 WorkStack.append(U->op_begin(), U->op_end());
542 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
543 VerifyConstantExprBitcastType(CE);
549 visitGlobalValue(GV);
552 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
553 SmallPtrSet<const GlobalAlias*, 4> Visited;
555 visitAliaseeSubExpr(Visited, GA, C);
558 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
559 const GlobalAlias &GA, const Constant &C) {
560 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
561 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
563 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
564 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
566 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
569 // Only continue verifying subexpressions of GlobalAliases.
570 // Do not recurse into global initializers.
575 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
576 VerifyConstantExprBitcastType(CE);
578 for (const Use &U : C.operands()) {
580 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
581 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
582 else if (const auto *C2 = dyn_cast<Constant>(V))
583 visitAliaseeSubExpr(Visited, GA, *C2);
587 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
588 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
589 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
590 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
591 "weak_odr, or external linkage!",
593 const Constant *Aliasee = GA.getAliasee();
594 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
595 Assert(GA.getType() == Aliasee->getType(),
596 "Alias and aliasee types should match!", &GA);
598 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
599 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
601 visitAliaseeSubExpr(GA, *Aliasee);
603 visitGlobalValue(GA);
606 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
607 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
608 MDNode *MD = NMD.getOperand(i);
610 if (NMD.getName() == "llvm.dbg.cu") {
611 Assert(MD && isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
621 void Verifier::visitMDNode(const MDNode &MD) {
622 // Only visit each node once. Metadata can be mutually recursive, so this
623 // avoids infinite recursion here, as well as being an optimization.
624 if (!MDNodes.insert(&MD).second)
627 switch (MD.getMetadataID()) {
629 llvm_unreachable("Invalid MDNode subclass");
630 case Metadata::MDTupleKind:
632 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
633 case Metadata::CLASS##Kind: \
634 visit##CLASS(cast<CLASS>(MD)); \
636 #include "llvm/IR/Metadata.def"
639 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
640 Metadata *Op = MD.getOperand(i);
643 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
645 if (auto *N = dyn_cast<MDNode>(Op)) {
649 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
650 visitValueAsMetadata(*V, nullptr);
655 // Check these last, so we diagnose problems in operands first.
656 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
657 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
660 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
661 Assert(MD.getValue(), "Expected valid value", &MD);
662 Assert(!MD.getValue()->getType()->isMetadataTy(),
663 "Unexpected metadata round-trip through values", &MD, MD.getValue());
665 auto *L = dyn_cast<LocalAsMetadata>(&MD);
669 Assert(F, "function-local metadata used outside a function", L);
671 // If this was an instruction, bb, or argument, verify that it is in the
672 // function that we expect.
673 Function *ActualF = nullptr;
674 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
675 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
676 ActualF = I->getParent()->getParent();
677 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
678 ActualF = BB->getParent();
679 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
680 ActualF = A->getParent();
681 assert(ActualF && "Unimplemented function local metadata case!");
683 Assert(ActualF == F, "function-local metadata used in wrong function", L);
686 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
687 Metadata *MD = MDV.getMetadata();
688 if (auto *N = dyn_cast<MDNode>(MD)) {
693 // Only visit each node once. Metadata can be mutually recursive, so this
694 // avoids infinite recursion here, as well as being an optimization.
695 if (!MDNodes.insert(MD).second)
698 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
699 visitValueAsMetadata(*V, F);
702 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
703 auto *S = dyn_cast<MDString>(MD);
706 if (S->getString().empty())
709 // Keep track of names of types referenced via UUID so we can check that they
711 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
715 /// \brief Check if a value can be a reference to a type.
716 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
717 return !MD || isValidUUID(N, MD) || isa<MDType>(MD);
720 /// \brief Check if a value can be a ScopeRef.
721 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
722 return !MD || isValidUUID(N, MD) || isa<MDScope>(MD);
725 /// \brief Check if a value can be a debug info ref.
726 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
727 return !MD || isValidUUID(N, MD) || isa<DebugNode>(MD);
731 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
732 for (Metadata *MD : N.operands()) {
745 bool isValidMetadataArray(const MDTuple &N) {
746 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
750 bool isValidMetadataNullArray(const MDTuple &N) {
751 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
754 void Verifier::visitMDLocation(const MDLocation &N) {
755 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
756 "location requires a valid scope", &N, N.getRawScope());
757 if (auto *IA = N.getRawInlinedAt())
758 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
761 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
762 Assert(N.getTag(), "invalid tag", &N);
765 void Verifier::visitMDScope(const MDScope &N) {
766 if (auto *F = N.getRawFile())
767 Assert(isa<MDFile>(F), "invalid file", &N, F);
770 void Verifier::visitMDSubrange(const MDSubrange &N) {
771 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
772 Assert(N.getCount() >= -1, "invalid subrange count", &N);
775 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
776 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
779 void Verifier::visitMDBasicType(const MDBasicType &N) {
780 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
781 N.getTag() == dwarf::DW_TAG_unspecified_type,
785 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
786 // Common scope checks.
789 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
790 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
793 // FIXME: Sink this into the subclass verifies.
794 if (!N.getFile() || N.getFile()->getFilename().empty()) {
795 // Check whether the filename is allowed to be empty.
796 uint16_t Tag = N.getTag();
798 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
799 Tag == dwarf::DW_TAG_pointer_type ||
800 Tag == dwarf::DW_TAG_ptr_to_member_type ||
801 Tag == dwarf::DW_TAG_reference_type ||
802 Tag == dwarf::DW_TAG_rvalue_reference_type ||
803 Tag == dwarf::DW_TAG_restrict_type ||
804 Tag == dwarf::DW_TAG_array_type ||
805 Tag == dwarf::DW_TAG_enumeration_type ||
806 Tag == dwarf::DW_TAG_subroutine_type ||
807 Tag == dwarf::DW_TAG_inheritance || Tag == dwarf::DW_TAG_friend ||
808 Tag == dwarf::DW_TAG_structure_type ||
809 Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef,
810 "derived/composite type requires a filename", &N, N.getFile());
814 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
815 // Common derived type checks.
816 visitMDDerivedTypeBase(N);
818 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
819 N.getTag() == dwarf::DW_TAG_pointer_type ||
820 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
821 N.getTag() == dwarf::DW_TAG_reference_type ||
822 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
823 N.getTag() == dwarf::DW_TAG_const_type ||
824 N.getTag() == dwarf::DW_TAG_volatile_type ||
825 N.getTag() == dwarf::DW_TAG_restrict_type ||
826 N.getTag() == dwarf::DW_TAG_member ||
827 N.getTag() == dwarf::DW_TAG_inheritance ||
828 N.getTag() == dwarf::DW_TAG_friend,
830 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
831 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
836 static bool hasConflictingReferenceFlags(unsigned Flags) {
837 return (Flags & DebugNode::FlagLValueReference) &&
838 (Flags & DebugNode::FlagRValueReference);
841 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
842 auto *Params = dyn_cast<MDTuple>(&RawParams);
843 Assert(Params, "invalid template params", &N, &RawParams);
844 for (Metadata *Op : Params->operands()) {
845 Assert(Op && isa<MDTemplateParameter>(Op), "invalid template parameter", &N,
850 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
851 // Common derived type checks.
852 visitMDDerivedTypeBase(N);
854 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
855 N.getTag() == dwarf::DW_TAG_structure_type ||
856 N.getTag() == dwarf::DW_TAG_union_type ||
857 N.getTag() == dwarf::DW_TAG_enumeration_type ||
858 N.getTag() == dwarf::DW_TAG_subroutine_type ||
859 N.getTag() == dwarf::DW_TAG_class_type,
862 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
863 "invalid composite elements", &N, N.getRawElements());
864 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
865 N.getRawVTableHolder());
866 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
867 "invalid composite elements", &N, N.getRawElements());
868 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
870 if (auto *Params = N.getRawTemplateParams())
871 visitTemplateParams(N, *Params);
874 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
875 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
876 if (auto *Types = N.getRawTypeArray()) {
877 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
878 for (Metadata *Ty : N.getTypeArray()->operands()) {
879 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
882 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
886 void Verifier::visitMDFile(const MDFile &N) {
887 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
890 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
891 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
893 // Don't bother verifying the compilation directory or producer string
894 // as those could be empty.
895 Assert(N.getRawFile() && isa<MDFile>(N.getRawFile()),
896 "invalid file", &N, N.getRawFile());
897 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
900 if (auto *Array = N.getRawEnumTypes()) {
901 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
902 for (Metadata *Op : N.getEnumTypes()->operands()) {
903 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
904 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
905 "invalid enum type", &N, N.getEnumTypes(), Op);
908 if (auto *Array = N.getRawRetainedTypes()) {
909 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
910 for (Metadata *Op : N.getRetainedTypes()->operands()) {
911 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
914 if (auto *Array = N.getRawSubprograms()) {
915 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
916 for (Metadata *Op : N.getSubprograms()->operands()) {
917 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
920 if (auto *Array = N.getRawGlobalVariables()) {
921 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
922 for (Metadata *Op : N.getGlobalVariables()->operands()) {
923 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
927 if (auto *Array = N.getRawImportedEntities()) {
928 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
929 for (Metadata *Op : N.getImportedEntities()->operands()) {
930 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
936 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
937 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
938 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
939 if (auto *T = N.getRawType())
940 Assert(isa<MDSubroutineType>(T), "invalid subroutine type", &N, T);
941 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
942 N.getRawContainingType());
943 if (auto *RawF = N.getRawFunction()) {
944 auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
945 auto *F = FMD ? FMD->getValue() : nullptr;
946 auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
947 Assert(F && FT && isa<FunctionType>(FT->getElementType()),
948 "invalid function", &N, F, FT);
950 if (auto *Params = N.getRawTemplateParams())
951 visitTemplateParams(N, *Params);
952 if (auto *S = N.getRawDeclaration()) {
953 Assert(isa<MDSubprogram>(S) && !cast<MDSubprogram>(S)->isDefinition(),
954 "invalid subprogram declaration", &N, S);
956 if (auto *RawVars = N.getRawVariables()) {
957 auto *Vars = dyn_cast<MDTuple>(RawVars);
958 Assert(Vars, "invalid variable list", &N, RawVars);
959 for (Metadata *Op : Vars->operands()) {
960 Assert(Op && isa<MDLocalVariable>(Op), "invalid local variable", &N, Vars,
964 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
967 auto *F = N.getFunction();
971 // Check that all !dbg attachments lead to back to N (or, at least, another
972 // subprogram that describes the same function).
974 // FIXME: Check this incrementally while visiting !dbg attachments.
975 // FIXME: Only check when N is the canonical subprogram for F.
976 SmallPtrSet<const MDNode *, 32> Seen;
979 // Be careful about using MDLocation here since we might be dealing with
980 // broken code (this is the Verifier after all).
982 dyn_cast_or_null<MDLocation>(I.getDebugLoc().getAsMDNode());
985 if (!Seen.insert(DL).second)
988 MDLocalScope *Scope = DL->getInlinedAtScope();
989 if (Scope && !Seen.insert(Scope).second)
992 MDSubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
993 if (SP && !Seen.insert(SP).second)
996 // FIXME: Once N is canonical, check "SP == &N".
997 Assert(DISubprogram(SP).describes(F),
998 "!dbg attachment points at wrong subprogram for function", &N, F,
1003 void Verifier::visitMDLexicalBlockBase(const MDLexicalBlockBase &N) {
1004 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1005 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
1006 "invalid local scope", &N, N.getRawScope());
1009 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
1010 visitMDLexicalBlockBase(N);
1012 Assert(N.getLine() || !N.getColumn(),
1013 "cannot have column info without line info", &N);
1016 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
1017 visitMDLexicalBlockBase(N);
1020 void Verifier::visitMDNamespace(const MDNamespace &N) {
1021 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1022 if (auto *S = N.getRawScope())
1023 Assert(isa<MDScope>(S), "invalid scope ref", &N, S);
1026 void Verifier::visitMDTemplateParameter(const MDTemplateParameter &N) {
1027 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1030 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
1031 visitMDTemplateParameter(N);
1033 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1037 void Verifier::visitMDTemplateValueParameter(
1038 const MDTemplateValueParameter &N) {
1039 visitMDTemplateParameter(N);
1041 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1042 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1043 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1047 void Verifier::visitMDVariable(const MDVariable &N) {
1048 if (auto *S = N.getRawScope())
1049 Assert(isa<MDScope>(S), "invalid scope", &N, S);
1050 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1051 if (auto *F = N.getRawFile())
1052 Assert(isa<MDFile>(F), "invalid file", &N, F);
1055 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
1056 // Checks common to all variables.
1059 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1060 Assert(!N.getName().empty(), "missing global variable name", &N);
1061 if (auto *V = N.getRawVariable()) {
1062 Assert(isa<ConstantAsMetadata>(V) &&
1063 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1064 "invalid global varaible ref", &N, V);
1066 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1067 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
1072 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
1073 // Checks common to all variables.
1076 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
1077 N.getTag() == dwarf::DW_TAG_arg_variable,
1079 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
1080 "local variable requires a valid scope", &N, N.getRawScope());
1081 if (auto *IA = N.getRawInlinedAt())
1082 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
1086 void Verifier::visitMDExpression(const MDExpression &N) {
1087 Assert(N.isValid(), "invalid expression", &N);
1090 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
1091 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1092 if (auto *T = N.getRawType())
1093 Assert(isa<MDType>(T), "invalid type ref", &N, T);
1094 if (auto *F = N.getRawFile())
1095 Assert(isa<MDFile>(F), "invalid file", &N, F);
1098 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
1099 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1100 N.getTag() == dwarf::DW_TAG_imported_declaration,
1102 if (auto *S = N.getRawScope())
1103 Assert(isa<MDScope>(S), "invalid scope for imported entity", &N, S);
1104 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1108 void Verifier::visitComdat(const Comdat &C) {
1109 // The Module is invalid if the GlobalValue has private linkage. Entities
1110 // with private linkage don't have entries in the symbol table.
1111 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1112 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1116 void Verifier::visitModuleIdents(const Module &M) {
1117 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1121 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1122 // Scan each llvm.ident entry and make sure that this requirement is met.
1123 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1124 const MDNode *N = Idents->getOperand(i);
1125 Assert(N->getNumOperands() == 1,
1126 "incorrect number of operands in llvm.ident metadata", N);
1127 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1128 ("invalid value for llvm.ident metadata entry operand"
1129 "(the operand should be a string)"),
1134 void Verifier::visitModuleFlags(const Module &M) {
1135 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1138 // Scan each flag, and track the flags and requirements.
1139 DenseMap<const MDString*, const MDNode*> SeenIDs;
1140 SmallVector<const MDNode*, 16> Requirements;
1141 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1142 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1145 // Validate that the requirements in the module are valid.
1146 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1147 const MDNode *Requirement = Requirements[I];
1148 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1149 const Metadata *ReqValue = Requirement->getOperand(1);
1151 const MDNode *Op = SeenIDs.lookup(Flag);
1153 CheckFailed("invalid requirement on flag, flag is not present in module",
1158 if (Op->getOperand(2) != ReqValue) {
1159 CheckFailed(("invalid requirement on flag, "
1160 "flag does not have the required value"),
1168 Verifier::visitModuleFlag(const MDNode *Op,
1169 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1170 SmallVectorImpl<const MDNode *> &Requirements) {
1171 // Each module flag should have three arguments, the merge behavior (a
1172 // constant int), the flag ID (an MDString), and the value.
1173 Assert(Op->getNumOperands() == 3,
1174 "incorrect number of operands in module flag", Op);
1175 Module::ModFlagBehavior MFB;
1176 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1178 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1179 "invalid behavior operand in module flag (expected constant integer)",
1182 "invalid behavior operand in module flag (unexpected constant)",
1185 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1186 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1189 // Sanity check the values for behaviors with additional requirements.
1192 case Module::Warning:
1193 case Module::Override:
1194 // These behavior types accept any value.
1197 case Module::Require: {
1198 // The value should itself be an MDNode with two operands, a flag ID (an
1199 // MDString), and a value.
1200 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1201 Assert(Value && Value->getNumOperands() == 2,
1202 "invalid value for 'require' module flag (expected metadata pair)",
1204 Assert(isa<MDString>(Value->getOperand(0)),
1205 ("invalid value for 'require' module flag "
1206 "(first value operand should be a string)"),
1207 Value->getOperand(0));
1209 // Append it to the list of requirements, to check once all module flags are
1211 Requirements.push_back(Value);
1215 case Module::Append:
1216 case Module::AppendUnique: {
1217 // These behavior types require the operand be an MDNode.
1218 Assert(isa<MDNode>(Op->getOperand(2)),
1219 "invalid value for 'append'-type module flag "
1220 "(expected a metadata node)",
1226 // Unless this is a "requires" flag, check the ID is unique.
1227 if (MFB != Module::Require) {
1228 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1230 "module flag identifiers must be unique (or of 'require' type)", ID);
1234 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1235 bool isFunction, const Value *V) {
1236 unsigned Slot = ~0U;
1237 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1238 if (Attrs.getSlotIndex(I) == Idx) {
1243 assert(Slot != ~0U && "Attribute set inconsistency!");
1245 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1247 if (I->isStringAttribute())
1250 if (I->getKindAsEnum() == Attribute::NoReturn ||
1251 I->getKindAsEnum() == Attribute::NoUnwind ||
1252 I->getKindAsEnum() == Attribute::NoInline ||
1253 I->getKindAsEnum() == Attribute::AlwaysInline ||
1254 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1255 I->getKindAsEnum() == Attribute::StackProtect ||
1256 I->getKindAsEnum() == Attribute::StackProtectReq ||
1257 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1258 I->getKindAsEnum() == Attribute::NoRedZone ||
1259 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1260 I->getKindAsEnum() == Attribute::Naked ||
1261 I->getKindAsEnum() == Attribute::InlineHint ||
1262 I->getKindAsEnum() == Attribute::StackAlignment ||
1263 I->getKindAsEnum() == Attribute::UWTable ||
1264 I->getKindAsEnum() == Attribute::NonLazyBind ||
1265 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1266 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1267 I->getKindAsEnum() == Attribute::SanitizeThread ||
1268 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1269 I->getKindAsEnum() == Attribute::MinSize ||
1270 I->getKindAsEnum() == Attribute::NoDuplicate ||
1271 I->getKindAsEnum() == Attribute::Builtin ||
1272 I->getKindAsEnum() == Attribute::NoBuiltin ||
1273 I->getKindAsEnum() == Attribute::Cold ||
1274 I->getKindAsEnum() == Attribute::OptimizeNone ||
1275 I->getKindAsEnum() == Attribute::JumpTable) {
1277 CheckFailed("Attribute '" + I->getAsString() +
1278 "' only applies to functions!", V);
1281 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1282 I->getKindAsEnum() == Attribute::ReadNone) {
1284 CheckFailed("Attribute '" + I->getAsString() +
1285 "' does not apply to function returns");
1288 } else if (isFunction) {
1289 CheckFailed("Attribute '" + I->getAsString() +
1290 "' does not apply to functions!", V);
1296 // VerifyParameterAttrs - Check the given attributes for an argument or return
1297 // value of the specified type. The value V is printed in error messages.
1298 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1299 bool isReturnValue, const Value *V) {
1300 if (!Attrs.hasAttributes(Idx))
1303 VerifyAttributeTypes(Attrs, Idx, false, V);
1306 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1307 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1308 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1309 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1310 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1311 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1312 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1313 "'returned' do not apply to return values!",
1316 // Check for mutually incompatible attributes. Only inreg is compatible with
1318 unsigned AttrCount = 0;
1319 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1320 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1321 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1322 Attrs.hasAttribute(Idx, Attribute::InReg);
1323 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1324 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1325 "and 'sret' are incompatible!",
1328 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1329 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1331 "'inalloca and readonly' are incompatible!",
1334 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1335 Attrs.hasAttribute(Idx, Attribute::Returned)),
1337 "'sret and returned' are incompatible!",
1340 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1341 Attrs.hasAttribute(Idx, Attribute::SExt)),
1343 "'zeroext and signext' are incompatible!",
1346 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1347 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1349 "'readnone and readonly' are incompatible!",
1352 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1353 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1355 "'noinline and alwaysinline' are incompatible!",
1358 Assert(!AttrBuilder(Attrs, Idx)
1359 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1360 "Wrong types for attribute: " +
1361 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1364 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1365 SmallPtrSet<const Type*, 4> Visited;
1366 if (!PTy->getElementType()->isSized(&Visited)) {
1367 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1368 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1369 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1373 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1374 "Attribute 'byval' only applies to parameters with pointer type!",
1379 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1380 // The value V is printed in error messages.
1381 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1383 if (Attrs.isEmpty())
1386 bool SawNest = false;
1387 bool SawReturned = false;
1388 bool SawSRet = false;
1390 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1391 unsigned Idx = Attrs.getSlotIndex(i);
1395 Ty = FT->getReturnType();
1396 else if (Idx-1 < FT->getNumParams())
1397 Ty = FT->getParamType(Idx-1);
1399 break; // VarArgs attributes, verified elsewhere.
1401 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1406 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1407 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1411 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1412 Assert(!SawReturned, "More than one parameter has attribute returned!",
1414 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1416 "argument and return types for 'returned' attribute",
1421 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1422 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1423 Assert(Idx == 1 || Idx == 2,
1424 "Attribute 'sret' is not on first or second parameter!", V);
1428 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1429 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1434 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1437 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1440 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1441 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1442 "Attributes 'readnone and readonly' are incompatible!", V);
1445 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1446 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1447 Attribute::AlwaysInline)),
1448 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1450 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1451 Attribute::OptimizeNone)) {
1452 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1453 "Attribute 'optnone' requires 'noinline'!", V);
1455 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1456 Attribute::OptimizeForSize),
1457 "Attributes 'optsize and optnone' are incompatible!", V);
1459 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1460 "Attributes 'minsize and optnone' are incompatible!", V);
1463 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1464 Attribute::JumpTable)) {
1465 const GlobalValue *GV = cast<GlobalValue>(V);
1466 Assert(GV->hasUnnamedAddr(),
1467 "Attribute 'jumptable' requires 'unnamed_addr'", V);
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 "gc.statepoint must read and write memory to preserve "
1504 "reordering restrictions required by safepoint semantics",
1507 const Value *Target = CS.getArgument(0);
1508 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1509 Assert(PT && PT->getElementType()->isFunctionTy(),
1510 "gc.statepoint callee must be of function pointer type", &CI, Target);
1511 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1513 const Value *NumCallArgsV = CS.getArgument(1);
1514 Assert(isa<ConstantInt>(NumCallArgsV),
1515 "gc.statepoint number of arguments to underlying call "
1516 "must be constant integer",
1518 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1519 Assert(NumCallArgs >= 0,
1520 "gc.statepoint number of arguments to underlying call "
1523 const int NumParams = (int)TargetFuncType->getNumParams();
1524 if (TargetFuncType->isVarArg()) {
1525 Assert(NumCallArgs >= NumParams,
1526 "gc.statepoint mismatch in number of vararg call args", &CI);
1528 // TODO: Remove this limitation
1529 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1530 "gc.statepoint doesn't support wrapping non-void "
1531 "vararg functions yet",
1534 Assert(NumCallArgs == NumParams,
1535 "gc.statepoint mismatch in number of call args", &CI);
1537 const Value *Unused = CS.getArgument(2);
1538 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1539 "gc.statepoint parameter #3 must be zero", &CI);
1541 // Verify that the types of the call parameter arguments match
1542 // the type of the wrapped callee.
1543 for (int i = 0; i < NumParams; i++) {
1544 Type *ParamType = TargetFuncType->getParamType(i);
1545 Type *ArgType = CS.getArgument(3+i)->getType();
1546 Assert(ArgType == ParamType,
1547 "gc.statepoint call argument does not match wrapped "
1551 const int EndCallArgsInx = 2+NumCallArgs;
1552 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1553 Assert(isa<ConstantInt>(NumDeoptArgsV),
1554 "gc.statepoint number of deoptimization arguments "
1555 "must be constant integer",
1557 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1558 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1562 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1563 "gc.statepoint too few arguments according to length fields", &CI);
1565 // Check that the only uses of this gc.statepoint are gc.result or
1566 // gc.relocate calls which are tied to this statepoint and thus part
1567 // of the same statepoint sequence
1568 for (const User *U : CI.users()) {
1569 const CallInst *Call = dyn_cast<const CallInst>(U);
1570 Assert(Call, "illegal use of statepoint token", &CI, U);
1571 if (!Call) continue;
1572 Assert(isGCRelocate(Call) || isGCResult(Call),
1573 "gc.result or gc.relocate are the only value uses"
1574 "of a gc.statepoint",
1576 if (isGCResult(Call)) {
1577 Assert(Call->getArgOperand(0) == &CI,
1578 "gc.result connected to wrong gc.statepoint", &CI, Call);
1579 } else if (isGCRelocate(Call)) {
1580 Assert(Call->getArgOperand(0) == &CI,
1581 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1585 // Note: It is legal for a single derived pointer to be listed multiple
1586 // times. It's non-optimal, but it is legal. It can also happen after
1587 // insertion if we strip a bitcast away.
1588 // Note: It is really tempting to check that each base is relocated and
1589 // that a derived pointer is never reused as a base pointer. This turns
1590 // out to be problematic since optimizations run after safepoint insertion
1591 // can recognize equality properties that the insertion logic doesn't know
1592 // about. See example statepoint.ll in the verifier subdirectory
1595 void Verifier::verifyFrameRecoverIndices() {
1596 for (auto &Counts : FrameEscapeInfo) {
1597 Function *F = Counts.first;
1598 unsigned EscapedObjectCount = Counts.second.first;
1599 unsigned MaxRecoveredIndex = Counts.second.second;
1600 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1601 "all indices passed to llvm.framerecover must be less than the "
1602 "number of arguments passed ot llvm.frameescape in the parent "
1608 // visitFunction - Verify that a function is ok.
1610 void Verifier::visitFunction(const Function &F) {
1611 // Check function arguments.
1612 FunctionType *FT = F.getFunctionType();
1613 unsigned NumArgs = F.arg_size();
1615 Assert(Context == &F.getContext(),
1616 "Function context does not match Module context!", &F);
1618 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1619 Assert(FT->getNumParams() == NumArgs,
1620 "# formal arguments must match # of arguments for function type!", &F,
1622 Assert(F.getReturnType()->isFirstClassType() ||
1623 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1624 "Functions cannot return aggregate values!", &F);
1626 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1627 "Invalid struct return type!", &F);
1629 AttributeSet Attrs = F.getAttributes();
1631 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1632 "Attribute after last parameter!", &F);
1634 // Check function attributes.
1635 VerifyFunctionAttrs(FT, Attrs, &F);
1637 // On function declarations/definitions, we do not support the builtin
1638 // attribute. We do not check this in VerifyFunctionAttrs since that is
1639 // checking for Attributes that can/can not ever be on functions.
1640 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1641 "Attribute 'builtin' can only be applied to a callsite.", &F);
1643 // Check that this function meets the restrictions on this calling convention.
1644 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1645 // restrictions can be lifted.
1646 switch (F.getCallingConv()) {
1648 case CallingConv::C:
1650 case CallingConv::Fast:
1651 case CallingConv::Cold:
1652 case CallingConv::Intel_OCL_BI:
1653 case CallingConv::PTX_Kernel:
1654 case CallingConv::PTX_Device:
1655 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1656 "perfect forwarding!",
1661 bool isLLVMdotName = F.getName().size() >= 5 &&
1662 F.getName().substr(0, 5) == "llvm.";
1664 // Check that the argument values match the function type for this function...
1666 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1668 Assert(I->getType() == FT->getParamType(i),
1669 "Argument value does not match function argument type!", I,
1670 FT->getParamType(i));
1671 Assert(I->getType()->isFirstClassType(),
1672 "Function arguments must have first-class types!", I);
1674 Assert(!I->getType()->isMetadataTy(),
1675 "Function takes metadata but isn't an intrinsic", I, &F);
1678 if (F.isMaterializable()) {
1679 // Function has a body somewhere we can't see.
1680 } else if (F.isDeclaration()) {
1681 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1682 "invalid linkage type for function declaration", &F);
1684 // Verify that this function (which has a body) is not named "llvm.*". It
1685 // is not legal to define intrinsics.
1686 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1688 // Check the entry node
1689 const BasicBlock *Entry = &F.getEntryBlock();
1690 Assert(pred_empty(Entry),
1691 "Entry block to function must not have predecessors!", Entry);
1693 // The address of the entry block cannot be taken, unless it is dead.
1694 if (Entry->hasAddressTaken()) {
1695 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1696 "blockaddress may not be used with the entry block!", Entry);
1700 // If this function is actually an intrinsic, verify that it is only used in
1701 // direct call/invokes, never having its "address taken".
1702 if (F.getIntrinsicID()) {
1704 if (F.hasAddressTaken(&U))
1705 Assert(0, "Invalid user of intrinsic instruction!", U);
1708 Assert(!F.hasDLLImportStorageClass() ||
1709 (F.isDeclaration() && F.hasExternalLinkage()) ||
1710 F.hasAvailableExternallyLinkage(),
1711 "Function is marked as dllimport, but not external.", &F);
1714 // verifyBasicBlock - Verify that a basic block is well formed...
1716 void Verifier::visitBasicBlock(BasicBlock &BB) {
1717 InstsInThisBlock.clear();
1719 // Ensure that basic blocks have terminators!
1720 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1722 // Check constraints that this basic block imposes on all of the PHI nodes in
1724 if (isa<PHINode>(BB.front())) {
1725 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1726 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1727 std::sort(Preds.begin(), Preds.end());
1729 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1730 // Ensure that PHI nodes have at least one entry!
1731 Assert(PN->getNumIncomingValues() != 0,
1732 "PHI nodes must have at least one entry. If the block is dead, "
1733 "the PHI should be removed!",
1735 Assert(PN->getNumIncomingValues() == Preds.size(),
1736 "PHINode should have one entry for each predecessor of its "
1737 "parent basic block!",
1740 // Get and sort all incoming values in the PHI node...
1742 Values.reserve(PN->getNumIncomingValues());
1743 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1744 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1745 PN->getIncomingValue(i)));
1746 std::sort(Values.begin(), Values.end());
1748 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1749 // Check to make sure that if there is more than one entry for a
1750 // particular basic block in this PHI node, that the incoming values are
1753 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1754 Values[i].second == Values[i - 1].second,
1755 "PHI node has multiple entries for the same basic block with "
1756 "different incoming values!",
1757 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1759 // Check to make sure that the predecessors and PHI node entries are
1761 Assert(Values[i].first == Preds[i],
1762 "PHI node entries do not match predecessors!", PN,
1763 Values[i].first, Preds[i]);
1768 // Check that all instructions have their parent pointers set up correctly.
1771 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1775 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1776 // Ensure that terminators only exist at the end of the basic block.
1777 Assert(&I == I.getParent()->getTerminator(),
1778 "Terminator found in the middle of a basic block!", I.getParent());
1779 visitInstruction(I);
1782 void Verifier::visitBranchInst(BranchInst &BI) {
1783 if (BI.isConditional()) {
1784 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1785 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1787 visitTerminatorInst(BI);
1790 void Verifier::visitReturnInst(ReturnInst &RI) {
1791 Function *F = RI.getParent()->getParent();
1792 unsigned N = RI.getNumOperands();
1793 if (F->getReturnType()->isVoidTy())
1795 "Found return instr that returns non-void in Function of void "
1797 &RI, F->getReturnType());
1799 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1800 "Function return type does not match operand "
1801 "type of return inst!",
1802 &RI, F->getReturnType());
1804 // Check to make sure that the return value has necessary properties for
1806 visitTerminatorInst(RI);
1809 void Verifier::visitSwitchInst(SwitchInst &SI) {
1810 // Check to make sure that all of the constants in the switch instruction
1811 // have the same type as the switched-on value.
1812 Type *SwitchTy = SI.getCondition()->getType();
1813 SmallPtrSet<ConstantInt*, 32> Constants;
1814 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1815 Assert(i.getCaseValue()->getType() == SwitchTy,
1816 "Switch constants must all be same type as switch value!", &SI);
1817 Assert(Constants.insert(i.getCaseValue()).second,
1818 "Duplicate integer as switch case", &SI, i.getCaseValue());
1821 visitTerminatorInst(SI);
1824 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1825 Assert(BI.getAddress()->getType()->isPointerTy(),
1826 "Indirectbr operand must have pointer type!", &BI);
1827 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1828 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1829 "Indirectbr destinations must all have pointer type!", &BI);
1831 visitTerminatorInst(BI);
1834 void Verifier::visitSelectInst(SelectInst &SI) {
1835 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1837 "Invalid operands for select instruction!", &SI);
1839 Assert(SI.getTrueValue()->getType() == SI.getType(),
1840 "Select values must have same type as select instruction!", &SI);
1841 visitInstruction(SI);
1844 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1845 /// a pass, if any exist, it's an error.
1847 void Verifier::visitUserOp1(Instruction &I) {
1848 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1851 void Verifier::visitTruncInst(TruncInst &I) {
1852 // Get the source and destination types
1853 Type *SrcTy = I.getOperand(0)->getType();
1854 Type *DestTy = I.getType();
1856 // Get the size of the types in bits, we'll need this later
1857 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1858 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1860 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1861 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1862 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1863 "trunc source and destination must both be a vector or neither", &I);
1864 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1866 visitInstruction(I);
1869 void Verifier::visitZExtInst(ZExtInst &I) {
1870 // Get the source and destination types
1871 Type *SrcTy = I.getOperand(0)->getType();
1872 Type *DestTy = I.getType();
1874 // Get the size of the types in bits, we'll need this later
1875 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1876 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1877 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1878 "zext source and destination must both be a vector or neither", &I);
1879 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1880 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1882 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1884 visitInstruction(I);
1887 void Verifier::visitSExtInst(SExtInst &I) {
1888 // Get the source and destination types
1889 Type *SrcTy = I.getOperand(0)->getType();
1890 Type *DestTy = I.getType();
1892 // Get the size of the types in bits, we'll need this later
1893 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1894 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1896 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1897 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1898 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1899 "sext source and destination must both be a vector or neither", &I);
1900 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1902 visitInstruction(I);
1905 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1906 // Get the source and destination types
1907 Type *SrcTy = I.getOperand(0)->getType();
1908 Type *DestTy = I.getType();
1909 // Get the size of the types in bits, we'll need this later
1910 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1911 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1913 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1914 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1915 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1916 "fptrunc source and destination must both be a vector or neither", &I);
1917 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1919 visitInstruction(I);
1922 void Verifier::visitFPExtInst(FPExtInst &I) {
1923 // Get the source and destination types
1924 Type *SrcTy = I.getOperand(0)->getType();
1925 Type *DestTy = I.getType();
1927 // Get the size of the types in bits, we'll need this later
1928 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1929 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1931 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1932 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1933 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1934 "fpext source and destination must both be a vector or neither", &I);
1935 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1937 visitInstruction(I);
1940 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1941 // Get the source and destination types
1942 Type *SrcTy = I.getOperand(0)->getType();
1943 Type *DestTy = I.getType();
1945 bool SrcVec = SrcTy->isVectorTy();
1946 bool DstVec = DestTy->isVectorTy();
1948 Assert(SrcVec == DstVec,
1949 "UIToFP source and dest must both be vector or scalar", &I);
1950 Assert(SrcTy->isIntOrIntVectorTy(),
1951 "UIToFP source must be integer or integer vector", &I);
1952 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1955 if (SrcVec && DstVec)
1956 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1957 cast<VectorType>(DestTy)->getNumElements(),
1958 "UIToFP source and dest vector length mismatch", &I);
1960 visitInstruction(I);
1963 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1964 // Get the source and destination types
1965 Type *SrcTy = I.getOperand(0)->getType();
1966 Type *DestTy = I.getType();
1968 bool SrcVec = SrcTy->isVectorTy();
1969 bool DstVec = DestTy->isVectorTy();
1971 Assert(SrcVec == DstVec,
1972 "SIToFP source and dest must both be vector or scalar", &I);
1973 Assert(SrcTy->isIntOrIntVectorTy(),
1974 "SIToFP source must be integer or integer vector", &I);
1975 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1978 if (SrcVec && DstVec)
1979 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1980 cast<VectorType>(DestTy)->getNumElements(),
1981 "SIToFP source and dest vector length mismatch", &I);
1983 visitInstruction(I);
1986 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1987 // Get the source and destination types
1988 Type *SrcTy = I.getOperand(0)->getType();
1989 Type *DestTy = I.getType();
1991 bool SrcVec = SrcTy->isVectorTy();
1992 bool DstVec = DestTy->isVectorTy();
1994 Assert(SrcVec == DstVec,
1995 "FPToUI source and dest must both be vector or scalar", &I);
1996 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1998 Assert(DestTy->isIntOrIntVectorTy(),
1999 "FPToUI result must be integer or integer vector", &I);
2001 if (SrcVec && DstVec)
2002 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2003 cast<VectorType>(DestTy)->getNumElements(),
2004 "FPToUI source and dest vector length mismatch", &I);
2006 visitInstruction(I);
2009 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2010 // Get the source and destination types
2011 Type *SrcTy = I.getOperand(0)->getType();
2012 Type *DestTy = I.getType();
2014 bool SrcVec = SrcTy->isVectorTy();
2015 bool DstVec = DestTy->isVectorTy();
2017 Assert(SrcVec == DstVec,
2018 "FPToSI source and dest must both be vector or scalar", &I);
2019 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2021 Assert(DestTy->isIntOrIntVectorTy(),
2022 "FPToSI result must be integer or integer vector", &I);
2024 if (SrcVec && DstVec)
2025 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2026 cast<VectorType>(DestTy)->getNumElements(),
2027 "FPToSI source and dest vector length mismatch", &I);
2029 visitInstruction(I);
2032 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2033 // Get the source and destination types
2034 Type *SrcTy = I.getOperand(0)->getType();
2035 Type *DestTy = I.getType();
2037 Assert(SrcTy->getScalarType()->isPointerTy(),
2038 "PtrToInt source must be pointer", &I);
2039 Assert(DestTy->getScalarType()->isIntegerTy(),
2040 "PtrToInt result must be integral", &I);
2041 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2044 if (SrcTy->isVectorTy()) {
2045 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2046 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2047 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2048 "PtrToInt Vector width mismatch", &I);
2051 visitInstruction(I);
2054 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2055 // Get the source and destination types
2056 Type *SrcTy = I.getOperand(0)->getType();
2057 Type *DestTy = I.getType();
2059 Assert(SrcTy->getScalarType()->isIntegerTy(),
2060 "IntToPtr source must be an integral", &I);
2061 Assert(DestTy->getScalarType()->isPointerTy(),
2062 "IntToPtr result must be a pointer", &I);
2063 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2065 if (SrcTy->isVectorTy()) {
2066 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2067 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2068 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2069 "IntToPtr Vector width mismatch", &I);
2071 visitInstruction(I);
2074 void Verifier::visitBitCastInst(BitCastInst &I) {
2076 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2077 "Invalid bitcast", &I);
2078 visitInstruction(I);
2081 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2082 Type *SrcTy = I.getOperand(0)->getType();
2083 Type *DestTy = I.getType();
2085 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2087 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2089 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2090 "AddrSpaceCast must be between different address spaces", &I);
2091 if (SrcTy->isVectorTy())
2092 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2093 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2094 visitInstruction(I);
2097 /// visitPHINode - Ensure that a PHI node is well formed.
2099 void Verifier::visitPHINode(PHINode &PN) {
2100 // Ensure that the PHI nodes are all grouped together at the top of the block.
2101 // This can be tested by checking whether the instruction before this is
2102 // either nonexistent (because this is begin()) or is a PHI node. If not,
2103 // then there is some other instruction before a PHI.
2104 Assert(&PN == &PN.getParent()->front() ||
2105 isa<PHINode>(--BasicBlock::iterator(&PN)),
2106 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2108 // Check that all of the values of the PHI node have the same type as the
2109 // result, and that the incoming blocks are really basic blocks.
2110 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2111 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
2112 "PHI node operands are not the same type as the result!", &PN);
2115 // All other PHI node constraints are checked in the visitBasicBlock method.
2117 visitInstruction(PN);
2120 void Verifier::VerifyCallSite(CallSite CS) {
2121 Instruction *I = CS.getInstruction();
2123 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2124 "Called function must be a pointer!", I);
2125 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2127 Assert(FPTy->getElementType()->isFunctionTy(),
2128 "Called function is not pointer to function type!", I);
2129 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
2131 // Verify that the correct number of arguments are being passed
2132 if (FTy->isVarArg())
2133 Assert(CS.arg_size() >= FTy->getNumParams(),
2134 "Called function requires more parameters than were provided!", I);
2136 Assert(CS.arg_size() == FTy->getNumParams(),
2137 "Incorrect number of arguments passed to called function!", I);
2139 // Verify that all arguments to the call match the function type.
2140 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2141 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2142 "Call parameter type does not match function signature!",
2143 CS.getArgument(i), FTy->getParamType(i), I);
2145 AttributeSet Attrs = CS.getAttributes();
2147 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2148 "Attribute after last parameter!", I);
2150 // Verify call attributes.
2151 VerifyFunctionAttrs(FTy, Attrs, I);
2153 // Conservatively check the inalloca argument.
2154 // We have a bug if we can find that there is an underlying alloca without
2156 if (CS.hasInAllocaArgument()) {
2157 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2158 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2159 Assert(AI->isUsedWithInAlloca(),
2160 "inalloca argument for call has mismatched alloca", AI, I);
2163 if (FTy->isVarArg()) {
2164 // FIXME? is 'nest' even legal here?
2165 bool SawNest = false;
2166 bool SawReturned = false;
2168 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2169 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2171 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2175 // Check attributes on the varargs part.
2176 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2177 Type *Ty = CS.getArgument(Idx-1)->getType();
2178 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2180 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2181 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2185 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2186 Assert(!SawReturned, "More than one parameter has attribute returned!",
2188 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2189 "Incompatible argument and return types for 'returned' "
2195 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2196 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2198 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2199 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2203 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2204 if (CS.getCalledFunction() == nullptr ||
2205 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2206 for (FunctionType::param_iterator PI = FTy->param_begin(),
2207 PE = FTy->param_end(); PI != PE; ++PI)
2208 Assert(!(*PI)->isMetadataTy(),
2209 "Function has metadata parameter but isn't an intrinsic", I);
2212 visitInstruction(*I);
2215 /// Two types are "congruent" if they are identical, or if they are both pointer
2216 /// types with different pointee types and the same address space.
2217 static bool isTypeCongruent(Type *L, Type *R) {
2220 PointerType *PL = dyn_cast<PointerType>(L);
2221 PointerType *PR = dyn_cast<PointerType>(R);
2224 return PL->getAddressSpace() == PR->getAddressSpace();
2227 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2228 static const Attribute::AttrKind ABIAttrs[] = {
2229 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2230 Attribute::InReg, Attribute::Returned};
2232 for (auto AK : ABIAttrs) {
2233 if (Attrs.hasAttribute(I + 1, AK))
2234 Copy.addAttribute(AK);
2236 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2237 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2241 void Verifier::verifyMustTailCall(CallInst &CI) {
2242 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2244 // - The caller and callee prototypes must match. Pointer types of
2245 // parameters or return types may differ in pointee type, but not
2247 Function *F = CI.getParent()->getParent();
2248 auto GetFnTy = [](Value *V) {
2249 return cast<FunctionType>(
2250 cast<PointerType>(V->getType())->getElementType());
2252 FunctionType *CallerTy = GetFnTy(F);
2253 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2254 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2255 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2256 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2257 "cannot guarantee tail call due to mismatched varargs", &CI);
2258 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2259 "cannot guarantee tail call due to mismatched return types", &CI);
2260 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2262 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2263 "cannot guarantee tail call due to mismatched parameter types", &CI);
2266 // - The calling conventions of the caller and callee must match.
2267 Assert(F->getCallingConv() == CI.getCallingConv(),
2268 "cannot guarantee tail call due to mismatched calling conv", &CI);
2270 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2271 // returned, and inalloca, must match.
2272 AttributeSet CallerAttrs = F->getAttributes();
2273 AttributeSet CalleeAttrs = CI.getAttributes();
2274 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2275 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2276 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2277 Assert(CallerABIAttrs == CalleeABIAttrs,
2278 "cannot guarantee tail call due to mismatched ABI impacting "
2279 "function attributes",
2280 &CI, CI.getOperand(I));
2283 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2284 // or a pointer bitcast followed by a ret instruction.
2285 // - The ret instruction must return the (possibly bitcasted) value
2286 // produced by the call or void.
2287 Value *RetVal = &CI;
2288 Instruction *Next = CI.getNextNode();
2290 // Handle the optional bitcast.
2291 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2292 Assert(BI->getOperand(0) == RetVal,
2293 "bitcast following musttail call must use the call", BI);
2295 Next = BI->getNextNode();
2298 // Check the return.
2299 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2300 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2302 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2303 "musttail call result must be returned", Ret);
2306 void Verifier::visitCallInst(CallInst &CI) {
2307 VerifyCallSite(&CI);
2309 if (CI.isMustTailCall())
2310 verifyMustTailCall(CI);
2312 if (Function *F = CI.getCalledFunction())
2313 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2314 visitIntrinsicFunctionCall(ID, CI);
2317 void Verifier::visitInvokeInst(InvokeInst &II) {
2318 VerifyCallSite(&II);
2320 // Verify that there is a landingpad instruction as the first non-PHI
2321 // instruction of the 'unwind' destination.
2322 Assert(II.getUnwindDest()->isLandingPad(),
2323 "The unwind destination does not have a landingpad instruction!", &II);
2325 if (Function *F = II.getCalledFunction())
2326 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2327 // CallInst as an input parameter. It not woth updating this whole
2328 // function only to support statepoint verification.
2329 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2330 VerifyStatepoint(ImmutableCallSite(&II));
2332 visitTerminatorInst(II);
2335 /// visitBinaryOperator - Check that both arguments to the binary operator are
2336 /// of the same type!
2338 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2339 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2340 "Both operands to a binary operator are not of the same type!", &B);
2342 switch (B.getOpcode()) {
2343 // Check that integer arithmetic operators are only used with
2344 // integral operands.
2345 case Instruction::Add:
2346 case Instruction::Sub:
2347 case Instruction::Mul:
2348 case Instruction::SDiv:
2349 case Instruction::UDiv:
2350 case Instruction::SRem:
2351 case Instruction::URem:
2352 Assert(B.getType()->isIntOrIntVectorTy(),
2353 "Integer arithmetic operators only work with integral types!", &B);
2354 Assert(B.getType() == B.getOperand(0)->getType(),
2355 "Integer arithmetic operators must have same type "
2356 "for operands and result!",
2359 // Check that floating-point arithmetic operators are only used with
2360 // floating-point operands.
2361 case Instruction::FAdd:
2362 case Instruction::FSub:
2363 case Instruction::FMul:
2364 case Instruction::FDiv:
2365 case Instruction::FRem:
2366 Assert(B.getType()->isFPOrFPVectorTy(),
2367 "Floating-point arithmetic operators only work with "
2368 "floating-point types!",
2370 Assert(B.getType() == B.getOperand(0)->getType(),
2371 "Floating-point arithmetic operators must have same type "
2372 "for operands and result!",
2375 // Check that logical operators are only used with integral operands.
2376 case Instruction::And:
2377 case Instruction::Or:
2378 case Instruction::Xor:
2379 Assert(B.getType()->isIntOrIntVectorTy(),
2380 "Logical operators only work with integral types!", &B);
2381 Assert(B.getType() == B.getOperand(0)->getType(),
2382 "Logical operators must have same type for operands and result!",
2385 case Instruction::Shl:
2386 case Instruction::LShr:
2387 case Instruction::AShr:
2388 Assert(B.getType()->isIntOrIntVectorTy(),
2389 "Shifts only work with integral types!", &B);
2390 Assert(B.getType() == B.getOperand(0)->getType(),
2391 "Shift return type must be same as operands!", &B);
2394 llvm_unreachable("Unknown BinaryOperator opcode!");
2397 visitInstruction(B);
2400 void Verifier::visitICmpInst(ICmpInst &IC) {
2401 // Check that the operands are the same type
2402 Type *Op0Ty = IC.getOperand(0)->getType();
2403 Type *Op1Ty = IC.getOperand(1)->getType();
2404 Assert(Op0Ty == Op1Ty,
2405 "Both operands to ICmp instruction are not of the same type!", &IC);
2406 // Check that the operands are the right type
2407 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2408 "Invalid operand types for ICmp instruction", &IC);
2409 // Check that the predicate is valid.
2410 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2411 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2412 "Invalid predicate in ICmp instruction!", &IC);
2414 visitInstruction(IC);
2417 void Verifier::visitFCmpInst(FCmpInst &FC) {
2418 // Check that the operands are the same type
2419 Type *Op0Ty = FC.getOperand(0)->getType();
2420 Type *Op1Ty = FC.getOperand(1)->getType();
2421 Assert(Op0Ty == Op1Ty,
2422 "Both operands to FCmp instruction are not of the same type!", &FC);
2423 // Check that the operands are the right type
2424 Assert(Op0Ty->isFPOrFPVectorTy(),
2425 "Invalid operand types for FCmp instruction", &FC);
2426 // Check that the predicate is valid.
2427 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2428 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2429 "Invalid predicate in FCmp instruction!", &FC);
2431 visitInstruction(FC);
2434 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2436 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2437 "Invalid extractelement operands!", &EI);
2438 visitInstruction(EI);
2441 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2442 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2444 "Invalid insertelement operands!", &IE);
2445 visitInstruction(IE);
2448 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2449 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2451 "Invalid shufflevector operands!", &SV);
2452 visitInstruction(SV);
2455 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2456 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2458 Assert(isa<PointerType>(TargetTy),
2459 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2460 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2461 "GEP into unsized type!", &GEP);
2462 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2463 GEP.getType()->isVectorTy(),
2464 "Vector GEP must return a vector value", &GEP);
2466 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2468 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2469 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2471 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2472 cast<PointerType>(GEP.getType()->getScalarType())
2473 ->getElementType() == ElTy,
2474 "GEP is not of right type for indices!", &GEP, ElTy);
2476 if (GEP.getPointerOperandType()->isVectorTy()) {
2477 // Additional checks for vector GEPs.
2478 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2479 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2480 "Vector GEP result width doesn't match operand's", &GEP);
2481 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2482 Type *IndexTy = Idxs[i]->getType();
2483 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2485 unsigned IndexWidth = IndexTy->getVectorNumElements();
2486 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2489 visitInstruction(GEP);
2492 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2493 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2496 void Verifier::visitRangeMetadata(Instruction& I,
2497 MDNode* Range, Type* Ty) {
2499 Range == I.getMetadata(LLVMContext::MD_range) &&
2500 "precondition violation");
2502 unsigned NumOperands = Range->getNumOperands();
2503 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2504 unsigned NumRanges = NumOperands / 2;
2505 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2507 ConstantRange LastRange(1); // Dummy initial value
2508 for (unsigned i = 0; i < NumRanges; ++i) {
2510 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2511 Assert(Low, "The lower limit must be an integer!", Low);
2513 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2514 Assert(High, "The upper limit must be an integer!", High);
2515 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2516 "Range types must match instruction type!", &I);
2518 APInt HighV = High->getValue();
2519 APInt LowV = Low->getValue();
2520 ConstantRange CurRange(LowV, HighV);
2521 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2522 "Range must not be empty!", Range);
2524 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2525 "Intervals are overlapping", Range);
2526 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2528 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2531 LastRange = ConstantRange(LowV, HighV);
2533 if (NumRanges > 2) {
2535 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2537 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2538 ConstantRange FirstRange(FirstLow, FirstHigh);
2539 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2540 "Intervals are overlapping", Range);
2541 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2546 void Verifier::visitLoadInst(LoadInst &LI) {
2547 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2548 Assert(PTy, "Load operand must be a pointer.", &LI);
2549 Type *ElTy = LI.getType();
2550 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2551 "huge alignment values are unsupported", &LI);
2552 if (LI.isAtomic()) {
2553 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2554 "Load cannot have Release ordering", &LI);
2555 Assert(LI.getAlignment() != 0,
2556 "Atomic load must specify explicit alignment", &LI);
2557 if (!ElTy->isPointerTy()) {
2558 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2560 unsigned Size = ElTy->getPrimitiveSizeInBits();
2561 Assert(Size >= 8 && !(Size & (Size - 1)),
2562 "atomic load operand must be power-of-two byte-sized integer", &LI,
2566 Assert(LI.getSynchScope() == CrossThread,
2567 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2570 visitInstruction(LI);
2573 void Verifier::visitStoreInst(StoreInst &SI) {
2574 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2575 Assert(PTy, "Store operand must be a pointer.", &SI);
2576 Type *ElTy = PTy->getElementType();
2577 Assert(ElTy == SI.getOperand(0)->getType(),
2578 "Stored value type does not match pointer operand type!", &SI, ElTy);
2579 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2580 "huge alignment values are unsupported", &SI);
2581 if (SI.isAtomic()) {
2582 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2583 "Store cannot have Acquire ordering", &SI);
2584 Assert(SI.getAlignment() != 0,
2585 "Atomic store must specify explicit alignment", &SI);
2586 if (!ElTy->isPointerTy()) {
2587 Assert(ElTy->isIntegerTy(),
2588 "atomic store operand must have integer type!", &SI, ElTy);
2589 unsigned Size = ElTy->getPrimitiveSizeInBits();
2590 Assert(Size >= 8 && !(Size & (Size - 1)),
2591 "atomic store operand must be power-of-two byte-sized integer",
2595 Assert(SI.getSynchScope() == CrossThread,
2596 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2598 visitInstruction(SI);
2601 void Verifier::visitAllocaInst(AllocaInst &AI) {
2602 SmallPtrSet<const Type*, 4> Visited;
2603 PointerType *PTy = AI.getType();
2604 Assert(PTy->getAddressSpace() == 0,
2605 "Allocation instruction pointer not in the generic address space!",
2607 Assert(PTy->getElementType()->isSized(&Visited),
2608 "Cannot allocate unsized type", &AI);
2609 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2610 "Alloca array size must have integer type", &AI);
2611 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2612 "huge alignment values are unsupported", &AI);
2614 visitInstruction(AI);
2617 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2619 // FIXME: more conditions???
2620 Assert(CXI.getSuccessOrdering() != NotAtomic,
2621 "cmpxchg instructions must be atomic.", &CXI);
2622 Assert(CXI.getFailureOrdering() != NotAtomic,
2623 "cmpxchg instructions must be atomic.", &CXI);
2624 Assert(CXI.getSuccessOrdering() != Unordered,
2625 "cmpxchg instructions cannot be unordered.", &CXI);
2626 Assert(CXI.getFailureOrdering() != Unordered,
2627 "cmpxchg instructions cannot be unordered.", &CXI);
2628 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2629 "cmpxchg instructions be at least as constrained on success as fail",
2631 Assert(CXI.getFailureOrdering() != Release &&
2632 CXI.getFailureOrdering() != AcquireRelease,
2633 "cmpxchg failure ordering cannot include release semantics", &CXI);
2635 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2636 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2637 Type *ElTy = PTy->getElementType();
2638 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2640 unsigned Size = ElTy->getPrimitiveSizeInBits();
2641 Assert(Size >= 8 && !(Size & (Size - 1)),
2642 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2643 Assert(ElTy == CXI.getOperand(1)->getType(),
2644 "Expected value type does not match pointer operand type!", &CXI,
2646 Assert(ElTy == CXI.getOperand(2)->getType(),
2647 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2648 visitInstruction(CXI);
2651 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2652 Assert(RMWI.getOrdering() != NotAtomic,
2653 "atomicrmw instructions must be atomic.", &RMWI);
2654 Assert(RMWI.getOrdering() != Unordered,
2655 "atomicrmw instructions cannot be unordered.", &RMWI);
2656 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2657 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2658 Type *ElTy = PTy->getElementType();
2659 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2661 unsigned Size = ElTy->getPrimitiveSizeInBits();
2662 Assert(Size >= 8 && !(Size & (Size - 1)),
2663 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2665 Assert(ElTy == RMWI.getOperand(1)->getType(),
2666 "Argument value type does not match pointer operand type!", &RMWI,
2668 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2669 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2670 "Invalid binary operation!", &RMWI);
2671 visitInstruction(RMWI);
2674 void Verifier::visitFenceInst(FenceInst &FI) {
2675 const AtomicOrdering Ordering = FI.getOrdering();
2676 Assert(Ordering == Acquire || Ordering == Release ||
2677 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2678 "fence instructions may only have "
2679 "acquire, release, acq_rel, or seq_cst ordering.",
2681 visitInstruction(FI);
2684 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2685 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2686 EVI.getIndices()) == EVI.getType(),
2687 "Invalid ExtractValueInst operands!", &EVI);
2689 visitInstruction(EVI);
2692 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2693 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2694 IVI.getIndices()) ==
2695 IVI.getOperand(1)->getType(),
2696 "Invalid InsertValueInst operands!", &IVI);
2698 visitInstruction(IVI);
2701 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2702 BasicBlock *BB = LPI.getParent();
2704 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2706 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2707 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2709 // The landingpad instruction defines its parent as a landing pad block. The
2710 // landing pad block may be branched to only by the unwind edge of an invoke.
2711 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2712 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2713 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2714 "Block containing LandingPadInst must be jumped to "
2715 "only by the unwind edge of an invoke.",
2719 // The landingpad instruction must be the first non-PHI instruction in the
2721 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2722 "LandingPadInst not the first non-PHI instruction in the block.",
2725 // The personality functions for all landingpad instructions within the same
2726 // function should match.
2728 Assert(LPI.getPersonalityFn() == PersonalityFn,
2729 "Personality function doesn't match others in function", &LPI);
2730 PersonalityFn = LPI.getPersonalityFn();
2732 // All operands must be constants.
2733 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2735 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2736 Constant *Clause = LPI.getClause(i);
2737 if (LPI.isCatch(i)) {
2738 Assert(isa<PointerType>(Clause->getType()),
2739 "Catch operand does not have pointer type!", &LPI);
2741 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2742 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2743 "Filter operand is not an array of constants!", &LPI);
2747 visitInstruction(LPI);
2750 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2751 Instruction *Op = cast<Instruction>(I.getOperand(i));
2752 // If the we have an invalid invoke, don't try to compute the dominance.
2753 // We already reject it in the invoke specific checks and the dominance
2754 // computation doesn't handle multiple edges.
2755 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2756 if (II->getNormalDest() == II->getUnwindDest())
2760 const Use &U = I.getOperandUse(i);
2761 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2762 "Instruction does not dominate all uses!", Op, &I);
2765 /// verifyInstruction - Verify that an instruction is well formed.
2767 void Verifier::visitInstruction(Instruction &I) {
2768 BasicBlock *BB = I.getParent();
2769 Assert(BB, "Instruction not embedded in basic block!", &I);
2771 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2772 for (User *U : I.users()) {
2773 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2774 "Only PHI nodes may reference their own value!", &I);
2778 // Check that void typed values don't have names
2779 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2780 "Instruction has a name, but provides a void value!", &I);
2782 // Check that the return value of the instruction is either void or a legal
2784 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2785 "Instruction returns a non-scalar type!", &I);
2787 // Check that the instruction doesn't produce metadata. Calls are already
2788 // checked against the callee type.
2789 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2790 "Invalid use of metadata!", &I);
2792 // Check that all uses of the instruction, if they are instructions
2793 // themselves, actually have parent basic blocks. If the use is not an
2794 // instruction, it is an error!
2795 for (Use &U : I.uses()) {
2796 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2797 Assert(Used->getParent() != nullptr,
2798 "Instruction referencing"
2799 " instruction not embedded in a basic block!",
2802 CheckFailed("Use of instruction is not an instruction!", U);
2807 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2808 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2810 // Check to make sure that only first-class-values are operands to
2812 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2813 Assert(0, "Instruction operands must be first-class values!", &I);
2816 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2817 // Check to make sure that the "address of" an intrinsic function is never
2820 !F->isIntrinsic() ||
2821 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2822 "Cannot take the address of an intrinsic!", &I);
2824 !F->isIntrinsic() || isa<CallInst>(I) ||
2825 F->getIntrinsicID() == Intrinsic::donothing ||
2826 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2827 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2828 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2829 "Cannot invoke an intrinsinc other than"
2830 " donothing or patchpoint",
2832 Assert(F->getParent() == M, "Referencing function in another module!",
2834 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2835 Assert(OpBB->getParent() == BB->getParent(),
2836 "Referring to a basic block in another function!", &I);
2837 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2838 Assert(OpArg->getParent() == BB->getParent(),
2839 "Referring to an argument in another function!", &I);
2840 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2841 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2842 } else if (isa<Instruction>(I.getOperand(i))) {
2843 verifyDominatesUse(I, i);
2844 } else if (isa<InlineAsm>(I.getOperand(i))) {
2845 Assert((i + 1 == e && isa<CallInst>(I)) ||
2846 (i + 3 == e && isa<InvokeInst>(I)),
2847 "Cannot take the address of an inline asm!", &I);
2848 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2849 if (CE->getType()->isPtrOrPtrVectorTy()) {
2850 // If we have a ConstantExpr pointer, we need to see if it came from an
2851 // illegal bitcast (inttoptr <constant int> )
2852 SmallVector<const ConstantExpr *, 4> Stack;
2853 SmallPtrSet<const ConstantExpr *, 4> Visited;
2854 Stack.push_back(CE);
2856 while (!Stack.empty()) {
2857 const ConstantExpr *V = Stack.pop_back_val();
2858 if (!Visited.insert(V).second)
2861 VerifyConstantExprBitcastType(V);
2863 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2864 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2865 Stack.push_back(Op);
2872 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2873 Assert(I.getType()->isFPOrFPVectorTy(),
2874 "fpmath requires a floating point result!", &I);
2875 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2876 if (ConstantFP *CFP0 =
2877 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2878 APFloat Accuracy = CFP0->getValueAPF();
2879 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2880 "fpmath accuracy not a positive number!", &I);
2882 Assert(false, "invalid fpmath accuracy!", &I);
2886 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2887 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2888 "Ranges are only for loads, calls and invokes!", &I);
2889 visitRangeMetadata(I, Range, I.getType());
2892 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2893 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2895 Assert(isa<LoadInst>(I),
2896 "nonnull applies only to load instructions, use attributes"
2897 " for calls or invokes",
2901 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2902 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2906 InstsInThisBlock.insert(&I);
2909 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2910 /// intrinsic argument or return value) matches the type constraints specified
2911 /// by the .td file (e.g. an "any integer" argument really is an integer).
2913 /// This return true on error but does not print a message.
2914 bool Verifier::VerifyIntrinsicType(Type *Ty,
2915 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2916 SmallVectorImpl<Type*> &ArgTys) {
2917 using namespace Intrinsic;
2919 // If we ran out of descriptors, there are too many arguments.
2920 if (Infos.empty()) return true;
2921 IITDescriptor D = Infos.front();
2922 Infos = Infos.slice(1);
2925 case IITDescriptor::Void: return !Ty->isVoidTy();
2926 case IITDescriptor::VarArg: return true;
2927 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2928 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2929 case IITDescriptor::Half: return !Ty->isHalfTy();
2930 case IITDescriptor::Float: return !Ty->isFloatTy();
2931 case IITDescriptor::Double: return !Ty->isDoubleTy();
2932 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2933 case IITDescriptor::Vector: {
2934 VectorType *VT = dyn_cast<VectorType>(Ty);
2935 return !VT || VT->getNumElements() != D.Vector_Width ||
2936 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2938 case IITDescriptor::Pointer: {
2939 PointerType *PT = dyn_cast<PointerType>(Ty);
2940 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2941 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2944 case IITDescriptor::Struct: {
2945 StructType *ST = dyn_cast<StructType>(Ty);
2946 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2949 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2950 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2955 case IITDescriptor::Argument:
2956 // Two cases here - If this is the second occurrence of an argument, verify
2957 // that the later instance matches the previous instance.
2958 if (D.getArgumentNumber() < ArgTys.size())
2959 return Ty != ArgTys[D.getArgumentNumber()];
2961 // Otherwise, if this is the first instance of an argument, record it and
2962 // verify the "Any" kind.
2963 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2964 ArgTys.push_back(Ty);
2966 switch (D.getArgumentKind()) {
2967 case IITDescriptor::AK_Any: return false; // Success
2968 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2969 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2970 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2971 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2973 llvm_unreachable("all argument kinds not covered");
2975 case IITDescriptor::ExtendArgument: {
2976 // This may only be used when referring to a previous vector argument.
2977 if (D.getArgumentNumber() >= ArgTys.size())
2980 Type *NewTy = ArgTys[D.getArgumentNumber()];
2981 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2982 NewTy = VectorType::getExtendedElementVectorType(VTy);
2983 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2984 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2990 case IITDescriptor::TruncArgument: {
2991 // This may only be used when referring to a previous vector argument.
2992 if (D.getArgumentNumber() >= ArgTys.size())
2995 Type *NewTy = ArgTys[D.getArgumentNumber()];
2996 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2997 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2998 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2999 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3005 case IITDescriptor::HalfVecArgument:
3006 // This may only be used when referring to a previous vector argument.
3007 return D.getArgumentNumber() >= ArgTys.size() ||
3008 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3009 VectorType::getHalfElementsVectorType(
3010 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3011 case IITDescriptor::SameVecWidthArgument: {
3012 if (D.getArgumentNumber() >= ArgTys.size())
3014 VectorType * ReferenceType =
3015 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3016 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3017 if (!ThisArgType || !ReferenceType ||
3018 (ReferenceType->getVectorNumElements() !=
3019 ThisArgType->getVectorNumElements()))
3021 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3024 case IITDescriptor::PtrToArgument: {
3025 if (D.getArgumentNumber() >= ArgTys.size())
3027 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3028 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3029 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3031 case IITDescriptor::VecOfPtrsToElt: {
3032 if (D.getArgumentNumber() >= ArgTys.size())
3034 VectorType * ReferenceType =
3035 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3036 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3037 if (!ThisArgVecTy || !ReferenceType ||
3038 (ReferenceType->getVectorNumElements() !=
3039 ThisArgVecTy->getVectorNumElements()))
3041 PointerType *ThisArgEltTy =
3042 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3045 return (!(ThisArgEltTy->getElementType() ==
3046 ReferenceType->getVectorElementType()));
3049 llvm_unreachable("unhandled");
3052 /// \brief Verify if the intrinsic has variable arguments.
3053 /// This method is intended to be called after all the fixed arguments have been
3056 /// This method returns true on error and does not print an error message.
3058 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3059 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3060 using namespace Intrinsic;
3062 // If there are no descriptors left, then it can't be a vararg.
3066 // There should be only one descriptor remaining at this point.
3067 if (Infos.size() != 1)
3070 // Check and verify the descriptor.
3071 IITDescriptor D = Infos.front();
3072 Infos = Infos.slice(1);
3073 if (D.Kind == IITDescriptor::VarArg)
3079 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
3081 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
3082 Function *IF = CI.getCalledFunction();
3083 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3086 // Verify that the intrinsic prototype lines up with what the .td files
3088 FunctionType *IFTy = IF->getFunctionType();
3089 bool IsVarArg = IFTy->isVarArg();
3091 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3092 getIntrinsicInfoTableEntries(ID, Table);
3093 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3095 SmallVector<Type *, 4> ArgTys;
3096 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3097 "Intrinsic has incorrect return type!", IF);
3098 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3099 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3100 "Intrinsic has incorrect argument type!", IF);
3102 // Verify if the intrinsic call matches the vararg property.
3104 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3105 "Intrinsic was not defined with variable arguments!", IF);
3107 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3108 "Callsite was not defined with variable arguments!", IF);
3110 // All descriptors should be absorbed by now.
3111 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3113 // Now that we have the intrinsic ID and the actual argument types (and we
3114 // know they are legal for the intrinsic!) get the intrinsic name through the
3115 // usual means. This allows us to verify the mangling of argument types into
3117 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3118 Assert(ExpectedName == IF->getName(),
3119 "Intrinsic name not mangled correctly for type arguments! "
3124 // If the intrinsic takes MDNode arguments, verify that they are either global
3125 // or are local to *this* function.
3126 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3127 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3128 visitMetadataAsValue(*MD, CI.getParent()->getParent());
3133 case Intrinsic::ctlz: // llvm.ctlz
3134 case Intrinsic::cttz: // llvm.cttz
3135 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3136 "is_zero_undef argument of bit counting intrinsics must be a "
3140 case Intrinsic::dbg_declare: // llvm.dbg.declare
3141 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3142 "invalid llvm.dbg.declare intrinsic call 1", &CI);
3143 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
3145 case Intrinsic::dbg_value: // llvm.dbg.value
3146 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
3148 case Intrinsic::memcpy:
3149 case Intrinsic::memmove:
3150 case Intrinsic::memset: {
3151 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3153 "alignment argument of memory intrinsics must be a constant int",
3155 const APInt &AlignVal = AlignCI->getValue();
3156 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3157 "alignment argument of memory intrinsics must be a power of 2", &CI);
3158 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3159 "isvolatile argument of memory intrinsics must be a constant int",
3163 case Intrinsic::gcroot:
3164 case Intrinsic::gcwrite:
3165 case Intrinsic::gcread:
3166 if (ID == Intrinsic::gcroot) {
3168 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3169 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3170 Assert(isa<Constant>(CI.getArgOperand(1)),
3171 "llvm.gcroot parameter #2 must be a constant.", &CI);
3172 if (!AI->getType()->getElementType()->isPointerTy()) {
3173 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3174 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3175 "or argument #2 must be a non-null constant.",
3180 Assert(CI.getParent()->getParent()->hasGC(),
3181 "Enclosing function does not use GC.", &CI);
3183 case Intrinsic::init_trampoline:
3184 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3185 "llvm.init_trampoline parameter #2 must resolve to a function.",
3188 case Intrinsic::prefetch:
3189 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3190 isa<ConstantInt>(CI.getArgOperand(2)) &&
3191 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3192 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3193 "invalid arguments to llvm.prefetch", &CI);
3195 case Intrinsic::stackprotector:
3196 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3197 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3199 case Intrinsic::lifetime_start:
3200 case Intrinsic::lifetime_end:
3201 case Intrinsic::invariant_start:
3202 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3203 "size argument of memory use markers must be a constant integer",
3206 case Intrinsic::invariant_end:
3207 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3208 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3211 case Intrinsic::frameescape: {
3212 BasicBlock *BB = CI.getParent();
3213 Assert(BB == &BB->getParent()->front(),
3214 "llvm.frameescape used outside of entry block", &CI);
3215 Assert(!SawFrameEscape,
3216 "multiple calls to llvm.frameescape in one function", &CI);
3217 for (Value *Arg : CI.arg_operands()) {
3218 if (isa<ConstantPointerNull>(Arg))
3219 continue; // Null values are allowed as placeholders.
3220 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3221 Assert(AI && AI->isStaticAlloca(),
3222 "llvm.frameescape only accepts static allocas", &CI);
3224 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3225 SawFrameEscape = true;
3228 case Intrinsic::framerecover: {
3229 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3230 Function *Fn = dyn_cast<Function>(FnArg);
3231 Assert(Fn && !Fn->isDeclaration(),
3232 "llvm.framerecover first "
3233 "argument must be function defined in this module",
3235 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3236 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3238 auto &Entry = FrameEscapeInfo[Fn];
3239 Entry.second = unsigned(
3240 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3244 case Intrinsic::experimental_gc_statepoint:
3245 Assert(!CI.isInlineAsm(),
3246 "gc.statepoint support for inline assembly unimplemented", &CI);
3247 Assert(CI.getParent()->getParent()->hasGC(),
3248 "Enclosing function does not use GC.", &CI);
3250 VerifyStatepoint(ImmutableCallSite(&CI));
3252 case Intrinsic::experimental_gc_result_int:
3253 case Intrinsic::experimental_gc_result_float:
3254 case Intrinsic::experimental_gc_result_ptr:
3255 case Intrinsic::experimental_gc_result: {
3256 Assert(CI.getParent()->getParent()->hasGC(),
3257 "Enclosing function does not use GC.", &CI);
3258 // Are we tied to a statepoint properly?
3259 CallSite StatepointCS(CI.getArgOperand(0));
3260 const Function *StatepointFn =
3261 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3262 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3263 StatepointFn->getIntrinsicID() ==
3264 Intrinsic::experimental_gc_statepoint,
3265 "gc.result operand #1 must be from a statepoint", &CI,
3266 CI.getArgOperand(0));
3268 // Assert that result type matches wrapped callee.
3269 const Value *Target = StatepointCS.getArgument(0);
3270 const PointerType *PT = cast<PointerType>(Target->getType());
3271 const FunctionType *TargetFuncType =
3272 cast<FunctionType>(PT->getElementType());
3273 Assert(CI.getType() == TargetFuncType->getReturnType(),
3274 "gc.result result type does not match wrapped callee", &CI);
3277 case Intrinsic::experimental_gc_relocate: {
3278 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3280 // Check that this relocate is correctly tied to the statepoint
3282 // This is case for relocate on the unwinding path of an invoke statepoint
3283 if (ExtractValueInst *ExtractValue =
3284 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3285 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3286 "gc relocate on unwind path incorrectly linked to the statepoint",
3289 const BasicBlock *invokeBB =
3290 ExtractValue->getParent()->getUniquePredecessor();
3292 // Landingpad relocates should have only one predecessor with invoke
3293 // statepoint terminator
3294 Assert(invokeBB, "safepoints should have unique landingpads",
3295 ExtractValue->getParent());
3296 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3298 Assert(isStatepoint(invokeBB->getTerminator()),
3299 "gc relocate should be linked to a statepoint", invokeBB);
3302 // In all other cases relocate should be tied to the statepoint directly.
3303 // This covers relocates on a normal return path of invoke statepoint and
3304 // relocates of a call statepoint
3305 auto Token = CI.getArgOperand(0);
3306 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3307 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3310 // Verify rest of the relocate arguments
3312 GCRelocateOperands ops(&CI);
3313 ImmutableCallSite StatepointCS(ops.statepoint());
3315 // Both the base and derived must be piped through the safepoint
3316 Value* Base = CI.getArgOperand(1);
3317 Assert(isa<ConstantInt>(Base),
3318 "gc.relocate operand #2 must be integer offset", &CI);
3320 Value* Derived = CI.getArgOperand(2);
3321 Assert(isa<ConstantInt>(Derived),
3322 "gc.relocate operand #3 must be integer offset", &CI);
3324 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3325 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3327 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3328 "gc.relocate: statepoint base index out of bounds", &CI);
3329 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3330 "gc.relocate: statepoint derived index out of bounds", &CI);
3332 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3333 // section of the statepoint's argument
3334 Assert(StatepointCS.arg_size() > 0,
3335 "gc.statepoint: insufficient arguments");
3336 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3337 "gc.statement: number of call arguments must be constant integer");
3338 const unsigned NumCallArgs =
3339 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3340 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3341 "gc.statepoint: mismatch in number of call arguments");
3342 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3343 "gc.statepoint: number of deoptimization arguments must be "
3344 "a constant integer");
3345 const int NumDeoptArgs =
3346 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3347 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3348 const int GCParamArgsEnd = StatepointCS.arg_size();
3349 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3350 "gc.relocate: statepoint base index doesn't fall within the "
3351 "'gc parameters' section of the statepoint call",
3353 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3354 "gc.relocate: statepoint derived index doesn't fall within the "
3355 "'gc parameters' section of the statepoint call",
3358 // Assert that the result type matches the type of the relocated pointer
3359 GCRelocateOperands Operands(&CI);
3360 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3361 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3367 template <class DbgIntrinsicTy>
3368 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3369 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3370 Assert(isa<ValueAsMetadata>(MD) ||
3371 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3372 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3373 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3374 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3375 DII.getRawVariable());
3376 Assert(isa<MDExpression>(DII.getRawExpression()),
3377 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3378 DII.getRawExpression());
3380 // Queue up bit piece expressions to be verified once we can resolve
3382 if (DII.getExpression()->isValid() && DII.getExpression()->isBitPiece())
3383 QueuedBitPieceExpressions.push_back(&DII);
3385 // Ignore broken !dbg attachments; they're checked elsewhere.
3386 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3387 if (!isa<MDLocation>(N))
3390 // The inlined-at attachments for variables and !dbg attachments must agree.
3391 MDLocalVariable *Var = DII.getVariable();
3392 MDLocation *VarIA = Var->getInlinedAt();
3393 MDLocation *Loc = DII.getDebugLoc();
3394 MDLocation *LocIA = Loc ? Loc->getInlinedAt() : nullptr;
3395 BasicBlock *BB = DII.getParent();
3396 Assert(VarIA == LocIA, "mismatched variable and !dbg inlined-at", &DII, BB,
3397 BB ? BB->getParent() : nullptr, Var, VarIA, Loc, LocIA);
3400 template <class MapTy>
3401 static uint64_t getVariableSize(const MDLocalVariable &V, const MapTy &Map) {
3402 // Be careful of broken types (checked elsewhere).
3403 const Metadata *RawType = V.getRawType();
3405 // Try to get the size directly.
3406 if (auto *T = dyn_cast<MDType>(RawType))
3407 if (uint64_t Size = T->getSizeInBits())
3410 if (auto *DT = dyn_cast<MDDerivedType>(RawType)) {
3411 // Look at the base type.
3412 RawType = DT->getRawBaseType();
3416 if (auto *S = dyn_cast<MDString>(RawType)) {
3417 // Don't error on missing types (checked elsewhere).
3418 RawType = Map.lookup(S);
3422 // Missing type or size.
3430 template <class MapTy>
3431 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3432 const MapTy &TypeRefs) {
3435 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3436 V = DVI->getVariable();
3437 E = DVI->getExpression();
3439 auto *DDI = cast<DbgDeclareInst>(&I);
3440 V = DDI->getVariable();
3441 E = DDI->getExpression();
3444 assert(V && E->isValid() && E->isBitPiece() &&
3445 "Expected valid bitpieces here");
3447 // If there's no size, the type is broken, but that should be checked
3449 uint64_t VarSize = getVariableSize(*V, TypeRefs);
3453 unsigned PieceSize = E->getBitPieceSize();
3454 unsigned PieceOffset = E->getBitPieceOffset();
3455 Assert(PieceSize + PieceOffset <= VarSize,
3456 "piece is larger than or outside of variable", &I, V, E);
3457 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3460 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3461 // This is in its own function so we get an error for each bad type ref (not
3463 Assert(false, "unresolved type ref", S, N);
3466 void Verifier::verifyTypeRefs() {
3467 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3471 // Visit all the compile units again to map the type references.
3472 SmallDenseMap<const MDString *, const MDType *, 32> TypeRefs;
3473 for (auto *CU : CUs->operands())
3474 if (auto Ts = cast<MDCompileUnit>(CU)->getRetainedTypes())
3475 for (MDType *Op : Ts)
3476 if (auto *T = dyn_cast<MDCompositeType>(Op))
3477 if (auto *S = T->getRawIdentifier()) {
3478 UnresolvedTypeRefs.erase(S);
3479 TypeRefs.insert(std::make_pair(S, T));
3482 // Verify debug intrinsic bit piece expressions.
3483 for (auto *DII : QueuedBitPieceExpressions)
3484 verifyBitPieceExpression(*DII, TypeRefs);
3486 // Return early if all typerefs were resolved.
3487 if (UnresolvedTypeRefs.empty())
3490 // Sort the unresolved references by name so the output is deterministic.
3491 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3492 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3493 UnresolvedTypeRefs.end());
3494 std::sort(Unresolved.begin(), Unresolved.end(),
3495 [](const TypeRef &LHS, const TypeRef &RHS) {
3496 return LHS.first->getString() < RHS.first->getString();
3499 // Visit the unresolved refs (printing out the errors).
3500 for (const TypeRef &TR : Unresolved)
3501 visitUnresolvedTypeRef(TR.first, TR.second);
3504 //===----------------------------------------------------------------------===//
3505 // Implement the public interfaces to this file...
3506 //===----------------------------------------------------------------------===//
3508 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3509 Function &F = const_cast<Function &>(f);
3510 assert(!F.isDeclaration() && "Cannot verify external functions");
3512 raw_null_ostream NullStr;
3513 Verifier V(OS ? *OS : NullStr);
3515 // Note that this function's return value is inverted from what you would
3516 // expect of a function called "verify".
3517 return !V.verify(F);
3520 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3521 raw_null_ostream NullStr;
3522 Verifier V(OS ? *OS : NullStr);
3524 bool Broken = false;
3525 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3526 if (!I->isDeclaration() && !I->isMaterializable())
3527 Broken |= !V.verify(*I);
3529 // Note that this function's return value is inverted from what you would
3530 // expect of a function called "verify".
3531 return !V.verify(M) || Broken;
3535 struct VerifierLegacyPass : public FunctionPass {
3541 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3542 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3544 explicit VerifierLegacyPass(bool FatalErrors)
3545 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3546 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3549 bool runOnFunction(Function &F) override {
3550 if (!V.verify(F) && FatalErrors)
3551 report_fatal_error("Broken function found, compilation aborted!");
3556 bool doFinalization(Module &M) override {
3557 if (!V.verify(M) && FatalErrors)
3558 report_fatal_error("Broken module found, compilation aborted!");
3563 void getAnalysisUsage(AnalysisUsage &AU) const override {
3564 AU.setPreservesAll();
3569 char VerifierLegacyPass::ID = 0;
3570 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3572 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3573 return new VerifierLegacyPass(FatalErrors);
3576 PreservedAnalyses VerifierPass::run(Module &M) {
3577 if (verifyModule(M, &dbgs()) && FatalErrors)
3578 report_fatal_error("Broken module found, compilation aborted!");
3580 return PreservedAnalyses::all();
3583 PreservedAnalyses VerifierPass::run(Function &F) {
3584 if (verifyFunction(F, &dbgs()) && FatalErrors)
3585 report_fatal_error("Broken function found, compilation aborted!");
3587 return PreservedAnalyses::all();