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.
92 explicit VerifierSupport(raw_ostream &OS)
93 : OS(OS), M(nullptr), Broken(false), EverBroken(false) {}
96 void Write(const Value *V) {
99 if (isa<Instruction>(V)) {
102 V->printAsOperand(OS, true, M);
107 void Write(const Metadata *MD) {
114 void Write(const NamedMDNode *NMD) {
121 void Write(Type *T) {
127 void Write(const Comdat *C) {
133 template <typename T1, typename... Ts>
134 void WriteTs(const T1 &V1, const Ts &... Vs) {
139 template <typename... Ts> void WriteTs() {}
142 /// \brief A check failed, so printout out the condition and the message.
144 /// This provides a nice place to put a breakpoint if you want to see why
145 /// something is not correct.
146 void CheckFailed(const Twine &Message) {
147 OS << Message << '\n';
148 EverBroken = Broken = true;
151 /// \brief A check failed (with values to print).
153 /// This calls the Message-only version so that the above is easier to set a
155 template <typename T1, typename... Ts>
156 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
157 CheckFailed(Message);
162 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
163 friend class InstVisitor<Verifier>;
165 LLVMContext *Context;
168 /// \brief When verifying a basic block, keep track of all of the
169 /// instructions we have seen so far.
171 /// This allows us to do efficient dominance checks for the case when an
172 /// instruction has an operand that is an instruction in the same block.
173 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
175 /// \brief Keep track of the metadata nodes that have been checked already.
176 SmallPtrSet<const Metadata *, 32> MDNodes;
178 /// \brief Track string-based type references.
179 SmallDenseMap<const MDString *, const MDNode *, 32> TypeRefs;
181 /// \brief The personality function referenced by the LandingPadInsts.
182 /// All LandingPadInsts within the same function must use the same
183 /// personality function.
184 const Value *PersonalityFn;
186 /// \brief Whether we've seen a call to @llvm.frameescape in this function
190 /// Stores the count of how many objects were passed to llvm.frameescape for a
191 /// given function and the largest index passed to llvm.framerecover.
192 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
195 explicit Verifier(raw_ostream &OS)
196 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
197 SawFrameEscape(false) {}
199 bool verify(const Function &F) {
201 Context = &M->getContext();
203 // First ensure the function is well-enough formed to compute dominance
206 OS << "Function '" << F.getName()
207 << "' does not contain an entry block!\n";
210 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
211 if (I->empty() || !I->back().isTerminator()) {
212 OS << "Basic Block in function '" << F.getName()
213 << "' does not have terminator!\n";
214 I->printAsOperand(OS, true);
220 // Now directly compute a dominance tree. We don't rely on the pass
221 // manager to provide this as it isolates us from a potentially
222 // out-of-date dominator tree and makes it significantly more complex to
223 // run this code outside of a pass manager.
224 // FIXME: It's really gross that we have to cast away constness here.
225 DT.recalculate(const_cast<Function &>(F));
228 // FIXME: We strip const here because the inst visitor strips const.
229 visit(const_cast<Function &>(F));
230 InstsInThisBlock.clear();
231 PersonalityFn = nullptr;
232 SawFrameEscape = false;
237 bool verify(const Module &M) {
239 Context = &M.getContext();
242 // Scan through, checking all of the external function's linkage now...
243 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
244 visitGlobalValue(*I);
246 // Check to make sure function prototypes are okay.
247 if (I->isDeclaration())
251 // Now that we've visited every function, verify that we never asked to
252 // recover a frame index that wasn't escaped.
253 verifyFrameRecoverIndices();
255 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
257 visitGlobalVariable(*I);
259 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
261 visitGlobalAlias(*I);
263 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
264 E = M.named_metadata_end();
266 visitNamedMDNode(*I);
268 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
269 visitComdat(SMEC.getValue());
272 visitModuleIdents(M);
274 // Verify type referneces last.
281 // Verification methods...
282 void visitGlobalValue(const GlobalValue &GV);
283 void visitGlobalVariable(const GlobalVariable &GV);
284 void visitGlobalAlias(const GlobalAlias &GA);
285 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
286 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
287 const GlobalAlias &A, const Constant &C);
288 void visitNamedMDNode(const NamedMDNode &NMD);
289 void visitMDNode(const MDNode &MD);
290 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
291 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
292 void visitComdat(const Comdat &C);
293 void visitModuleIdents(const Module &M);
294 void visitModuleFlags(const Module &M);
295 void visitModuleFlag(const MDNode *Op,
296 DenseMap<const MDString *, const MDNode *> &SeenIDs,
297 SmallVectorImpl<const MDNode *> &Requirements);
298 void visitFunction(const Function &F);
299 void visitBasicBlock(BasicBlock &BB);
300 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
302 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
303 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
304 #include "llvm/IR/Metadata.def"
305 void visitMDScope(const MDScope &N);
306 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
307 void visitMDVariable(const MDVariable &N);
308 void visitMDLexicalBlockBase(const MDLexicalBlockBase &N);
309 void visitMDTemplateParameter(const MDTemplateParameter &N);
311 /// \brief Check for a valid string-based type reference.
313 /// Checks if \c MD is a string-based type reference. If it is, keeps track
314 /// of it (and its user, \c N) for error messages later.
315 bool isValidUUID(const MDNode &N, const Metadata *MD);
317 /// \brief Check for a valid type reference.
319 /// Checks for subclasses of \a MDType, or \a isValidUUID().
320 bool isTypeRef(const MDNode &N, const Metadata *MD);
322 /// \brief Check for a valid scope reference.
324 /// Checks for subclasses of \a MDScope, or \a isValidUUID().
325 bool isScopeRef(const MDNode &N, const Metadata *MD);
327 /// \brief Check for a valid debug info reference.
329 /// Checks for subclasses of \a DebugNode, or \a isValidUUID().
330 bool isDIRef(const MDNode &N, const Metadata *MD);
332 // InstVisitor overrides...
333 using InstVisitor<Verifier>::visit;
334 void visit(Instruction &I);
336 void visitTruncInst(TruncInst &I);
337 void visitZExtInst(ZExtInst &I);
338 void visitSExtInst(SExtInst &I);
339 void visitFPTruncInst(FPTruncInst &I);
340 void visitFPExtInst(FPExtInst &I);
341 void visitFPToUIInst(FPToUIInst &I);
342 void visitFPToSIInst(FPToSIInst &I);
343 void visitUIToFPInst(UIToFPInst &I);
344 void visitSIToFPInst(SIToFPInst &I);
345 void visitIntToPtrInst(IntToPtrInst &I);
346 void visitPtrToIntInst(PtrToIntInst &I);
347 void visitBitCastInst(BitCastInst &I);
348 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
349 void visitPHINode(PHINode &PN);
350 void visitBinaryOperator(BinaryOperator &B);
351 void visitICmpInst(ICmpInst &IC);
352 void visitFCmpInst(FCmpInst &FC);
353 void visitExtractElementInst(ExtractElementInst &EI);
354 void visitInsertElementInst(InsertElementInst &EI);
355 void visitShuffleVectorInst(ShuffleVectorInst &EI);
356 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
357 void visitCallInst(CallInst &CI);
358 void visitInvokeInst(InvokeInst &II);
359 void visitGetElementPtrInst(GetElementPtrInst &GEP);
360 void visitLoadInst(LoadInst &LI);
361 void visitStoreInst(StoreInst &SI);
362 void verifyDominatesUse(Instruction &I, unsigned i);
363 void visitInstruction(Instruction &I);
364 void visitTerminatorInst(TerminatorInst &I);
365 void visitBranchInst(BranchInst &BI);
366 void visitReturnInst(ReturnInst &RI);
367 void visitSwitchInst(SwitchInst &SI);
368 void visitIndirectBrInst(IndirectBrInst &BI);
369 void visitSelectInst(SelectInst &SI);
370 void visitUserOp1(Instruction &I);
371 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
372 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
373 template <class DbgIntrinsicTy>
374 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
375 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
376 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
377 void visitFenceInst(FenceInst &FI);
378 void visitAllocaInst(AllocaInst &AI);
379 void visitExtractValueInst(ExtractValueInst &EVI);
380 void visitInsertValueInst(InsertValueInst &IVI);
381 void visitLandingPadInst(LandingPadInst &LPI);
383 void VerifyCallSite(CallSite CS);
384 void verifyMustTailCall(CallInst &CI);
385 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
386 unsigned ArgNo, std::string &Suffix);
387 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
388 SmallVectorImpl<Type *> &ArgTys);
389 bool VerifyIntrinsicIsVarArg(bool isVarArg,
390 ArrayRef<Intrinsic::IITDescriptor> &Infos);
391 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
392 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
394 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
395 bool isReturnValue, const Value *V);
396 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
399 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
400 void VerifyStatepoint(ImmutableCallSite CS);
401 void verifyFrameRecoverIndices();
403 // Module-level debug info verification...
404 void verifyTypeRefs();
405 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
407 } // End anonymous namespace
409 // Assert - We know that cond should be true, if not print an error message.
410 #define Assert(C, ...) \
411 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
413 void Verifier::visit(Instruction &I) {
414 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
415 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
416 InstVisitor<Verifier>::visit(I);
420 void Verifier::visitGlobalValue(const GlobalValue &GV) {
421 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
422 GV.hasExternalWeakLinkage(),
423 "Global is external, but doesn't have external or weak linkage!", &GV);
425 Assert(GV.getAlignment() <= Value::MaximumAlignment,
426 "huge alignment values are unsupported", &GV);
427 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
428 "Only global variables can have appending linkage!", &GV);
430 if (GV.hasAppendingLinkage()) {
431 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
432 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
433 "Only global arrays can have appending linkage!", GVar);
437 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
438 if (GV.hasInitializer()) {
439 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
440 "Global variable initializer type does not match global "
444 // If the global has common linkage, it must have a zero initializer and
445 // cannot be constant.
446 if (GV.hasCommonLinkage()) {
447 Assert(GV.getInitializer()->isNullValue(),
448 "'common' global must have a zero initializer!", &GV);
449 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
451 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
454 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
455 "invalid linkage type for global declaration", &GV);
458 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
459 GV.getName() == "llvm.global_dtors")) {
460 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
461 "invalid linkage for intrinsic global variable", &GV);
462 // Don't worry about emitting an error for it not being an array,
463 // visitGlobalValue will complain on appending non-array.
464 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
465 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
466 PointerType *FuncPtrTy =
467 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
468 // FIXME: Reject the 2-field form in LLVM 4.0.
470 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
471 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
472 STy->getTypeAtIndex(1) == FuncPtrTy,
473 "wrong type for intrinsic global variable", &GV);
474 if (STy->getNumElements() == 3) {
475 Type *ETy = STy->getTypeAtIndex(2);
476 Assert(ETy->isPointerTy() &&
477 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
478 "wrong type for intrinsic global variable", &GV);
483 if (GV.hasName() && (GV.getName() == "llvm.used" ||
484 GV.getName() == "llvm.compiler.used")) {
485 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
486 "invalid linkage for intrinsic global variable", &GV);
487 Type *GVType = GV.getType()->getElementType();
488 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
489 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
490 Assert(PTy, "wrong type for intrinsic global variable", &GV);
491 if (GV.hasInitializer()) {
492 const Constant *Init = GV.getInitializer();
493 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
494 Assert(InitArray, "wrong initalizer for intrinsic global variable",
496 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
497 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
498 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
500 "invalid llvm.used member", V);
501 Assert(V->hasName(), "members of llvm.used must be named", V);
507 Assert(!GV.hasDLLImportStorageClass() ||
508 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
509 GV.hasAvailableExternallyLinkage(),
510 "Global is marked as dllimport, but not external", &GV);
512 if (!GV.hasInitializer()) {
513 visitGlobalValue(GV);
517 // Walk any aggregate initializers looking for bitcasts between address spaces
518 SmallPtrSet<const Value *, 4> Visited;
519 SmallVector<const Value *, 4> WorkStack;
520 WorkStack.push_back(cast<Value>(GV.getInitializer()));
522 while (!WorkStack.empty()) {
523 const Value *V = WorkStack.pop_back_val();
524 if (!Visited.insert(V).second)
527 if (const User *U = dyn_cast<User>(V)) {
528 WorkStack.append(U->op_begin(), U->op_end());
531 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
532 VerifyConstantExprBitcastType(CE);
538 visitGlobalValue(GV);
541 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
542 SmallPtrSet<const GlobalAlias*, 4> Visited;
544 visitAliaseeSubExpr(Visited, GA, C);
547 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
548 const GlobalAlias &GA, const Constant &C) {
549 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
550 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
552 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
553 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
555 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
558 // Only continue verifying subexpressions of GlobalAliases.
559 // Do not recurse into global initializers.
564 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
565 VerifyConstantExprBitcastType(CE);
567 for (const Use &U : C.operands()) {
569 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
570 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
571 else if (const auto *C2 = dyn_cast<Constant>(V))
572 visitAliaseeSubExpr(Visited, GA, *C2);
576 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
577 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
578 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
579 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
580 "weak_odr, or external linkage!",
582 const Constant *Aliasee = GA.getAliasee();
583 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
584 Assert(GA.getType() == Aliasee->getType(),
585 "Alias and aliasee types should match!", &GA);
587 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
588 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
590 visitAliaseeSubExpr(GA, *Aliasee);
592 visitGlobalValue(GA);
595 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
596 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
597 MDNode *MD = NMD.getOperand(i);
599 if (NMD.getName() == "llvm.dbg.cu") {
600 Assert(MD && isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
610 void Verifier::visitMDNode(const MDNode &MD) {
611 // Only visit each node once. Metadata can be mutually recursive, so this
612 // avoids infinite recursion here, as well as being an optimization.
613 if (!MDNodes.insert(&MD).second)
616 switch (MD.getMetadataID()) {
618 llvm_unreachable("Invalid MDNode subclass");
619 case Metadata::MDTupleKind:
621 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
622 case Metadata::CLASS##Kind: \
623 visit##CLASS(cast<CLASS>(MD)); \
625 #include "llvm/IR/Metadata.def"
628 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
629 Metadata *Op = MD.getOperand(i);
632 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
634 if (auto *N = dyn_cast<MDNode>(Op)) {
638 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
639 visitValueAsMetadata(*V, nullptr);
644 // Check these last, so we diagnose problems in operands first.
645 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
646 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
649 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
650 Assert(MD.getValue(), "Expected valid value", &MD);
651 Assert(!MD.getValue()->getType()->isMetadataTy(),
652 "Unexpected metadata round-trip through values", &MD, MD.getValue());
654 auto *L = dyn_cast<LocalAsMetadata>(&MD);
658 Assert(F, "function-local metadata used outside a function", L);
660 // If this was an instruction, bb, or argument, verify that it is in the
661 // function that we expect.
662 Function *ActualF = nullptr;
663 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
664 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
665 ActualF = I->getParent()->getParent();
666 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
667 ActualF = BB->getParent();
668 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
669 ActualF = A->getParent();
670 assert(ActualF && "Unimplemented function local metadata case!");
672 Assert(ActualF == F, "function-local metadata used in wrong function", L);
675 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
676 Metadata *MD = MDV.getMetadata();
677 if (auto *N = dyn_cast<MDNode>(MD)) {
682 // Only visit each node once. Metadata can be mutually recursive, so this
683 // avoids infinite recursion here, as well as being an optimization.
684 if (!MDNodes.insert(MD).second)
687 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
688 visitValueAsMetadata(*V, F);
691 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
692 auto *S = dyn_cast<MDString>(MD);
695 if (S->getString().empty())
698 // Keep track of names of types referenced via UUID so we can check that they
700 TypeRefs.insert(std::make_pair(S, &N));
704 /// \brief Check if a value can be a reference to a type.
705 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
706 return !MD || isValidUUID(N, MD) || isa<MDType>(MD);
709 /// \brief Check if a value can be a ScopeRef.
710 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
711 return !MD || isValidUUID(N, MD) || isa<MDScope>(MD);
714 /// \brief Check if a value can be a debug info ref.
715 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
716 return !MD || isValidUUID(N, MD) || isa<DebugNode>(MD);
720 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
721 for (Metadata *MD : N.operands()) {
734 bool isValidMetadataArray(const MDTuple &N) {
735 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
739 bool isValidMetadataNullArray(const MDTuple &N) {
740 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
743 void Verifier::visitMDLocation(const MDLocation &N) {
744 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
745 "location requires a valid scope", &N, N.getRawScope());
746 if (auto *IA = N.getRawInlinedAt())
747 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
750 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
751 Assert(N.getTag(), "invalid tag", &N);
754 void Verifier::visitMDScope(const MDScope &N) {
755 if (auto *F = N.getRawFile())
756 Assert(isa<MDFile>(F), "invalid file", &N, F);
759 void Verifier::visitMDSubrange(const MDSubrange &N) {
760 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
761 Assert(N.getCount() >= -1, "invalid subrange count", &N);
764 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
765 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
768 void Verifier::visitMDBasicType(const MDBasicType &N) {
769 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
770 N.getTag() == dwarf::DW_TAG_unspecified_type,
774 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
775 // Common scope checks.
778 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
779 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
782 // FIXME: Sink this into the subclass verifies.
783 if (!N.getFile() || N.getFile()->getFilename().empty()) {
784 // Check whether the filename is allowed to be empty.
785 uint16_t Tag = N.getTag();
787 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
788 Tag == dwarf::DW_TAG_pointer_type ||
789 Tag == dwarf::DW_TAG_ptr_to_member_type ||
790 Tag == dwarf::DW_TAG_reference_type ||
791 Tag == dwarf::DW_TAG_rvalue_reference_type ||
792 Tag == dwarf::DW_TAG_restrict_type ||
793 Tag == dwarf::DW_TAG_array_type ||
794 Tag == dwarf::DW_TAG_enumeration_type ||
795 Tag == dwarf::DW_TAG_subroutine_type ||
796 Tag == dwarf::DW_TAG_inheritance || Tag == dwarf::DW_TAG_friend ||
797 Tag == dwarf::DW_TAG_structure_type ||
798 Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef,
799 "derived/composite type requires a filename", &N, N.getFile());
803 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
804 // Common derived type checks.
805 visitMDDerivedTypeBase(N);
807 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
808 N.getTag() == dwarf::DW_TAG_pointer_type ||
809 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
810 N.getTag() == dwarf::DW_TAG_reference_type ||
811 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
812 N.getTag() == dwarf::DW_TAG_const_type ||
813 N.getTag() == dwarf::DW_TAG_volatile_type ||
814 N.getTag() == dwarf::DW_TAG_restrict_type ||
815 N.getTag() == dwarf::DW_TAG_member ||
816 N.getTag() == dwarf::DW_TAG_inheritance ||
817 N.getTag() == dwarf::DW_TAG_friend,
819 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
820 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
825 static bool hasConflictingReferenceFlags(unsigned Flags) {
826 return (Flags & DebugNode::FlagLValueReference) &&
827 (Flags & DebugNode::FlagRValueReference);
830 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
831 // Common derived type checks.
832 visitMDDerivedTypeBase(N);
834 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
835 N.getTag() == dwarf::DW_TAG_structure_type ||
836 N.getTag() == dwarf::DW_TAG_union_type ||
837 N.getTag() == dwarf::DW_TAG_enumeration_type ||
838 N.getTag() == dwarf::DW_TAG_subroutine_type ||
839 N.getTag() == dwarf::DW_TAG_class_type,
842 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
843 "invalid composite elements", &N, N.getRawElements());
844 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
845 N.getRawVTableHolder());
846 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
847 "invalid composite elements", &N, N.getRawElements());
848 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
852 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
853 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
854 if (auto *Types = N.getRawTypeArray()) {
855 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
856 for (Metadata *Ty : N.getTypeArray()->operands()) {
857 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
860 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
864 void Verifier::visitMDFile(const MDFile &N) {
865 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
868 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
869 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
871 // Don't bother verifying the compilation directory or producer string
872 // as those could be empty.
873 Assert(N.getRawFile() && isa<MDFile>(N.getRawFile()),
874 "invalid file", &N, N.getRawFile());
875 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
878 if (auto *Array = N.getRawEnumTypes()) {
879 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
880 for (Metadata *Op : N.getEnumTypes()->operands()) {
881 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
882 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
883 "invalid enum type", &N, N.getEnumTypes(), Op);
886 if (auto *Array = N.getRawRetainedTypes()) {
887 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
888 for (Metadata *Op : N.getRetainedTypes()->operands()) {
889 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
892 if (auto *Array = N.getRawSubprograms()) {
893 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
894 for (Metadata *Op : N.getSubprograms()->operands()) {
895 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
898 if (auto *Array = N.getRawGlobalVariables()) {
899 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
900 for (Metadata *Op : N.getGlobalVariables()->operands()) {
901 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
905 if (auto *Array = N.getRawImportedEntities()) {
906 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
907 for (Metadata *Op : N.getImportedEntities()->operands()) {
908 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
914 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
915 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
916 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
917 if (auto *T = N.getRawType())
918 Assert(isa<MDSubroutineType>(T), "invalid subroutine type", &N, T);
919 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
920 N.getRawContainingType());
921 if (auto *RawF = N.getRawFunction()) {
922 auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
923 auto *F = FMD ? FMD->getValue() : nullptr;
924 auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
925 Assert(F && FT && isa<FunctionType>(FT->getElementType()),
926 "invalid function", &N, F, FT);
928 if (N.getRawTemplateParams()) {
929 auto *Params = dyn_cast<MDTuple>(N.getRawTemplateParams());
930 Assert(Params, "invalid template params", &N, Params);
931 for (Metadata *Op : Params->operands()) {
932 Assert(Op && isa<MDTemplateParameter>(Op), "invalid template parameter",
936 if (auto *S = N.getRawDeclaration()) {
937 Assert(isa<MDSubprogram>(S) && !cast<MDSubprogram>(S)->isDefinition(),
938 "invalid subprogram declaration", &N, S);
940 if (N.getRawVariables()) {
941 auto *Vars = dyn_cast<MDTuple>(N.getRawVariables());
942 Assert(Vars, "invalid variable list", &N, Vars);
943 for (Metadata *Op : Vars->operands()) {
944 Assert(Op && isa<MDLocalVariable>(Op), "invalid local variable", &N, Vars,
948 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
951 if (!N.getFunction())
954 // FIXME: Should this be looking through bitcasts?
955 auto *F = dyn_cast<Function>(N.getFunction()->getValue());
959 // Check that all !dbg attachments lead to back to N (or, at least, another
960 // subprogram that describes the same function).
962 // FIXME: Check this incrementally while visiting !dbg attachments.
963 // FIXME: Only check when N is the canonical subprogram for F.
964 SmallPtrSet<const MDNode *, 32> Seen;
967 // Be careful about using MDLocation here since we might be dealing with
968 // broken code (this is the Verifier after all).
970 dyn_cast_or_null<MDLocation>(I.getDebugLoc().getAsMDNode());
973 if (!Seen.insert(DL).second)
976 MDLocalScope *Scope = DL->getInlinedAtScope();
977 if (Scope && !Seen.insert(Scope).second)
980 MDSubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
981 if (SP && !Seen.insert(SP).second)
984 // FIXME: Once N is canonical, check "SP == &N".
985 Assert(DISubprogram(SP).describes(F),
986 "!dbg attachment points at wrong subprogram for function", &N, F,
991 void Verifier::visitMDLexicalBlockBase(const MDLexicalBlockBase &N) {
992 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
993 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
994 "invalid local scope", &N, N.getRawScope());
997 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
998 visitMDLexicalBlockBase(N);
1000 Assert(N.getLine() || !N.getColumn(),
1001 "cannot have column info without line info", &N);
1004 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
1005 visitMDLexicalBlockBase(N);
1008 void Verifier::visitMDNamespace(const MDNamespace &N) {
1009 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1010 if (auto *S = N.getRawScope())
1011 Assert(isa<MDScope>(S), "invalid scope ref", &N, S);
1014 void Verifier::visitMDTemplateParameter(const MDTemplateParameter &N) {
1015 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1018 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
1019 visitMDTemplateParameter(N);
1021 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1025 void Verifier::visitMDTemplateValueParameter(
1026 const MDTemplateValueParameter &N) {
1027 visitMDTemplateParameter(N);
1029 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1030 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1031 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1035 void Verifier::visitMDVariable(const MDVariable &N) {
1036 if (auto *S = N.getRawScope())
1037 Assert(isa<MDScope>(S), "invalid scope", &N, S);
1038 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1039 if (auto *F = N.getRawFile())
1040 Assert(isa<MDFile>(F), "invalid file", &N, F);
1043 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
1044 // Checks common to all variables.
1047 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1048 Assert(!N.getName().empty(), "missing global variable name", &N);
1049 if (auto *V = N.getRawVariable()) {
1050 Assert(isa<ConstantAsMetadata>(V) &&
1051 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1052 "invalid global varaible ref", &N, V);
1054 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1055 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
1060 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
1061 // Checks common to all variables.
1064 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
1065 N.getTag() == dwarf::DW_TAG_arg_variable,
1067 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
1068 "local variable requires a valid scope", &N, N.getRawScope());
1069 if (auto *IA = N.getRawInlinedAt())
1070 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
1074 void Verifier::visitMDExpression(const MDExpression &N) {
1075 Assert(N.isValid(), "invalid expression", &N);
1078 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
1079 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1080 if (auto *T = N.getRawType())
1081 Assert(isa<MDType>(T), "invalid type ref", &N, T);
1082 if (auto *F = N.getRawFile())
1083 Assert(isa<MDFile>(F), "invalid file", &N, F);
1086 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
1087 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1088 N.getTag() == dwarf::DW_TAG_imported_declaration,
1090 if (auto *S = N.getRawScope())
1091 Assert(isa<MDScope>(S), "invalid scope for imported entity", &N, S);
1092 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1096 void Verifier::visitComdat(const Comdat &C) {
1097 // The Module is invalid if the GlobalValue has private linkage. Entities
1098 // with private linkage don't have entries in the symbol table.
1099 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1100 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1104 void Verifier::visitModuleIdents(const Module &M) {
1105 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1109 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1110 // Scan each llvm.ident entry and make sure that this requirement is met.
1111 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1112 const MDNode *N = Idents->getOperand(i);
1113 Assert(N->getNumOperands() == 1,
1114 "incorrect number of operands in llvm.ident metadata", N);
1115 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1116 ("invalid value for llvm.ident metadata entry operand"
1117 "(the operand should be a string)"),
1122 void Verifier::visitModuleFlags(const Module &M) {
1123 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1126 // Scan each flag, and track the flags and requirements.
1127 DenseMap<const MDString*, const MDNode*> SeenIDs;
1128 SmallVector<const MDNode*, 16> Requirements;
1129 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1130 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1133 // Validate that the requirements in the module are valid.
1134 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1135 const MDNode *Requirement = Requirements[I];
1136 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1137 const Metadata *ReqValue = Requirement->getOperand(1);
1139 const MDNode *Op = SeenIDs.lookup(Flag);
1141 CheckFailed("invalid requirement on flag, flag is not present in module",
1146 if (Op->getOperand(2) != ReqValue) {
1147 CheckFailed(("invalid requirement on flag, "
1148 "flag does not have the required value"),
1156 Verifier::visitModuleFlag(const MDNode *Op,
1157 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1158 SmallVectorImpl<const MDNode *> &Requirements) {
1159 // Each module flag should have three arguments, the merge behavior (a
1160 // constant int), the flag ID (an MDString), and the value.
1161 Assert(Op->getNumOperands() == 3,
1162 "incorrect number of operands in module flag", Op);
1163 Module::ModFlagBehavior MFB;
1164 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1166 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1167 "invalid behavior operand in module flag (expected constant integer)",
1170 "invalid behavior operand in module flag (unexpected constant)",
1173 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1174 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1177 // Sanity check the values for behaviors with additional requirements.
1180 case Module::Warning:
1181 case Module::Override:
1182 // These behavior types accept any value.
1185 case Module::Require: {
1186 // The value should itself be an MDNode with two operands, a flag ID (an
1187 // MDString), and a value.
1188 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1189 Assert(Value && Value->getNumOperands() == 2,
1190 "invalid value for 'require' module flag (expected metadata pair)",
1192 Assert(isa<MDString>(Value->getOperand(0)),
1193 ("invalid value for 'require' module flag "
1194 "(first value operand should be a string)"),
1195 Value->getOperand(0));
1197 // Append it to the list of requirements, to check once all module flags are
1199 Requirements.push_back(Value);
1203 case Module::Append:
1204 case Module::AppendUnique: {
1205 // These behavior types require the operand be an MDNode.
1206 Assert(isa<MDNode>(Op->getOperand(2)),
1207 "invalid value for 'append'-type module flag "
1208 "(expected a metadata node)",
1214 // Unless this is a "requires" flag, check the ID is unique.
1215 if (MFB != Module::Require) {
1216 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1218 "module flag identifiers must be unique (or of 'require' type)", ID);
1222 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1223 bool isFunction, const Value *V) {
1224 unsigned Slot = ~0U;
1225 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1226 if (Attrs.getSlotIndex(I) == Idx) {
1231 assert(Slot != ~0U && "Attribute set inconsistency!");
1233 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1235 if (I->isStringAttribute())
1238 if (I->getKindAsEnum() == Attribute::NoReturn ||
1239 I->getKindAsEnum() == Attribute::NoUnwind ||
1240 I->getKindAsEnum() == Attribute::NoInline ||
1241 I->getKindAsEnum() == Attribute::AlwaysInline ||
1242 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1243 I->getKindAsEnum() == Attribute::StackProtect ||
1244 I->getKindAsEnum() == Attribute::StackProtectReq ||
1245 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1246 I->getKindAsEnum() == Attribute::NoRedZone ||
1247 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1248 I->getKindAsEnum() == Attribute::Naked ||
1249 I->getKindAsEnum() == Attribute::InlineHint ||
1250 I->getKindAsEnum() == Attribute::StackAlignment ||
1251 I->getKindAsEnum() == Attribute::UWTable ||
1252 I->getKindAsEnum() == Attribute::NonLazyBind ||
1253 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1254 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1255 I->getKindAsEnum() == Attribute::SanitizeThread ||
1256 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1257 I->getKindAsEnum() == Attribute::MinSize ||
1258 I->getKindAsEnum() == Attribute::NoDuplicate ||
1259 I->getKindAsEnum() == Attribute::Builtin ||
1260 I->getKindAsEnum() == Attribute::NoBuiltin ||
1261 I->getKindAsEnum() == Attribute::Cold ||
1262 I->getKindAsEnum() == Attribute::OptimizeNone ||
1263 I->getKindAsEnum() == Attribute::JumpTable) {
1265 CheckFailed("Attribute '" + I->getAsString() +
1266 "' only applies to functions!", V);
1269 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1270 I->getKindAsEnum() == Attribute::ReadNone) {
1272 CheckFailed("Attribute '" + I->getAsString() +
1273 "' does not apply to function returns");
1276 } else if (isFunction) {
1277 CheckFailed("Attribute '" + I->getAsString() +
1278 "' does not apply to functions!", V);
1284 // VerifyParameterAttrs - Check the given attributes for an argument or return
1285 // value of the specified type. The value V is printed in error messages.
1286 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1287 bool isReturnValue, const Value *V) {
1288 if (!Attrs.hasAttributes(Idx))
1291 VerifyAttributeTypes(Attrs, Idx, false, V);
1294 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1295 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1296 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1297 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1298 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1299 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1300 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1301 "'returned' do not apply to return values!",
1304 // Check for mutually incompatible attributes. Only inreg is compatible with
1306 unsigned AttrCount = 0;
1307 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1308 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1309 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1310 Attrs.hasAttribute(Idx, Attribute::InReg);
1311 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1312 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1313 "and 'sret' are incompatible!",
1316 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1317 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1319 "'inalloca and readonly' are incompatible!",
1322 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1323 Attrs.hasAttribute(Idx, Attribute::Returned)),
1325 "'sret and returned' are incompatible!",
1328 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1329 Attrs.hasAttribute(Idx, Attribute::SExt)),
1331 "'zeroext and signext' are incompatible!",
1334 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1335 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1337 "'readnone and readonly' are incompatible!",
1340 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1341 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1343 "'noinline and alwaysinline' are incompatible!",
1346 Assert(!AttrBuilder(Attrs, Idx)
1347 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1348 "Wrong types for attribute: " +
1349 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1352 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1353 SmallPtrSet<const Type*, 4> Visited;
1354 if (!PTy->getElementType()->isSized(&Visited)) {
1355 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1356 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1357 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1361 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1362 "Attribute 'byval' only applies to parameters with pointer type!",
1367 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1368 // The value V is printed in error messages.
1369 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1371 if (Attrs.isEmpty())
1374 bool SawNest = false;
1375 bool SawReturned = false;
1376 bool SawSRet = false;
1378 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1379 unsigned Idx = Attrs.getSlotIndex(i);
1383 Ty = FT->getReturnType();
1384 else if (Idx-1 < FT->getNumParams())
1385 Ty = FT->getParamType(Idx-1);
1387 break; // VarArgs attributes, verified elsewhere.
1389 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1394 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1395 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1399 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1400 Assert(!SawReturned, "More than one parameter has attribute returned!",
1402 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1404 "argument and return types for 'returned' attribute",
1409 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1410 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1411 Assert(Idx == 1 || Idx == 2,
1412 "Attribute 'sret' is not on first or second parameter!", V);
1416 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1417 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1422 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1425 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1428 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1429 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1430 "Attributes 'readnone and readonly' are incompatible!", V);
1433 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1434 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1435 Attribute::AlwaysInline)),
1436 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1438 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1439 Attribute::OptimizeNone)) {
1440 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1441 "Attribute 'optnone' requires 'noinline'!", V);
1443 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1444 Attribute::OptimizeForSize),
1445 "Attributes 'optsize and optnone' are incompatible!", V);
1447 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1448 "Attributes 'minsize and optnone' are incompatible!", V);
1451 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1452 Attribute::JumpTable)) {
1453 const GlobalValue *GV = cast<GlobalValue>(V);
1454 Assert(GV->hasUnnamedAddr(),
1455 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1459 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1460 if (CE->getOpcode() != Instruction::BitCast)
1463 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1465 "Invalid bitcast", CE);
1468 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1469 if (Attrs.getNumSlots() == 0)
1472 unsigned LastSlot = Attrs.getNumSlots() - 1;
1473 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1474 if (LastIndex <= Params
1475 || (LastIndex == AttributeSet::FunctionIndex
1476 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1482 /// \brief Verify that statepoint intrinsic is well formed.
1483 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1484 assert(CS.getCalledFunction() &&
1485 CS.getCalledFunction()->getIntrinsicID() ==
1486 Intrinsic::experimental_gc_statepoint);
1488 const Instruction &CI = *CS.getInstruction();
1490 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1491 "gc.statepoint must read and write memory to preserve "
1492 "reordering restrictions required by safepoint semantics",
1495 const Value *Target = CS.getArgument(0);
1496 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1497 Assert(PT && PT->getElementType()->isFunctionTy(),
1498 "gc.statepoint callee must be of function pointer type", &CI, Target);
1499 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1501 const Value *NumCallArgsV = CS.getArgument(1);
1502 Assert(isa<ConstantInt>(NumCallArgsV),
1503 "gc.statepoint number of arguments to underlying call "
1504 "must be constant integer",
1506 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1507 Assert(NumCallArgs >= 0,
1508 "gc.statepoint number of arguments to underlying call "
1511 const int NumParams = (int)TargetFuncType->getNumParams();
1512 if (TargetFuncType->isVarArg()) {
1513 Assert(NumCallArgs >= NumParams,
1514 "gc.statepoint mismatch in number of vararg call args", &CI);
1516 // TODO: Remove this limitation
1517 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1518 "gc.statepoint doesn't support wrapping non-void "
1519 "vararg functions yet",
1522 Assert(NumCallArgs == NumParams,
1523 "gc.statepoint mismatch in number of call args", &CI);
1525 const Value *Unused = CS.getArgument(2);
1526 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1527 "gc.statepoint parameter #3 must be zero", &CI);
1529 // Verify that the types of the call parameter arguments match
1530 // the type of the wrapped callee.
1531 for (int i = 0; i < NumParams; i++) {
1532 Type *ParamType = TargetFuncType->getParamType(i);
1533 Type *ArgType = CS.getArgument(3+i)->getType();
1534 Assert(ArgType == ParamType,
1535 "gc.statepoint call argument does not match wrapped "
1539 const int EndCallArgsInx = 2+NumCallArgs;
1540 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1541 Assert(isa<ConstantInt>(NumDeoptArgsV),
1542 "gc.statepoint number of deoptimization arguments "
1543 "must be constant integer",
1545 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1546 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1550 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1551 "gc.statepoint too few arguments according to length fields", &CI);
1553 // Check that the only uses of this gc.statepoint are gc.result or
1554 // gc.relocate calls which are tied to this statepoint and thus part
1555 // of the same statepoint sequence
1556 for (const User *U : CI.users()) {
1557 const CallInst *Call = dyn_cast<const CallInst>(U);
1558 Assert(Call, "illegal use of statepoint token", &CI, U);
1559 if (!Call) continue;
1560 Assert(isGCRelocate(Call) || isGCResult(Call),
1561 "gc.result or gc.relocate are the only value uses"
1562 "of a gc.statepoint",
1564 if (isGCResult(Call)) {
1565 Assert(Call->getArgOperand(0) == &CI,
1566 "gc.result connected to wrong gc.statepoint", &CI, Call);
1567 } else if (isGCRelocate(Call)) {
1568 Assert(Call->getArgOperand(0) == &CI,
1569 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1573 // Note: It is legal for a single derived pointer to be listed multiple
1574 // times. It's non-optimal, but it is legal. It can also happen after
1575 // insertion if we strip a bitcast away.
1576 // Note: It is really tempting to check that each base is relocated and
1577 // that a derived pointer is never reused as a base pointer. This turns
1578 // out to be problematic since optimizations run after safepoint insertion
1579 // can recognize equality properties that the insertion logic doesn't know
1580 // about. See example statepoint.ll in the verifier subdirectory
1583 void Verifier::verifyFrameRecoverIndices() {
1584 for (auto &Counts : FrameEscapeInfo) {
1585 Function *F = Counts.first;
1586 unsigned EscapedObjectCount = Counts.second.first;
1587 unsigned MaxRecoveredIndex = Counts.second.second;
1588 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1589 "all indices passed to llvm.framerecover must be less than the "
1590 "number of arguments passed ot llvm.frameescape in the parent "
1596 // visitFunction - Verify that a function is ok.
1598 void Verifier::visitFunction(const Function &F) {
1599 // Check function arguments.
1600 FunctionType *FT = F.getFunctionType();
1601 unsigned NumArgs = F.arg_size();
1603 Assert(Context == &F.getContext(),
1604 "Function context does not match Module context!", &F);
1606 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1607 Assert(FT->getNumParams() == NumArgs,
1608 "# formal arguments must match # of arguments for function type!", &F,
1610 Assert(F.getReturnType()->isFirstClassType() ||
1611 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1612 "Functions cannot return aggregate values!", &F);
1614 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1615 "Invalid struct return type!", &F);
1617 AttributeSet Attrs = F.getAttributes();
1619 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1620 "Attribute after last parameter!", &F);
1622 // Check function attributes.
1623 VerifyFunctionAttrs(FT, Attrs, &F);
1625 // On function declarations/definitions, we do not support the builtin
1626 // attribute. We do not check this in VerifyFunctionAttrs since that is
1627 // checking for Attributes that can/can not ever be on functions.
1628 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1629 "Attribute 'builtin' can only be applied to a callsite.", &F);
1631 // Check that this function meets the restrictions on this calling convention.
1632 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1633 // restrictions can be lifted.
1634 switch (F.getCallingConv()) {
1636 case CallingConv::C:
1638 case CallingConv::Fast:
1639 case CallingConv::Cold:
1640 case CallingConv::Intel_OCL_BI:
1641 case CallingConv::PTX_Kernel:
1642 case CallingConv::PTX_Device:
1643 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1644 "perfect forwarding!",
1649 bool isLLVMdotName = F.getName().size() >= 5 &&
1650 F.getName().substr(0, 5) == "llvm.";
1652 // Check that the argument values match the function type for this function...
1654 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1656 Assert(I->getType() == FT->getParamType(i),
1657 "Argument value does not match function argument type!", I,
1658 FT->getParamType(i));
1659 Assert(I->getType()->isFirstClassType(),
1660 "Function arguments must have first-class types!", I);
1662 Assert(!I->getType()->isMetadataTy(),
1663 "Function takes metadata but isn't an intrinsic", I, &F);
1666 if (F.isMaterializable()) {
1667 // Function has a body somewhere we can't see.
1668 } else if (F.isDeclaration()) {
1669 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1670 "invalid linkage type for function declaration", &F);
1672 // Verify that this function (which has a body) is not named "llvm.*". It
1673 // is not legal to define intrinsics.
1674 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1676 // Check the entry node
1677 const BasicBlock *Entry = &F.getEntryBlock();
1678 Assert(pred_empty(Entry),
1679 "Entry block to function must not have predecessors!", Entry);
1681 // The address of the entry block cannot be taken, unless it is dead.
1682 if (Entry->hasAddressTaken()) {
1683 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1684 "blockaddress may not be used with the entry block!", Entry);
1688 // If this function is actually an intrinsic, verify that it is only used in
1689 // direct call/invokes, never having its "address taken".
1690 if (F.getIntrinsicID()) {
1692 if (F.hasAddressTaken(&U))
1693 Assert(0, "Invalid user of intrinsic instruction!", U);
1696 Assert(!F.hasDLLImportStorageClass() ||
1697 (F.isDeclaration() && F.hasExternalLinkage()) ||
1698 F.hasAvailableExternallyLinkage(),
1699 "Function is marked as dllimport, but not external.", &F);
1702 // verifyBasicBlock - Verify that a basic block is well formed...
1704 void Verifier::visitBasicBlock(BasicBlock &BB) {
1705 InstsInThisBlock.clear();
1707 // Ensure that basic blocks have terminators!
1708 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1710 // Check constraints that this basic block imposes on all of the PHI nodes in
1712 if (isa<PHINode>(BB.front())) {
1713 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1714 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1715 std::sort(Preds.begin(), Preds.end());
1717 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1718 // Ensure that PHI nodes have at least one entry!
1719 Assert(PN->getNumIncomingValues() != 0,
1720 "PHI nodes must have at least one entry. If the block is dead, "
1721 "the PHI should be removed!",
1723 Assert(PN->getNumIncomingValues() == Preds.size(),
1724 "PHINode should have one entry for each predecessor of its "
1725 "parent basic block!",
1728 // Get and sort all incoming values in the PHI node...
1730 Values.reserve(PN->getNumIncomingValues());
1731 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1732 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1733 PN->getIncomingValue(i)));
1734 std::sort(Values.begin(), Values.end());
1736 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1737 // Check to make sure that if there is more than one entry for a
1738 // particular basic block in this PHI node, that the incoming values are
1741 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1742 Values[i].second == Values[i - 1].second,
1743 "PHI node has multiple entries for the same basic block with "
1744 "different incoming values!",
1745 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1747 // Check to make sure that the predecessors and PHI node entries are
1749 Assert(Values[i].first == Preds[i],
1750 "PHI node entries do not match predecessors!", PN,
1751 Values[i].first, Preds[i]);
1756 // Check that all instructions have their parent pointers set up correctly.
1759 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1763 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1764 // Ensure that terminators only exist at the end of the basic block.
1765 Assert(&I == I.getParent()->getTerminator(),
1766 "Terminator found in the middle of a basic block!", I.getParent());
1767 visitInstruction(I);
1770 void Verifier::visitBranchInst(BranchInst &BI) {
1771 if (BI.isConditional()) {
1772 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1773 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1775 visitTerminatorInst(BI);
1778 void Verifier::visitReturnInst(ReturnInst &RI) {
1779 Function *F = RI.getParent()->getParent();
1780 unsigned N = RI.getNumOperands();
1781 if (F->getReturnType()->isVoidTy())
1783 "Found return instr that returns non-void in Function of void "
1785 &RI, F->getReturnType());
1787 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1788 "Function return type does not match operand "
1789 "type of return inst!",
1790 &RI, F->getReturnType());
1792 // Check to make sure that the return value has necessary properties for
1794 visitTerminatorInst(RI);
1797 void Verifier::visitSwitchInst(SwitchInst &SI) {
1798 // Check to make sure that all of the constants in the switch instruction
1799 // have the same type as the switched-on value.
1800 Type *SwitchTy = SI.getCondition()->getType();
1801 SmallPtrSet<ConstantInt*, 32> Constants;
1802 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1803 Assert(i.getCaseValue()->getType() == SwitchTy,
1804 "Switch constants must all be same type as switch value!", &SI);
1805 Assert(Constants.insert(i.getCaseValue()).second,
1806 "Duplicate integer as switch case", &SI, i.getCaseValue());
1809 visitTerminatorInst(SI);
1812 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1813 Assert(BI.getAddress()->getType()->isPointerTy(),
1814 "Indirectbr operand must have pointer type!", &BI);
1815 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1816 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1817 "Indirectbr destinations must all have pointer type!", &BI);
1819 visitTerminatorInst(BI);
1822 void Verifier::visitSelectInst(SelectInst &SI) {
1823 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1825 "Invalid operands for select instruction!", &SI);
1827 Assert(SI.getTrueValue()->getType() == SI.getType(),
1828 "Select values must have same type as select instruction!", &SI);
1829 visitInstruction(SI);
1832 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1833 /// a pass, if any exist, it's an error.
1835 void Verifier::visitUserOp1(Instruction &I) {
1836 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1839 void Verifier::visitTruncInst(TruncInst &I) {
1840 // Get the source and destination types
1841 Type *SrcTy = I.getOperand(0)->getType();
1842 Type *DestTy = I.getType();
1844 // Get the size of the types in bits, we'll need this later
1845 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1846 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1848 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1849 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1850 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1851 "trunc source and destination must both be a vector or neither", &I);
1852 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1854 visitInstruction(I);
1857 void Verifier::visitZExtInst(ZExtInst &I) {
1858 // Get the source and destination types
1859 Type *SrcTy = I.getOperand(0)->getType();
1860 Type *DestTy = I.getType();
1862 // Get the size of the types in bits, we'll need this later
1863 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1864 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1865 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1866 "zext source and destination must both be a vector or neither", &I);
1867 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1868 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1870 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1872 visitInstruction(I);
1875 void Verifier::visitSExtInst(SExtInst &I) {
1876 // Get the source and destination types
1877 Type *SrcTy = I.getOperand(0)->getType();
1878 Type *DestTy = I.getType();
1880 // Get the size of the types in bits, we'll need this later
1881 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1882 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1884 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1885 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1886 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1887 "sext source and destination must both be a vector or neither", &I);
1888 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1890 visitInstruction(I);
1893 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1894 // Get the source and destination types
1895 Type *SrcTy = I.getOperand(0)->getType();
1896 Type *DestTy = I.getType();
1897 // Get the size of the types in bits, we'll need this later
1898 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1899 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1901 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1902 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1903 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1904 "fptrunc source and destination must both be a vector or neither", &I);
1905 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1907 visitInstruction(I);
1910 void Verifier::visitFPExtInst(FPExtInst &I) {
1911 // Get the source and destination types
1912 Type *SrcTy = I.getOperand(0)->getType();
1913 Type *DestTy = I.getType();
1915 // Get the size of the types in bits, we'll need this later
1916 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1917 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1919 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1920 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1921 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1922 "fpext source and destination must both be a vector or neither", &I);
1923 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1925 visitInstruction(I);
1928 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1929 // Get the source and destination types
1930 Type *SrcTy = I.getOperand(0)->getType();
1931 Type *DestTy = I.getType();
1933 bool SrcVec = SrcTy->isVectorTy();
1934 bool DstVec = DestTy->isVectorTy();
1936 Assert(SrcVec == DstVec,
1937 "UIToFP source and dest must both be vector or scalar", &I);
1938 Assert(SrcTy->isIntOrIntVectorTy(),
1939 "UIToFP source must be integer or integer vector", &I);
1940 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1943 if (SrcVec && DstVec)
1944 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1945 cast<VectorType>(DestTy)->getNumElements(),
1946 "UIToFP source and dest vector length mismatch", &I);
1948 visitInstruction(I);
1951 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1952 // Get the source and destination types
1953 Type *SrcTy = I.getOperand(0)->getType();
1954 Type *DestTy = I.getType();
1956 bool SrcVec = SrcTy->isVectorTy();
1957 bool DstVec = DestTy->isVectorTy();
1959 Assert(SrcVec == DstVec,
1960 "SIToFP source and dest must both be vector or scalar", &I);
1961 Assert(SrcTy->isIntOrIntVectorTy(),
1962 "SIToFP source must be integer or integer vector", &I);
1963 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1966 if (SrcVec && DstVec)
1967 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1968 cast<VectorType>(DestTy)->getNumElements(),
1969 "SIToFP source and dest vector length mismatch", &I);
1971 visitInstruction(I);
1974 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1975 // Get the source and destination types
1976 Type *SrcTy = I.getOperand(0)->getType();
1977 Type *DestTy = I.getType();
1979 bool SrcVec = SrcTy->isVectorTy();
1980 bool DstVec = DestTy->isVectorTy();
1982 Assert(SrcVec == DstVec,
1983 "FPToUI source and dest must both be vector or scalar", &I);
1984 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1986 Assert(DestTy->isIntOrIntVectorTy(),
1987 "FPToUI result must be integer or integer vector", &I);
1989 if (SrcVec && DstVec)
1990 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1991 cast<VectorType>(DestTy)->getNumElements(),
1992 "FPToUI source and dest vector length mismatch", &I);
1994 visitInstruction(I);
1997 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1998 // Get the source and destination types
1999 Type *SrcTy = I.getOperand(0)->getType();
2000 Type *DestTy = I.getType();
2002 bool SrcVec = SrcTy->isVectorTy();
2003 bool DstVec = DestTy->isVectorTy();
2005 Assert(SrcVec == DstVec,
2006 "FPToSI source and dest must both be vector or scalar", &I);
2007 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2009 Assert(DestTy->isIntOrIntVectorTy(),
2010 "FPToSI result must be integer or integer vector", &I);
2012 if (SrcVec && DstVec)
2013 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2014 cast<VectorType>(DestTy)->getNumElements(),
2015 "FPToSI source and dest vector length mismatch", &I);
2017 visitInstruction(I);
2020 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2021 // Get the source and destination types
2022 Type *SrcTy = I.getOperand(0)->getType();
2023 Type *DestTy = I.getType();
2025 Assert(SrcTy->getScalarType()->isPointerTy(),
2026 "PtrToInt source must be pointer", &I);
2027 Assert(DestTy->getScalarType()->isIntegerTy(),
2028 "PtrToInt result must be integral", &I);
2029 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2032 if (SrcTy->isVectorTy()) {
2033 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2034 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2035 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2036 "PtrToInt Vector width mismatch", &I);
2039 visitInstruction(I);
2042 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2043 // Get the source and destination types
2044 Type *SrcTy = I.getOperand(0)->getType();
2045 Type *DestTy = I.getType();
2047 Assert(SrcTy->getScalarType()->isIntegerTy(),
2048 "IntToPtr source must be an integral", &I);
2049 Assert(DestTy->getScalarType()->isPointerTy(),
2050 "IntToPtr result must be a pointer", &I);
2051 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2053 if (SrcTy->isVectorTy()) {
2054 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2055 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2056 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2057 "IntToPtr Vector width mismatch", &I);
2059 visitInstruction(I);
2062 void Verifier::visitBitCastInst(BitCastInst &I) {
2064 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2065 "Invalid bitcast", &I);
2066 visitInstruction(I);
2069 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2070 Type *SrcTy = I.getOperand(0)->getType();
2071 Type *DestTy = I.getType();
2073 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2075 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2077 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2078 "AddrSpaceCast must be between different address spaces", &I);
2079 if (SrcTy->isVectorTy())
2080 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2081 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2082 visitInstruction(I);
2085 /// visitPHINode - Ensure that a PHI node is well formed.
2087 void Verifier::visitPHINode(PHINode &PN) {
2088 // Ensure that the PHI nodes are all grouped together at the top of the block.
2089 // This can be tested by checking whether the instruction before this is
2090 // either nonexistent (because this is begin()) or is a PHI node. If not,
2091 // then there is some other instruction before a PHI.
2092 Assert(&PN == &PN.getParent()->front() ||
2093 isa<PHINode>(--BasicBlock::iterator(&PN)),
2094 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2096 // Check that all of the values of the PHI node have the same type as the
2097 // result, and that the incoming blocks are really basic blocks.
2098 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2099 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
2100 "PHI node operands are not the same type as the result!", &PN);
2103 // All other PHI node constraints are checked in the visitBasicBlock method.
2105 visitInstruction(PN);
2108 void Verifier::VerifyCallSite(CallSite CS) {
2109 Instruction *I = CS.getInstruction();
2111 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2112 "Called function must be a pointer!", I);
2113 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2115 Assert(FPTy->getElementType()->isFunctionTy(),
2116 "Called function is not pointer to function type!", I);
2117 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
2119 // Verify that the correct number of arguments are being passed
2120 if (FTy->isVarArg())
2121 Assert(CS.arg_size() >= FTy->getNumParams(),
2122 "Called function requires more parameters than were provided!", I);
2124 Assert(CS.arg_size() == FTy->getNumParams(),
2125 "Incorrect number of arguments passed to called function!", I);
2127 // Verify that all arguments to the call match the function type.
2128 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2129 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2130 "Call parameter type does not match function signature!",
2131 CS.getArgument(i), FTy->getParamType(i), I);
2133 AttributeSet Attrs = CS.getAttributes();
2135 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2136 "Attribute after last parameter!", I);
2138 // Verify call attributes.
2139 VerifyFunctionAttrs(FTy, Attrs, I);
2141 // Conservatively check the inalloca argument.
2142 // We have a bug if we can find that there is an underlying alloca without
2144 if (CS.hasInAllocaArgument()) {
2145 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2146 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2147 Assert(AI->isUsedWithInAlloca(),
2148 "inalloca argument for call has mismatched alloca", AI, I);
2151 if (FTy->isVarArg()) {
2152 // FIXME? is 'nest' even legal here?
2153 bool SawNest = false;
2154 bool SawReturned = false;
2156 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2157 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2159 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2163 // Check attributes on the varargs part.
2164 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2165 Type *Ty = CS.getArgument(Idx-1)->getType();
2166 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2168 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2169 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2173 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2174 Assert(!SawReturned, "More than one parameter has attribute returned!",
2176 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2177 "Incompatible argument and return types for 'returned' "
2183 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2184 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2186 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2187 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2191 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2192 if (CS.getCalledFunction() == nullptr ||
2193 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2194 for (FunctionType::param_iterator PI = FTy->param_begin(),
2195 PE = FTy->param_end(); PI != PE; ++PI)
2196 Assert(!(*PI)->isMetadataTy(),
2197 "Function has metadata parameter but isn't an intrinsic", I);
2200 visitInstruction(*I);
2203 /// Two types are "congruent" if they are identical, or if they are both pointer
2204 /// types with different pointee types and the same address space.
2205 static bool isTypeCongruent(Type *L, Type *R) {
2208 PointerType *PL = dyn_cast<PointerType>(L);
2209 PointerType *PR = dyn_cast<PointerType>(R);
2212 return PL->getAddressSpace() == PR->getAddressSpace();
2215 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2216 static const Attribute::AttrKind ABIAttrs[] = {
2217 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2218 Attribute::InReg, Attribute::Returned};
2220 for (auto AK : ABIAttrs) {
2221 if (Attrs.hasAttribute(I + 1, AK))
2222 Copy.addAttribute(AK);
2224 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2225 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2229 void Verifier::verifyMustTailCall(CallInst &CI) {
2230 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2232 // - The caller and callee prototypes must match. Pointer types of
2233 // parameters or return types may differ in pointee type, but not
2235 Function *F = CI.getParent()->getParent();
2236 auto GetFnTy = [](Value *V) {
2237 return cast<FunctionType>(
2238 cast<PointerType>(V->getType())->getElementType());
2240 FunctionType *CallerTy = GetFnTy(F);
2241 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2242 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2243 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2244 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2245 "cannot guarantee tail call due to mismatched varargs", &CI);
2246 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2247 "cannot guarantee tail call due to mismatched return types", &CI);
2248 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2250 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2251 "cannot guarantee tail call due to mismatched parameter types", &CI);
2254 // - The calling conventions of the caller and callee must match.
2255 Assert(F->getCallingConv() == CI.getCallingConv(),
2256 "cannot guarantee tail call due to mismatched calling conv", &CI);
2258 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2259 // returned, and inalloca, must match.
2260 AttributeSet CallerAttrs = F->getAttributes();
2261 AttributeSet CalleeAttrs = CI.getAttributes();
2262 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2263 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2264 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2265 Assert(CallerABIAttrs == CalleeABIAttrs,
2266 "cannot guarantee tail call due to mismatched ABI impacting "
2267 "function attributes",
2268 &CI, CI.getOperand(I));
2271 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2272 // or a pointer bitcast followed by a ret instruction.
2273 // - The ret instruction must return the (possibly bitcasted) value
2274 // produced by the call or void.
2275 Value *RetVal = &CI;
2276 Instruction *Next = CI.getNextNode();
2278 // Handle the optional bitcast.
2279 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2280 Assert(BI->getOperand(0) == RetVal,
2281 "bitcast following musttail call must use the call", BI);
2283 Next = BI->getNextNode();
2286 // Check the return.
2287 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2288 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2290 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2291 "musttail call result must be returned", Ret);
2294 void Verifier::visitCallInst(CallInst &CI) {
2295 VerifyCallSite(&CI);
2297 if (CI.isMustTailCall())
2298 verifyMustTailCall(CI);
2300 if (Function *F = CI.getCalledFunction())
2301 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2302 visitIntrinsicFunctionCall(ID, CI);
2305 void Verifier::visitInvokeInst(InvokeInst &II) {
2306 VerifyCallSite(&II);
2308 // Verify that there is a landingpad instruction as the first non-PHI
2309 // instruction of the 'unwind' destination.
2310 Assert(II.getUnwindDest()->isLandingPad(),
2311 "The unwind destination does not have a landingpad instruction!", &II);
2313 if (Function *F = II.getCalledFunction())
2314 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2315 // CallInst as an input parameter. It not woth updating this whole
2316 // function only to support statepoint verification.
2317 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2318 VerifyStatepoint(ImmutableCallSite(&II));
2320 visitTerminatorInst(II);
2323 /// visitBinaryOperator - Check that both arguments to the binary operator are
2324 /// of the same type!
2326 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2327 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2328 "Both operands to a binary operator are not of the same type!", &B);
2330 switch (B.getOpcode()) {
2331 // Check that integer arithmetic operators are only used with
2332 // integral operands.
2333 case Instruction::Add:
2334 case Instruction::Sub:
2335 case Instruction::Mul:
2336 case Instruction::SDiv:
2337 case Instruction::UDiv:
2338 case Instruction::SRem:
2339 case Instruction::URem:
2340 Assert(B.getType()->isIntOrIntVectorTy(),
2341 "Integer arithmetic operators only work with integral types!", &B);
2342 Assert(B.getType() == B.getOperand(0)->getType(),
2343 "Integer arithmetic operators must have same type "
2344 "for operands and result!",
2347 // Check that floating-point arithmetic operators are only used with
2348 // floating-point operands.
2349 case Instruction::FAdd:
2350 case Instruction::FSub:
2351 case Instruction::FMul:
2352 case Instruction::FDiv:
2353 case Instruction::FRem:
2354 Assert(B.getType()->isFPOrFPVectorTy(),
2355 "Floating-point arithmetic operators only work with "
2356 "floating-point types!",
2358 Assert(B.getType() == B.getOperand(0)->getType(),
2359 "Floating-point arithmetic operators must have same type "
2360 "for operands and result!",
2363 // Check that logical operators are only used with integral operands.
2364 case Instruction::And:
2365 case Instruction::Or:
2366 case Instruction::Xor:
2367 Assert(B.getType()->isIntOrIntVectorTy(),
2368 "Logical operators only work with integral types!", &B);
2369 Assert(B.getType() == B.getOperand(0)->getType(),
2370 "Logical operators must have same type for operands and result!",
2373 case Instruction::Shl:
2374 case Instruction::LShr:
2375 case Instruction::AShr:
2376 Assert(B.getType()->isIntOrIntVectorTy(),
2377 "Shifts only work with integral types!", &B);
2378 Assert(B.getType() == B.getOperand(0)->getType(),
2379 "Shift return type must be same as operands!", &B);
2382 llvm_unreachable("Unknown BinaryOperator opcode!");
2385 visitInstruction(B);
2388 void Verifier::visitICmpInst(ICmpInst &IC) {
2389 // Check that the operands are the same type
2390 Type *Op0Ty = IC.getOperand(0)->getType();
2391 Type *Op1Ty = IC.getOperand(1)->getType();
2392 Assert(Op0Ty == Op1Ty,
2393 "Both operands to ICmp instruction are not of the same type!", &IC);
2394 // Check that the operands are the right type
2395 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2396 "Invalid operand types for ICmp instruction", &IC);
2397 // Check that the predicate is valid.
2398 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2399 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2400 "Invalid predicate in ICmp instruction!", &IC);
2402 visitInstruction(IC);
2405 void Verifier::visitFCmpInst(FCmpInst &FC) {
2406 // Check that the operands are the same type
2407 Type *Op0Ty = FC.getOperand(0)->getType();
2408 Type *Op1Ty = FC.getOperand(1)->getType();
2409 Assert(Op0Ty == Op1Ty,
2410 "Both operands to FCmp instruction are not of the same type!", &FC);
2411 // Check that the operands are the right type
2412 Assert(Op0Ty->isFPOrFPVectorTy(),
2413 "Invalid operand types for FCmp instruction", &FC);
2414 // Check that the predicate is valid.
2415 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2416 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2417 "Invalid predicate in FCmp instruction!", &FC);
2419 visitInstruction(FC);
2422 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2424 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2425 "Invalid extractelement operands!", &EI);
2426 visitInstruction(EI);
2429 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2430 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2432 "Invalid insertelement operands!", &IE);
2433 visitInstruction(IE);
2436 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2437 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2439 "Invalid shufflevector operands!", &SV);
2440 visitInstruction(SV);
2443 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2444 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2446 Assert(isa<PointerType>(TargetTy),
2447 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2448 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2449 "GEP into unsized type!", &GEP);
2450 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2451 GEP.getType()->isVectorTy(),
2452 "Vector GEP must return a vector value", &GEP);
2454 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2456 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2457 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2459 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2460 cast<PointerType>(GEP.getType()->getScalarType())
2461 ->getElementType() == ElTy,
2462 "GEP is not of right type for indices!", &GEP, ElTy);
2464 if (GEP.getPointerOperandType()->isVectorTy()) {
2465 // Additional checks for vector GEPs.
2466 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2467 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2468 "Vector GEP result width doesn't match operand's", &GEP);
2469 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2470 Type *IndexTy = Idxs[i]->getType();
2471 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2473 unsigned IndexWidth = IndexTy->getVectorNumElements();
2474 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2477 visitInstruction(GEP);
2480 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2481 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2484 void Verifier::visitRangeMetadata(Instruction& I,
2485 MDNode* Range, Type* Ty) {
2487 Range == I.getMetadata(LLVMContext::MD_range) &&
2488 "precondition violation");
2490 unsigned NumOperands = Range->getNumOperands();
2491 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2492 unsigned NumRanges = NumOperands / 2;
2493 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2495 ConstantRange LastRange(1); // Dummy initial value
2496 for (unsigned i = 0; i < NumRanges; ++i) {
2498 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2499 Assert(Low, "The lower limit must be an integer!", Low);
2501 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2502 Assert(High, "The upper limit must be an integer!", High);
2503 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2504 "Range types must match instruction type!", &I);
2506 APInt HighV = High->getValue();
2507 APInt LowV = Low->getValue();
2508 ConstantRange CurRange(LowV, HighV);
2509 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2510 "Range must not be empty!", Range);
2512 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2513 "Intervals are overlapping", Range);
2514 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2516 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2519 LastRange = ConstantRange(LowV, HighV);
2521 if (NumRanges > 2) {
2523 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2525 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2526 ConstantRange FirstRange(FirstLow, FirstHigh);
2527 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2528 "Intervals are overlapping", Range);
2529 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2534 void Verifier::visitLoadInst(LoadInst &LI) {
2535 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2536 Assert(PTy, "Load operand must be a pointer.", &LI);
2537 Type *ElTy = PTy->getElementType();
2538 Assert(ElTy == LI.getType(),
2539 "Load result type does not match pointer operand type!", &LI, ElTy);
2540 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2541 "huge alignment values are unsupported", &LI);
2542 if (LI.isAtomic()) {
2543 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2544 "Load cannot have Release ordering", &LI);
2545 Assert(LI.getAlignment() != 0,
2546 "Atomic load must specify explicit alignment", &LI);
2547 if (!ElTy->isPointerTy()) {
2548 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2550 unsigned Size = ElTy->getPrimitiveSizeInBits();
2551 Assert(Size >= 8 && !(Size & (Size - 1)),
2552 "atomic load operand must be power-of-two byte-sized integer", &LI,
2556 Assert(LI.getSynchScope() == CrossThread,
2557 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2560 visitInstruction(LI);
2563 void Verifier::visitStoreInst(StoreInst &SI) {
2564 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2565 Assert(PTy, "Store operand must be a pointer.", &SI);
2566 Type *ElTy = PTy->getElementType();
2567 Assert(ElTy == SI.getOperand(0)->getType(),
2568 "Stored value type does not match pointer operand type!", &SI, ElTy);
2569 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2570 "huge alignment values are unsupported", &SI);
2571 if (SI.isAtomic()) {
2572 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2573 "Store cannot have Acquire ordering", &SI);
2574 Assert(SI.getAlignment() != 0,
2575 "Atomic store must specify explicit alignment", &SI);
2576 if (!ElTy->isPointerTy()) {
2577 Assert(ElTy->isIntegerTy(),
2578 "atomic store operand must have integer type!", &SI, ElTy);
2579 unsigned Size = ElTy->getPrimitiveSizeInBits();
2580 Assert(Size >= 8 && !(Size & (Size - 1)),
2581 "atomic store operand must be power-of-two byte-sized integer",
2585 Assert(SI.getSynchScope() == CrossThread,
2586 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2588 visitInstruction(SI);
2591 void Verifier::visitAllocaInst(AllocaInst &AI) {
2592 SmallPtrSet<const Type*, 4> Visited;
2593 PointerType *PTy = AI.getType();
2594 Assert(PTy->getAddressSpace() == 0,
2595 "Allocation instruction pointer not in the generic address space!",
2597 Assert(PTy->getElementType()->isSized(&Visited),
2598 "Cannot allocate unsized type", &AI);
2599 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2600 "Alloca array size must have integer type", &AI);
2601 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2602 "huge alignment values are unsupported", &AI);
2604 visitInstruction(AI);
2607 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2609 // FIXME: more conditions???
2610 Assert(CXI.getSuccessOrdering() != NotAtomic,
2611 "cmpxchg instructions must be atomic.", &CXI);
2612 Assert(CXI.getFailureOrdering() != NotAtomic,
2613 "cmpxchg instructions must be atomic.", &CXI);
2614 Assert(CXI.getSuccessOrdering() != Unordered,
2615 "cmpxchg instructions cannot be unordered.", &CXI);
2616 Assert(CXI.getFailureOrdering() != Unordered,
2617 "cmpxchg instructions cannot be unordered.", &CXI);
2618 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2619 "cmpxchg instructions be at least as constrained on success as fail",
2621 Assert(CXI.getFailureOrdering() != Release &&
2622 CXI.getFailureOrdering() != AcquireRelease,
2623 "cmpxchg failure ordering cannot include release semantics", &CXI);
2625 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2626 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2627 Type *ElTy = PTy->getElementType();
2628 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2630 unsigned Size = ElTy->getPrimitiveSizeInBits();
2631 Assert(Size >= 8 && !(Size & (Size - 1)),
2632 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2633 Assert(ElTy == CXI.getOperand(1)->getType(),
2634 "Expected value type does not match pointer operand type!", &CXI,
2636 Assert(ElTy == CXI.getOperand(2)->getType(),
2637 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2638 visitInstruction(CXI);
2641 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2642 Assert(RMWI.getOrdering() != NotAtomic,
2643 "atomicrmw instructions must be atomic.", &RMWI);
2644 Assert(RMWI.getOrdering() != Unordered,
2645 "atomicrmw instructions cannot be unordered.", &RMWI);
2646 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2647 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2648 Type *ElTy = PTy->getElementType();
2649 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2651 unsigned Size = ElTy->getPrimitiveSizeInBits();
2652 Assert(Size >= 8 && !(Size & (Size - 1)),
2653 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2655 Assert(ElTy == RMWI.getOperand(1)->getType(),
2656 "Argument value type does not match pointer operand type!", &RMWI,
2658 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2659 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2660 "Invalid binary operation!", &RMWI);
2661 visitInstruction(RMWI);
2664 void Verifier::visitFenceInst(FenceInst &FI) {
2665 const AtomicOrdering Ordering = FI.getOrdering();
2666 Assert(Ordering == Acquire || Ordering == Release ||
2667 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2668 "fence instructions may only have "
2669 "acquire, release, acq_rel, or seq_cst ordering.",
2671 visitInstruction(FI);
2674 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2675 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2676 EVI.getIndices()) == EVI.getType(),
2677 "Invalid ExtractValueInst operands!", &EVI);
2679 visitInstruction(EVI);
2682 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2683 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2684 IVI.getIndices()) ==
2685 IVI.getOperand(1)->getType(),
2686 "Invalid InsertValueInst operands!", &IVI);
2688 visitInstruction(IVI);
2691 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2692 BasicBlock *BB = LPI.getParent();
2694 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2696 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2697 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2699 // The landingpad instruction defines its parent as a landing pad block. The
2700 // landing pad block may be branched to only by the unwind edge of an invoke.
2701 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2702 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2703 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2704 "Block containing LandingPadInst must be jumped to "
2705 "only by the unwind edge of an invoke.",
2709 // The landingpad instruction must be the first non-PHI instruction in the
2711 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2712 "LandingPadInst not the first non-PHI instruction in the block.",
2715 // The personality functions for all landingpad instructions within the same
2716 // function should match.
2718 Assert(LPI.getPersonalityFn() == PersonalityFn,
2719 "Personality function doesn't match others in function", &LPI);
2720 PersonalityFn = LPI.getPersonalityFn();
2722 // All operands must be constants.
2723 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2725 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2726 Constant *Clause = LPI.getClause(i);
2727 if (LPI.isCatch(i)) {
2728 Assert(isa<PointerType>(Clause->getType()),
2729 "Catch operand does not have pointer type!", &LPI);
2731 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2732 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2733 "Filter operand is not an array of constants!", &LPI);
2737 visitInstruction(LPI);
2740 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2741 Instruction *Op = cast<Instruction>(I.getOperand(i));
2742 // If the we have an invalid invoke, don't try to compute the dominance.
2743 // We already reject it in the invoke specific checks and the dominance
2744 // computation doesn't handle multiple edges.
2745 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2746 if (II->getNormalDest() == II->getUnwindDest())
2750 const Use &U = I.getOperandUse(i);
2751 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2752 "Instruction does not dominate all uses!", Op, &I);
2755 /// verifyInstruction - Verify that an instruction is well formed.
2757 void Verifier::visitInstruction(Instruction &I) {
2758 BasicBlock *BB = I.getParent();
2759 Assert(BB, "Instruction not embedded in basic block!", &I);
2761 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2762 for (User *U : I.users()) {
2763 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2764 "Only PHI nodes may reference their own value!", &I);
2768 // Check that void typed values don't have names
2769 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2770 "Instruction has a name, but provides a void value!", &I);
2772 // Check that the return value of the instruction is either void or a legal
2774 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2775 "Instruction returns a non-scalar type!", &I);
2777 // Check that the instruction doesn't produce metadata. Calls are already
2778 // checked against the callee type.
2779 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2780 "Invalid use of metadata!", &I);
2782 // Check that all uses of the instruction, if they are instructions
2783 // themselves, actually have parent basic blocks. If the use is not an
2784 // instruction, it is an error!
2785 for (Use &U : I.uses()) {
2786 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2787 Assert(Used->getParent() != nullptr,
2788 "Instruction referencing"
2789 " instruction not embedded in a basic block!",
2792 CheckFailed("Use of instruction is not an instruction!", U);
2797 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2798 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2800 // Check to make sure that only first-class-values are operands to
2802 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2803 Assert(0, "Instruction operands must be first-class values!", &I);
2806 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2807 // Check to make sure that the "address of" an intrinsic function is never
2810 !F->isIntrinsic() ||
2811 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2812 "Cannot take the address of an intrinsic!", &I);
2814 !F->isIntrinsic() || isa<CallInst>(I) ||
2815 F->getIntrinsicID() == Intrinsic::donothing ||
2816 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2817 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2818 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2819 "Cannot invoke an intrinsinc other than"
2820 " donothing or patchpoint",
2822 Assert(F->getParent() == M, "Referencing function in another module!",
2824 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2825 Assert(OpBB->getParent() == BB->getParent(),
2826 "Referring to a basic block in another function!", &I);
2827 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2828 Assert(OpArg->getParent() == BB->getParent(),
2829 "Referring to an argument in another function!", &I);
2830 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2831 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2832 } else if (isa<Instruction>(I.getOperand(i))) {
2833 verifyDominatesUse(I, i);
2834 } else if (isa<InlineAsm>(I.getOperand(i))) {
2835 Assert((i + 1 == e && isa<CallInst>(I)) ||
2836 (i + 3 == e && isa<InvokeInst>(I)),
2837 "Cannot take the address of an inline asm!", &I);
2838 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2839 if (CE->getType()->isPtrOrPtrVectorTy()) {
2840 // If we have a ConstantExpr pointer, we need to see if it came from an
2841 // illegal bitcast (inttoptr <constant int> )
2842 SmallVector<const ConstantExpr *, 4> Stack;
2843 SmallPtrSet<const ConstantExpr *, 4> Visited;
2844 Stack.push_back(CE);
2846 while (!Stack.empty()) {
2847 const ConstantExpr *V = Stack.pop_back_val();
2848 if (!Visited.insert(V).second)
2851 VerifyConstantExprBitcastType(V);
2853 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2854 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2855 Stack.push_back(Op);
2862 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2863 Assert(I.getType()->isFPOrFPVectorTy(),
2864 "fpmath requires a floating point result!", &I);
2865 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2866 if (ConstantFP *CFP0 =
2867 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2868 APFloat Accuracy = CFP0->getValueAPF();
2869 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2870 "fpmath accuracy not a positive number!", &I);
2872 Assert(false, "invalid fpmath accuracy!", &I);
2876 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2877 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2878 "Ranges are only for loads, calls and invokes!", &I);
2879 visitRangeMetadata(I, Range, I.getType());
2882 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2883 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2885 Assert(isa<LoadInst>(I),
2886 "nonnull applies only to load instructions, use attributes"
2887 " for calls or invokes",
2891 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2892 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2896 InstsInThisBlock.insert(&I);
2899 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2900 /// intrinsic argument or return value) matches the type constraints specified
2901 /// by the .td file (e.g. an "any integer" argument really is an integer).
2903 /// This return true on error but does not print a message.
2904 bool Verifier::VerifyIntrinsicType(Type *Ty,
2905 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2906 SmallVectorImpl<Type*> &ArgTys) {
2907 using namespace Intrinsic;
2909 // If we ran out of descriptors, there are too many arguments.
2910 if (Infos.empty()) return true;
2911 IITDescriptor D = Infos.front();
2912 Infos = Infos.slice(1);
2915 case IITDescriptor::Void: return !Ty->isVoidTy();
2916 case IITDescriptor::VarArg: return true;
2917 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2918 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2919 case IITDescriptor::Half: return !Ty->isHalfTy();
2920 case IITDescriptor::Float: return !Ty->isFloatTy();
2921 case IITDescriptor::Double: return !Ty->isDoubleTy();
2922 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2923 case IITDescriptor::Vector: {
2924 VectorType *VT = dyn_cast<VectorType>(Ty);
2925 return !VT || VT->getNumElements() != D.Vector_Width ||
2926 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2928 case IITDescriptor::Pointer: {
2929 PointerType *PT = dyn_cast<PointerType>(Ty);
2930 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2931 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2934 case IITDescriptor::Struct: {
2935 StructType *ST = dyn_cast<StructType>(Ty);
2936 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2939 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2940 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2945 case IITDescriptor::Argument:
2946 // Two cases here - If this is the second occurrence of an argument, verify
2947 // that the later instance matches the previous instance.
2948 if (D.getArgumentNumber() < ArgTys.size())
2949 return Ty != ArgTys[D.getArgumentNumber()];
2951 // Otherwise, if this is the first instance of an argument, record it and
2952 // verify the "Any" kind.
2953 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2954 ArgTys.push_back(Ty);
2956 switch (D.getArgumentKind()) {
2957 case IITDescriptor::AK_Any: return false; // Success
2958 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2959 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2960 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2961 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2963 llvm_unreachable("all argument kinds not covered");
2965 case IITDescriptor::ExtendArgument: {
2966 // This may only be used when referring to a previous vector argument.
2967 if (D.getArgumentNumber() >= ArgTys.size())
2970 Type *NewTy = ArgTys[D.getArgumentNumber()];
2971 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2972 NewTy = VectorType::getExtendedElementVectorType(VTy);
2973 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2974 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2980 case IITDescriptor::TruncArgument: {
2981 // This may only be used when referring to a previous vector argument.
2982 if (D.getArgumentNumber() >= ArgTys.size())
2985 Type *NewTy = ArgTys[D.getArgumentNumber()];
2986 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2987 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2988 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2989 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2995 case IITDescriptor::HalfVecArgument:
2996 // This may only be used when referring to a previous vector argument.
2997 return D.getArgumentNumber() >= ArgTys.size() ||
2998 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2999 VectorType::getHalfElementsVectorType(
3000 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3001 case IITDescriptor::SameVecWidthArgument: {
3002 if (D.getArgumentNumber() >= ArgTys.size())
3004 VectorType * ReferenceType =
3005 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3006 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3007 if (!ThisArgType || !ReferenceType ||
3008 (ReferenceType->getVectorNumElements() !=
3009 ThisArgType->getVectorNumElements()))
3011 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3014 case IITDescriptor::PtrToArgument: {
3015 if (D.getArgumentNumber() >= ArgTys.size())
3017 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3018 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3019 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3021 case IITDescriptor::VecOfPtrsToElt: {
3022 if (D.getArgumentNumber() >= ArgTys.size())
3024 VectorType * ReferenceType =
3025 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3026 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3027 if (!ThisArgVecTy || !ReferenceType ||
3028 (ReferenceType->getVectorNumElements() !=
3029 ThisArgVecTy->getVectorNumElements()))
3031 PointerType *ThisArgEltTy =
3032 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3035 return (!(ThisArgEltTy->getElementType() ==
3036 ReferenceType->getVectorElementType()));
3039 llvm_unreachable("unhandled");
3042 /// \brief Verify if the intrinsic has variable arguments.
3043 /// This method is intended to be called after all the fixed arguments have been
3046 /// This method returns true on error and does not print an error message.
3048 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3049 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3050 using namespace Intrinsic;
3052 // If there are no descriptors left, then it can't be a vararg.
3056 // There should be only one descriptor remaining at this point.
3057 if (Infos.size() != 1)
3060 // Check and verify the descriptor.
3061 IITDescriptor D = Infos.front();
3062 Infos = Infos.slice(1);
3063 if (D.Kind == IITDescriptor::VarArg)
3069 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
3071 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
3072 Function *IF = CI.getCalledFunction();
3073 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3076 // Verify that the intrinsic prototype lines up with what the .td files
3078 FunctionType *IFTy = IF->getFunctionType();
3079 bool IsVarArg = IFTy->isVarArg();
3081 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3082 getIntrinsicInfoTableEntries(ID, Table);
3083 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3085 SmallVector<Type *, 4> ArgTys;
3086 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3087 "Intrinsic has incorrect return type!", IF);
3088 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3089 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3090 "Intrinsic has incorrect argument type!", IF);
3092 // Verify if the intrinsic call matches the vararg property.
3094 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3095 "Intrinsic was not defined with variable arguments!", IF);
3097 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3098 "Callsite was not defined with variable arguments!", IF);
3100 // All descriptors should be absorbed by now.
3101 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3103 // Now that we have the intrinsic ID and the actual argument types (and we
3104 // know they are legal for the intrinsic!) get the intrinsic name through the
3105 // usual means. This allows us to verify the mangling of argument types into
3107 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3108 Assert(ExpectedName == IF->getName(),
3109 "Intrinsic name not mangled correctly for type arguments! "
3114 // If the intrinsic takes MDNode arguments, verify that they are either global
3115 // or are local to *this* function.
3116 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3117 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3118 visitMetadataAsValue(*MD, CI.getParent()->getParent());
3123 case Intrinsic::ctlz: // llvm.ctlz
3124 case Intrinsic::cttz: // llvm.cttz
3125 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3126 "is_zero_undef argument of bit counting intrinsics must be a "
3130 case Intrinsic::dbg_declare: // llvm.dbg.declare
3131 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3132 "invalid llvm.dbg.declare intrinsic call 1", &CI);
3133 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
3135 case Intrinsic::dbg_value: // llvm.dbg.value
3136 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
3138 case Intrinsic::memcpy:
3139 case Intrinsic::memmove:
3140 case Intrinsic::memset: {
3141 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3143 "alignment argument of memory intrinsics must be a constant int",
3145 const APInt &AlignVal = AlignCI->getValue();
3146 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3147 "alignment argument of memory intrinsics must be a power of 2", &CI);
3148 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3149 "isvolatile argument of memory intrinsics must be a constant int",
3153 case Intrinsic::gcroot:
3154 case Intrinsic::gcwrite:
3155 case Intrinsic::gcread:
3156 if (ID == Intrinsic::gcroot) {
3158 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3159 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3160 Assert(isa<Constant>(CI.getArgOperand(1)),
3161 "llvm.gcroot parameter #2 must be a constant.", &CI);
3162 if (!AI->getType()->getElementType()->isPointerTy()) {
3163 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3164 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3165 "or argument #2 must be a non-null constant.",
3170 Assert(CI.getParent()->getParent()->hasGC(),
3171 "Enclosing function does not use GC.", &CI);
3173 case Intrinsic::init_trampoline:
3174 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3175 "llvm.init_trampoline parameter #2 must resolve to a function.",
3178 case Intrinsic::prefetch:
3179 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3180 isa<ConstantInt>(CI.getArgOperand(2)) &&
3181 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3182 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3183 "invalid arguments to llvm.prefetch", &CI);
3185 case Intrinsic::stackprotector:
3186 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3187 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3189 case Intrinsic::lifetime_start:
3190 case Intrinsic::lifetime_end:
3191 case Intrinsic::invariant_start:
3192 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3193 "size argument of memory use markers must be a constant integer",
3196 case Intrinsic::invariant_end:
3197 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3198 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3201 case Intrinsic::frameescape: {
3202 BasicBlock *BB = CI.getParent();
3203 Assert(BB == &BB->getParent()->front(),
3204 "llvm.frameescape used outside of entry block", &CI);
3205 Assert(!SawFrameEscape,
3206 "multiple calls to llvm.frameescape in one function", &CI);
3207 for (Value *Arg : CI.arg_operands()) {
3208 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3209 Assert(AI && AI->isStaticAlloca(),
3210 "llvm.frameescape only accepts static allocas", &CI);
3212 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3213 SawFrameEscape = true;
3216 case Intrinsic::framerecover: {
3217 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3218 Function *Fn = dyn_cast<Function>(FnArg);
3219 Assert(Fn && !Fn->isDeclaration(),
3220 "llvm.framerecover first "
3221 "argument must be function defined in this module",
3223 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3224 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3226 auto &Entry = FrameEscapeInfo[Fn];
3227 Entry.second = unsigned(
3228 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3232 case Intrinsic::eh_parentframe: {
3233 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3234 Assert(AI && AI->isStaticAlloca(),
3235 "llvm.eh.parentframe requires a static alloca", &CI);
3239 case Intrinsic::eh_unwindhelp: {
3240 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3241 Assert(AI && AI->isStaticAlloca(),
3242 "llvm.eh.unwindhelp requires a static alloca", &CI);
3246 case Intrinsic::experimental_gc_statepoint:
3247 Assert(!CI.isInlineAsm(),
3248 "gc.statepoint support for inline assembly unimplemented", &CI);
3249 Assert(CI.getParent()->getParent()->hasGC(),
3250 "Enclosing function does not use GC.", &CI);
3252 VerifyStatepoint(ImmutableCallSite(&CI));
3254 case Intrinsic::experimental_gc_result_int:
3255 case Intrinsic::experimental_gc_result_float:
3256 case Intrinsic::experimental_gc_result_ptr:
3257 case Intrinsic::experimental_gc_result: {
3258 Assert(CI.getParent()->getParent()->hasGC(),
3259 "Enclosing function does not use GC.", &CI);
3260 // Are we tied to a statepoint properly?
3261 CallSite StatepointCS(CI.getArgOperand(0));
3262 const Function *StatepointFn =
3263 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3264 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3265 StatepointFn->getIntrinsicID() ==
3266 Intrinsic::experimental_gc_statepoint,
3267 "gc.result operand #1 must be from a statepoint", &CI,
3268 CI.getArgOperand(0));
3270 // Assert that result type matches wrapped callee.
3271 const Value *Target = StatepointCS.getArgument(0);
3272 const PointerType *PT = cast<PointerType>(Target->getType());
3273 const FunctionType *TargetFuncType =
3274 cast<FunctionType>(PT->getElementType());
3275 Assert(CI.getType() == TargetFuncType->getReturnType(),
3276 "gc.result result type does not match wrapped callee", &CI);
3279 case Intrinsic::experimental_gc_relocate: {
3280 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3282 // Check that this relocate is correctly tied to the statepoint
3284 // This is case for relocate on the unwinding path of an invoke statepoint
3285 if (ExtractValueInst *ExtractValue =
3286 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3287 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3288 "gc relocate on unwind path incorrectly linked to the statepoint",
3291 const BasicBlock *invokeBB =
3292 ExtractValue->getParent()->getUniquePredecessor();
3294 // Landingpad relocates should have only one predecessor with invoke
3295 // statepoint terminator
3296 Assert(invokeBB, "safepoints should have unique landingpads",
3297 ExtractValue->getParent());
3298 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3300 Assert(isStatepoint(invokeBB->getTerminator()),
3301 "gc relocate should be linked to a statepoint", invokeBB);
3304 // In all other cases relocate should be tied to the statepoint directly.
3305 // This covers relocates on a normal return path of invoke statepoint and
3306 // relocates of a call statepoint
3307 auto Token = CI.getArgOperand(0);
3308 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3309 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3312 // Verify rest of the relocate arguments
3314 GCRelocateOperands ops(&CI);
3315 ImmutableCallSite StatepointCS(ops.statepoint());
3317 // Both the base and derived must be piped through the safepoint
3318 Value* Base = CI.getArgOperand(1);
3319 Assert(isa<ConstantInt>(Base),
3320 "gc.relocate operand #2 must be integer offset", &CI);
3322 Value* Derived = CI.getArgOperand(2);
3323 Assert(isa<ConstantInt>(Derived),
3324 "gc.relocate operand #3 must be integer offset", &CI);
3326 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3327 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3329 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3330 "gc.relocate: statepoint base index out of bounds", &CI);
3331 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3332 "gc.relocate: statepoint derived index out of bounds", &CI);
3334 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3335 // section of the statepoint's argument
3336 Assert(StatepointCS.arg_size() > 0,
3337 "gc.statepoint: insufficient arguments");
3338 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3339 "gc.statement: number of call arguments must be constant integer");
3340 const unsigned NumCallArgs =
3341 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3342 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3343 "gc.statepoint: mismatch in number of call arguments");
3344 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3345 "gc.statepoint: number of deoptimization arguments must be "
3346 "a constant integer");
3347 const int NumDeoptArgs =
3348 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3349 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3350 const int GCParamArgsEnd = StatepointCS.arg_size();
3351 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3352 "gc.relocate: statepoint base index doesn't fall within the "
3353 "'gc parameters' section of the statepoint call",
3355 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3356 "gc.relocate: statepoint derived index doesn't fall within the "
3357 "'gc parameters' section of the statepoint call",
3360 // Assert that the result type matches the type of the relocated pointer
3361 GCRelocateOperands Operands(&CI);
3362 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3363 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3369 template <class DbgIntrinsicTy>
3370 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3371 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3372 Assert(isa<ValueAsMetadata>(MD) ||
3373 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3374 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3375 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3376 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3377 DII.getRawVariable());
3378 Assert(isa<MDExpression>(DII.getRawExpression()),
3379 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3380 DII.getRawExpression());
3383 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3384 // This is in its own function so we get an error for each bad type ref (not
3386 Assert(false, "unresolved type ref", S, N);
3389 void Verifier::verifyTypeRefs() {
3390 // Run the debug info verifier only if the regular verifier succeeds, since
3391 // sometimes checks that have already failed will cause crashes here.
3392 if (EverBroken || !VerifyDebugInfo)
3395 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3399 // Visit all the compile units again to check the type references.
3400 for (auto *CU : CUs->operands())
3401 if (auto *Ts = cast<MDCompileUnit>(CU)->getRetainedTypes())
3402 for (auto &Op : Ts->operands())
3403 if (auto *T = dyn_cast<MDCompositeType>(Op))
3404 TypeRefs.erase(T->getRawIdentifier());
3405 if (TypeRefs.empty())
3408 // Sort the unresolved references by name so the output is deterministic.
3409 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3410 SmallVector<TypeRef, 32> Unresolved(TypeRefs.begin(), TypeRefs.end());
3411 std::sort(Unresolved.begin(), Unresolved.end(),
3412 [](const TypeRef &LHS, const TypeRef &RHS) {
3413 return LHS.first->getString() < RHS.first->getString();
3416 // Visit the unresolved refs (printing out the errors).
3417 for (const TypeRef &TR : Unresolved)
3418 visitUnresolvedTypeRef(TR.first, TR.second);
3421 //===----------------------------------------------------------------------===//
3422 // Implement the public interfaces to this file...
3423 //===----------------------------------------------------------------------===//
3425 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3426 Function &F = const_cast<Function &>(f);
3427 assert(!F.isDeclaration() && "Cannot verify external functions");
3429 raw_null_ostream NullStr;
3430 Verifier V(OS ? *OS : NullStr);
3432 // Note that this function's return value is inverted from what you would
3433 // expect of a function called "verify".
3434 return !V.verify(F);
3437 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3438 raw_null_ostream NullStr;
3439 Verifier V(OS ? *OS : NullStr);
3441 bool Broken = false;
3442 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3443 if (!I->isDeclaration() && !I->isMaterializable())
3444 Broken |= !V.verify(*I);
3446 // Note that this function's return value is inverted from what you would
3447 // expect of a function called "verify".
3448 return !V.verify(M) || Broken;
3452 struct VerifierLegacyPass : public FunctionPass {
3458 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3459 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3461 explicit VerifierLegacyPass(bool FatalErrors)
3462 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3463 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3466 bool runOnFunction(Function &F) override {
3467 if (!V.verify(F) && FatalErrors)
3468 report_fatal_error("Broken function found, compilation aborted!");
3473 bool doFinalization(Module &M) override {
3474 if (!V.verify(M) && FatalErrors)
3475 report_fatal_error("Broken module found, compilation aborted!");
3480 void getAnalysisUsage(AnalysisUsage &AU) const override {
3481 AU.setPreservesAll();
3486 char VerifierLegacyPass::ID = 0;
3487 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3489 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3490 return new VerifierLegacyPass(FatalErrors);
3493 PreservedAnalyses VerifierPass::run(Module &M) {
3494 if (verifyModule(M, &dbgs()) && FatalErrors)
3495 report_fatal_error("Broken module found, compilation aborted!");
3497 return PreservedAnalyses::all();
3500 PreservedAnalyses VerifierPass::run(Function &F) {
3501 if (verifyFunction(F, &dbgs()) && FatalErrors)
3502 report_fatal_error("Broken function found, compilation aborted!");
3504 return PreservedAnalyses::all();