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 The personality function referenced by the LandingPadInsts.
179 /// All LandingPadInsts within the same function must use the same
180 /// personality function.
181 const Value *PersonalityFn;
183 /// \brief Whether we've seen a call to @llvm.frameescape in this function
187 /// Stores the count of how many objects were passed to llvm.frameescape for a
188 /// given function and the largest index passed to llvm.framerecover.
189 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
192 explicit Verifier(raw_ostream &OS)
193 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
194 SawFrameEscape(false) {}
196 bool verify(const Function &F) {
198 Context = &M->getContext();
200 // First ensure the function is well-enough formed to compute dominance
203 OS << "Function '" << F.getName()
204 << "' does not contain an entry block!\n";
207 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
208 if (I->empty() || !I->back().isTerminator()) {
209 OS << "Basic Block in function '" << F.getName()
210 << "' does not have terminator!\n";
211 I->printAsOperand(OS, true);
217 // Now directly compute a dominance tree. We don't rely on the pass
218 // manager to provide this as it isolates us from a potentially
219 // out-of-date dominator tree and makes it significantly more complex to
220 // run this code outside of a pass manager.
221 // FIXME: It's really gross that we have to cast away constness here.
222 DT.recalculate(const_cast<Function &>(F));
225 // FIXME: We strip const here because the inst visitor strips const.
226 visit(const_cast<Function &>(F));
227 InstsInThisBlock.clear();
228 PersonalityFn = nullptr;
229 SawFrameEscape = false;
234 bool verify(const Module &M) {
236 Context = &M.getContext();
239 // Scan through, checking all of the external function's linkage now...
240 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
241 visitGlobalValue(*I);
243 // Check to make sure function prototypes are okay.
244 if (I->isDeclaration())
248 // Now that we've visited every function, verify that we never asked to
249 // recover a frame index that wasn't escaped.
250 verifyFrameRecoverIndices();
252 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
254 visitGlobalVariable(*I);
256 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
258 visitGlobalAlias(*I);
260 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
261 E = M.named_metadata_end();
263 visitNamedMDNode(*I);
265 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
266 visitComdat(SMEC.getValue());
269 visitModuleIdents(M);
271 // Verify debug info last.
278 // Verification methods...
279 void visitGlobalValue(const GlobalValue &GV);
280 void visitGlobalVariable(const GlobalVariable &GV);
281 void visitGlobalAlias(const GlobalAlias &GA);
282 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
283 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
284 const GlobalAlias &A, const Constant &C);
285 void visitNamedMDNode(const NamedMDNode &NMD);
286 void visitMDNode(const MDNode &MD);
287 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
288 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
289 void visitComdat(const Comdat &C);
290 void visitModuleIdents(const Module &M);
291 void visitModuleFlags(const Module &M);
292 void visitModuleFlag(const MDNode *Op,
293 DenseMap<const MDString *, const MDNode *> &SeenIDs,
294 SmallVectorImpl<const MDNode *> &Requirements);
295 void visitFunction(const Function &F);
296 void visitBasicBlock(BasicBlock &BB);
297 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
299 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
300 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
301 #include "llvm/IR/Metadata.def"
302 void visitMDScope(const MDScope &N);
303 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
304 void visitMDVariable(const MDVariable &N);
305 void visitMDLexicalBlockBase(const MDLexicalBlockBase &N);
306 void visitMDTemplateParameter(const MDTemplateParameter &N);
308 // InstVisitor overrides...
309 using InstVisitor<Verifier>::visit;
310 void visit(Instruction &I);
312 void visitTruncInst(TruncInst &I);
313 void visitZExtInst(ZExtInst &I);
314 void visitSExtInst(SExtInst &I);
315 void visitFPTruncInst(FPTruncInst &I);
316 void visitFPExtInst(FPExtInst &I);
317 void visitFPToUIInst(FPToUIInst &I);
318 void visitFPToSIInst(FPToSIInst &I);
319 void visitUIToFPInst(UIToFPInst &I);
320 void visitSIToFPInst(SIToFPInst &I);
321 void visitIntToPtrInst(IntToPtrInst &I);
322 void visitPtrToIntInst(PtrToIntInst &I);
323 void visitBitCastInst(BitCastInst &I);
324 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
325 void visitPHINode(PHINode &PN);
326 void visitBinaryOperator(BinaryOperator &B);
327 void visitICmpInst(ICmpInst &IC);
328 void visitFCmpInst(FCmpInst &FC);
329 void visitExtractElementInst(ExtractElementInst &EI);
330 void visitInsertElementInst(InsertElementInst &EI);
331 void visitShuffleVectorInst(ShuffleVectorInst &EI);
332 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
333 void visitCallInst(CallInst &CI);
334 void visitInvokeInst(InvokeInst &II);
335 void visitGetElementPtrInst(GetElementPtrInst &GEP);
336 void visitLoadInst(LoadInst &LI);
337 void visitStoreInst(StoreInst &SI);
338 void verifyDominatesUse(Instruction &I, unsigned i);
339 void visitInstruction(Instruction &I);
340 void visitTerminatorInst(TerminatorInst &I);
341 void visitBranchInst(BranchInst &BI);
342 void visitReturnInst(ReturnInst &RI);
343 void visitSwitchInst(SwitchInst &SI);
344 void visitIndirectBrInst(IndirectBrInst &BI);
345 void visitSelectInst(SelectInst &SI);
346 void visitUserOp1(Instruction &I);
347 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
348 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
349 template <class DbgIntrinsicTy>
350 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
351 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
352 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
353 void visitFenceInst(FenceInst &FI);
354 void visitAllocaInst(AllocaInst &AI);
355 void visitExtractValueInst(ExtractValueInst &EVI);
356 void visitInsertValueInst(InsertValueInst &IVI);
357 void visitLandingPadInst(LandingPadInst &LPI);
359 void VerifyCallSite(CallSite CS);
360 void verifyMustTailCall(CallInst &CI);
361 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
362 unsigned ArgNo, std::string &Suffix);
363 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
364 SmallVectorImpl<Type *> &ArgTys);
365 bool VerifyIntrinsicIsVarArg(bool isVarArg,
366 ArrayRef<Intrinsic::IITDescriptor> &Infos);
367 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
368 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
370 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
371 bool isReturnValue, const Value *V);
372 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
375 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
376 void VerifyStatepoint(ImmutableCallSite CS);
377 void verifyFrameRecoverIndices();
379 // Module-level debug info verification...
380 void verifyDebugInfo();
381 void processInstructions(DebugInfoFinder &Finder);
382 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
384 } // End anonymous namespace
386 // Assert - We know that cond should be true, if not print an error message.
387 #define Assert(C, ...) \
388 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
390 void Verifier::visit(Instruction &I) {
391 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
392 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
393 InstVisitor<Verifier>::visit(I);
397 void Verifier::visitGlobalValue(const GlobalValue &GV) {
398 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
399 GV.hasExternalWeakLinkage(),
400 "Global is external, but doesn't have external or weak linkage!", &GV);
402 Assert(GV.getAlignment() <= Value::MaximumAlignment,
403 "huge alignment values are unsupported", &GV);
404 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
405 "Only global variables can have appending linkage!", &GV);
407 if (GV.hasAppendingLinkage()) {
408 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
409 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
410 "Only global arrays can have appending linkage!", GVar);
414 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
415 if (GV.hasInitializer()) {
416 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
417 "Global variable initializer type does not match global "
421 // If the global has common linkage, it must have a zero initializer and
422 // cannot be constant.
423 if (GV.hasCommonLinkage()) {
424 Assert(GV.getInitializer()->isNullValue(),
425 "'common' global must have a zero initializer!", &GV);
426 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
428 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
431 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
432 "invalid linkage type for global declaration", &GV);
435 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
436 GV.getName() == "llvm.global_dtors")) {
437 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
438 "invalid linkage for intrinsic global variable", &GV);
439 // Don't worry about emitting an error for it not being an array,
440 // visitGlobalValue will complain on appending non-array.
441 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
442 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
443 PointerType *FuncPtrTy =
444 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
445 // FIXME: Reject the 2-field form in LLVM 4.0.
447 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
448 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
449 STy->getTypeAtIndex(1) == FuncPtrTy,
450 "wrong type for intrinsic global variable", &GV);
451 if (STy->getNumElements() == 3) {
452 Type *ETy = STy->getTypeAtIndex(2);
453 Assert(ETy->isPointerTy() &&
454 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
455 "wrong type for intrinsic global variable", &GV);
460 if (GV.hasName() && (GV.getName() == "llvm.used" ||
461 GV.getName() == "llvm.compiler.used")) {
462 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
463 "invalid linkage for intrinsic global variable", &GV);
464 Type *GVType = GV.getType()->getElementType();
465 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
466 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
467 Assert(PTy, "wrong type for intrinsic global variable", &GV);
468 if (GV.hasInitializer()) {
469 const Constant *Init = GV.getInitializer();
470 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
471 Assert(InitArray, "wrong initalizer for intrinsic global variable",
473 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
474 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
475 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
477 "invalid llvm.used member", V);
478 Assert(V->hasName(), "members of llvm.used must be named", V);
484 Assert(!GV.hasDLLImportStorageClass() ||
485 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
486 GV.hasAvailableExternallyLinkage(),
487 "Global is marked as dllimport, but not external", &GV);
489 if (!GV.hasInitializer()) {
490 visitGlobalValue(GV);
494 // Walk any aggregate initializers looking for bitcasts between address spaces
495 SmallPtrSet<const Value *, 4> Visited;
496 SmallVector<const Value *, 4> WorkStack;
497 WorkStack.push_back(cast<Value>(GV.getInitializer()));
499 while (!WorkStack.empty()) {
500 const Value *V = WorkStack.pop_back_val();
501 if (!Visited.insert(V).second)
504 if (const User *U = dyn_cast<User>(V)) {
505 WorkStack.append(U->op_begin(), U->op_end());
508 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
509 VerifyConstantExprBitcastType(CE);
515 visitGlobalValue(GV);
518 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
519 SmallPtrSet<const GlobalAlias*, 4> Visited;
521 visitAliaseeSubExpr(Visited, GA, C);
524 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
525 const GlobalAlias &GA, const Constant &C) {
526 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
527 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
529 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
530 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
532 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
535 // Only continue verifying subexpressions of GlobalAliases.
536 // Do not recurse into global initializers.
541 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
542 VerifyConstantExprBitcastType(CE);
544 for (const Use &U : C.operands()) {
546 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
547 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
548 else if (const auto *C2 = dyn_cast<Constant>(V))
549 visitAliaseeSubExpr(Visited, GA, *C2);
553 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
554 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
555 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
556 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
557 "weak_odr, or external linkage!",
559 const Constant *Aliasee = GA.getAliasee();
560 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
561 Assert(GA.getType() == Aliasee->getType(),
562 "Alias and aliasee types should match!", &GA);
564 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
565 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
567 visitAliaseeSubExpr(GA, *Aliasee);
569 visitGlobalValue(GA);
572 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
573 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
574 MDNode *MD = NMD.getOperand(i);
578 if (NMD.getName() == "llvm.dbg.cu") {
579 Assert(isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
586 void Verifier::visitMDNode(const MDNode &MD) {
587 // Only visit each node once. Metadata can be mutually recursive, so this
588 // avoids infinite recursion here, as well as being an optimization.
589 if (!MDNodes.insert(&MD).second)
592 switch (MD.getMetadataID()) {
594 llvm_unreachable("Invalid MDNode subclass");
595 case Metadata::MDTupleKind:
597 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
598 case Metadata::CLASS##Kind: \
599 visit##CLASS(cast<CLASS>(MD)); \
601 #include "llvm/IR/Metadata.def"
604 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
605 Metadata *Op = MD.getOperand(i);
608 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
610 if (auto *N = dyn_cast<MDNode>(Op)) {
614 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
615 visitValueAsMetadata(*V, nullptr);
620 // Check these last, so we diagnose problems in operands first.
621 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
622 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
625 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
626 Assert(MD.getValue(), "Expected valid value", &MD);
627 Assert(!MD.getValue()->getType()->isMetadataTy(),
628 "Unexpected metadata round-trip through values", &MD, MD.getValue());
630 auto *L = dyn_cast<LocalAsMetadata>(&MD);
634 Assert(F, "function-local metadata used outside a function", L);
636 // If this was an instruction, bb, or argument, verify that it is in the
637 // function that we expect.
638 Function *ActualF = nullptr;
639 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
640 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
641 ActualF = I->getParent()->getParent();
642 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
643 ActualF = BB->getParent();
644 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
645 ActualF = A->getParent();
646 assert(ActualF && "Unimplemented function local metadata case!");
648 Assert(ActualF == F, "function-local metadata used in wrong function", L);
651 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
652 Metadata *MD = MDV.getMetadata();
653 if (auto *N = dyn_cast<MDNode>(MD)) {
658 // Only visit each node once. Metadata can be mutually recursive, so this
659 // avoids infinite recursion here, as well as being an optimization.
660 if (!MDNodes.insert(MD).second)
663 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
664 visitValueAsMetadata(*V, F);
667 /// \brief Check if a value can be a reference to a type.
668 static bool isTypeRef(const Metadata *MD) {
671 if (auto *S = dyn_cast<MDString>(MD))
672 return !S->getString().empty();
673 return isa<MDType>(MD);
676 /// \brief Check if a value can be a ScopeRef.
677 static bool isScopeRef(const Metadata *MD) {
680 if (auto *S = dyn_cast<MDString>(MD))
681 return !S->getString().empty();
682 return isa<MDScope>(MD);
685 /// \brief Check if a value can be a debug info ref.
686 static bool isDIRef(const Metadata *MD) {
689 if (auto *S = dyn_cast<MDString>(MD))
690 return !S->getString().empty();
691 return isa<DebugNode>(MD);
695 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
696 for (Metadata *MD : N.operands()) {
709 bool isValidMetadataArray(const MDTuple &N) {
710 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
714 bool isValidMetadataNullArray(const MDTuple &N) {
715 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
718 void Verifier::visitMDLocation(const MDLocation &N) {
719 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
720 "location requires a valid scope", &N, N.getRawScope());
721 if (auto *IA = N.getRawInlinedAt())
722 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
725 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
726 Assert(N.getTag(), "invalid tag", &N);
729 void Verifier::visitMDScope(const MDScope &N) {
730 if (auto *F = N.getRawFile())
731 Assert(isa<MDFile>(F), "invalid file", &N, F);
734 void Verifier::visitMDSubrange(const MDSubrange &N) {
735 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
736 Assert(N.getCount() >= -1, "invalid subrange count", &N);
739 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
740 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
743 void Verifier::visitMDBasicType(const MDBasicType &N) {
744 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
745 N.getTag() == dwarf::DW_TAG_unspecified_type,
749 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
750 // Common scope checks.
753 Assert(isScopeRef(N.getScope()), "invalid scope", &N, N.getScope());
754 Assert(isTypeRef(N.getBaseType()), "invalid base type", &N, N.getBaseType());
756 // FIXME: Sink this into the subclass verifies.
757 if (!N.getFile() || N.getFile()->getFilename().empty()) {
758 // Check whether the filename is allowed to be empty.
759 uint16_t Tag = N.getTag();
761 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
762 Tag == dwarf::DW_TAG_pointer_type ||
763 Tag == dwarf::DW_TAG_ptr_to_member_type ||
764 Tag == dwarf::DW_TAG_reference_type ||
765 Tag == dwarf::DW_TAG_rvalue_reference_type ||
766 Tag == dwarf::DW_TAG_restrict_type ||
767 Tag == dwarf::DW_TAG_array_type ||
768 Tag == dwarf::DW_TAG_enumeration_type ||
769 Tag == dwarf::DW_TAG_subroutine_type ||
770 Tag == dwarf::DW_TAG_inheritance || Tag == dwarf::DW_TAG_friend ||
771 Tag == dwarf::DW_TAG_structure_type ||
772 Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef,
773 "derived/composite type requires a filename", &N, N.getFile());
777 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
778 // Common derived type checks.
779 visitMDDerivedTypeBase(N);
781 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
782 N.getTag() == dwarf::DW_TAG_pointer_type ||
783 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
784 N.getTag() == dwarf::DW_TAG_reference_type ||
785 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
786 N.getTag() == dwarf::DW_TAG_const_type ||
787 N.getTag() == dwarf::DW_TAG_volatile_type ||
788 N.getTag() == dwarf::DW_TAG_restrict_type ||
789 N.getTag() == dwarf::DW_TAG_member ||
790 N.getTag() == dwarf::DW_TAG_inheritance ||
791 N.getTag() == dwarf::DW_TAG_friend,
793 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
794 Assert(isTypeRef(N.getExtraData()), "invalid pointer to member type",
795 &N, N.getExtraData());
799 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
800 // Common derived type checks.
801 visitMDDerivedTypeBase(N);
803 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
804 N.getTag() == dwarf::DW_TAG_structure_type ||
805 N.getTag() == dwarf::DW_TAG_union_type ||
806 N.getTag() == dwarf::DW_TAG_enumeration_type ||
807 N.getTag() == dwarf::DW_TAG_subroutine_type ||
808 N.getTag() == dwarf::DW_TAG_class_type,
811 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
812 "invalid composite elements", &N, N.getRawElements());
813 Assert(isTypeRef(N.getRawVTableHolder()), "invalid vtable holder", &N,
814 N.getRawVTableHolder());
815 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
816 "invalid composite elements", &N, N.getRawElements());
819 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
820 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
821 if (auto *Types = N.getRawTypeArray()) {
822 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
823 for (Metadata *Ty : N.getTypeArray()->operands()) {
824 Assert(isTypeRef(Ty), "invalid subroutine type ref", &N, Types, Ty);
829 void Verifier::visitMDFile(const MDFile &N) {
830 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
833 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
834 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
836 // Don't bother verifying the compilation directory or producer string
837 // as those could be empty.
838 Assert(N.getRawFile() && isa<MDFile>(N.getRawFile()),
839 "invalid file", &N, N.getRawFile());
840 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
843 if (auto *Array = N.getRawEnumTypes()) {
844 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
845 for (Metadata *Op : N.getEnumTypes()->operands()) {
846 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
847 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
848 "invalid enum type", &N, N.getEnumTypes(), Op);
851 if (auto *Array = N.getRawRetainedTypes()) {
852 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
853 for (Metadata *Op : N.getRetainedTypes()->operands()) {
854 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
857 if (auto *Array = N.getRawSubprograms()) {
858 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
859 for (Metadata *Op : N.getSubprograms()->operands()) {
860 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
863 if (auto *Array = N.getRawGlobalVariables()) {
864 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
865 for (Metadata *Op : N.getGlobalVariables()->operands()) {
866 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
870 if (auto *Array = N.getRawImportedEntities()) {
871 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
872 for (Metadata *Op : N.getImportedEntities()->operands()) {
873 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
879 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
880 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
881 Assert(isScopeRef(N.getRawScope()), "invalid scope", &N, N.getRawScope());
882 if (auto *T = N.getRawType())
883 Assert(isa<MDSubroutineType>(T), "invalid subroutine type", &N, T);
884 Assert(isTypeRef(N.getRawContainingType()), "invalid containing type", &N,
885 N.getRawContainingType());
886 if (auto *RawF = N.getRawFunction()) {
887 auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
888 auto *F = FMD ? FMD->getValue() : nullptr;
889 auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
890 Assert(F && FT && isa<FunctionType>(FT->getElementType()),
891 "invalid function", &N, F, FT);
893 if (N.getRawTemplateParams()) {
894 auto *Params = dyn_cast<MDTuple>(N.getRawTemplateParams());
895 Assert(Params, "invalid template params", &N, Params);
896 for (Metadata *Op : Params->operands()) {
897 Assert(Op && isa<MDTemplateParameter>(Op), "invalid template parameter",
901 if (auto *S = N.getRawDeclaration()) {
902 Assert(isa<MDSubprogram>(S) && !cast<MDSubprogram>(S)->isDefinition(),
903 "invalid subprogram declaration", &N, S);
905 if (N.getRawVariables()) {
906 auto *Vars = dyn_cast<MDTuple>(N.getRawVariables());
907 Assert(Vars, "invalid variable list", &N, Vars);
908 for (Metadata *Op : Vars->operands()) {
909 Assert(Op && isa<MDLocalVariable>(Op), "invalid local variable", &N, Vars,
915 void Verifier::visitMDLexicalBlockBase(const MDLexicalBlockBase &N) {
916 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
917 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
918 "invalid local scope", &N, N.getRawScope());
921 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
922 visitMDLexicalBlockBase(N);
924 Assert(N.getLine() || !N.getColumn(),
925 "cannot have column info without line info", &N);
928 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
929 visitMDLexicalBlockBase(N);
932 void Verifier::visitMDNamespace(const MDNamespace &N) {
933 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
934 if (auto *S = N.getRawScope())
935 Assert(isa<MDScope>(S), "invalid scope ref", &N, S);
938 void Verifier::visitMDTemplateParameter(const MDTemplateParameter &N) {
939 Assert(isTypeRef(N.getType()), "invalid type ref", &N, N.getType());
942 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
943 visitMDTemplateParameter(N);
945 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
949 void Verifier::visitMDTemplateValueParameter(
950 const MDTemplateValueParameter &N) {
951 visitMDTemplateParameter(N);
953 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
954 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
955 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
959 void Verifier::visitMDVariable(const MDVariable &N) {
960 if (auto *S = N.getRawScope())
961 Assert(isa<MDScope>(S), "invalid scope", &N, S);
962 Assert(isTypeRef(N.getRawType()), "invalid type ref", &N, N.getRawType());
963 if (auto *F = N.getRawFile())
964 Assert(isa<MDFile>(F), "invalid file", &N, F);
967 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
968 // Checks common to all variables.
971 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
972 Assert(!N.getName().empty(), "missing global variable name", &N);
973 if (auto *V = N.getRawVariable()) {
974 Assert(isa<ConstantAsMetadata>(V) &&
975 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
976 "invalid global varaible ref", &N, V);
978 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
979 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
984 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
985 // Checks common to all variables.
988 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
989 N.getTag() == dwarf::DW_TAG_arg_variable,
991 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
992 "local variable requires a valid scope", &N, N.getRawScope());
993 if (auto *IA = N.getRawInlinedAt())
994 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
998 void Verifier::visitMDExpression(const MDExpression &N) {
999 Assert(N.isValid(), "invalid expression", &N);
1002 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
1003 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1004 if (auto *T = N.getRawType())
1005 Assert(isa<MDType>(T), "invalid type ref", &N, T);
1006 if (auto *F = N.getRawFile())
1007 Assert(isa<MDFile>(F), "invalid file", &N, F);
1010 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
1011 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1012 N.getTag() == dwarf::DW_TAG_imported_declaration,
1014 if (auto *S = N.getRawScope())
1015 Assert(isa<MDScope>(S), "invalid scope for imported entity", &N, S);
1016 Assert(isDIRef(N.getEntity()), "invalid imported entity", &N, N.getEntity());
1019 void Verifier::visitComdat(const Comdat &C) {
1020 // The Module is invalid if the GlobalValue has private linkage. Entities
1021 // with private linkage don't have entries in the symbol table.
1022 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1023 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1027 void Verifier::visitModuleIdents(const Module &M) {
1028 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1032 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1033 // Scan each llvm.ident entry and make sure that this requirement is met.
1034 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1035 const MDNode *N = Idents->getOperand(i);
1036 Assert(N->getNumOperands() == 1,
1037 "incorrect number of operands in llvm.ident metadata", N);
1038 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1039 ("invalid value for llvm.ident metadata entry operand"
1040 "(the operand should be a string)"),
1045 void Verifier::visitModuleFlags(const Module &M) {
1046 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1049 // Scan each flag, and track the flags and requirements.
1050 DenseMap<const MDString*, const MDNode*> SeenIDs;
1051 SmallVector<const MDNode*, 16> Requirements;
1052 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1053 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1056 // Validate that the requirements in the module are valid.
1057 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1058 const MDNode *Requirement = Requirements[I];
1059 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1060 const Metadata *ReqValue = Requirement->getOperand(1);
1062 const MDNode *Op = SeenIDs.lookup(Flag);
1064 CheckFailed("invalid requirement on flag, flag is not present in module",
1069 if (Op->getOperand(2) != ReqValue) {
1070 CheckFailed(("invalid requirement on flag, "
1071 "flag does not have the required value"),
1079 Verifier::visitModuleFlag(const MDNode *Op,
1080 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1081 SmallVectorImpl<const MDNode *> &Requirements) {
1082 // Each module flag should have three arguments, the merge behavior (a
1083 // constant int), the flag ID (an MDString), and the value.
1084 Assert(Op->getNumOperands() == 3,
1085 "incorrect number of operands in module flag", Op);
1086 Module::ModFlagBehavior MFB;
1087 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1089 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1090 "invalid behavior operand in module flag (expected constant integer)",
1093 "invalid behavior operand in module flag (unexpected constant)",
1096 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1097 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1100 // Sanity check the values for behaviors with additional requirements.
1103 case Module::Warning:
1104 case Module::Override:
1105 // These behavior types accept any value.
1108 case Module::Require: {
1109 // The value should itself be an MDNode with two operands, a flag ID (an
1110 // MDString), and a value.
1111 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1112 Assert(Value && Value->getNumOperands() == 2,
1113 "invalid value for 'require' module flag (expected metadata pair)",
1115 Assert(isa<MDString>(Value->getOperand(0)),
1116 ("invalid value for 'require' module flag "
1117 "(first value operand should be a string)"),
1118 Value->getOperand(0));
1120 // Append it to the list of requirements, to check once all module flags are
1122 Requirements.push_back(Value);
1126 case Module::Append:
1127 case Module::AppendUnique: {
1128 // These behavior types require the operand be an MDNode.
1129 Assert(isa<MDNode>(Op->getOperand(2)),
1130 "invalid value for 'append'-type module flag "
1131 "(expected a metadata node)",
1137 // Unless this is a "requires" flag, check the ID is unique.
1138 if (MFB != Module::Require) {
1139 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1141 "module flag identifiers must be unique (or of 'require' type)", ID);
1145 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1146 bool isFunction, const Value *V) {
1147 unsigned Slot = ~0U;
1148 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1149 if (Attrs.getSlotIndex(I) == Idx) {
1154 assert(Slot != ~0U && "Attribute set inconsistency!");
1156 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1158 if (I->isStringAttribute())
1161 if (I->getKindAsEnum() == Attribute::NoReturn ||
1162 I->getKindAsEnum() == Attribute::NoUnwind ||
1163 I->getKindAsEnum() == Attribute::NoInline ||
1164 I->getKindAsEnum() == Attribute::AlwaysInline ||
1165 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1166 I->getKindAsEnum() == Attribute::StackProtect ||
1167 I->getKindAsEnum() == Attribute::StackProtectReq ||
1168 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1169 I->getKindAsEnum() == Attribute::NoRedZone ||
1170 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1171 I->getKindAsEnum() == Attribute::Naked ||
1172 I->getKindAsEnum() == Attribute::InlineHint ||
1173 I->getKindAsEnum() == Attribute::StackAlignment ||
1174 I->getKindAsEnum() == Attribute::UWTable ||
1175 I->getKindAsEnum() == Attribute::NonLazyBind ||
1176 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1177 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1178 I->getKindAsEnum() == Attribute::SanitizeThread ||
1179 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1180 I->getKindAsEnum() == Attribute::MinSize ||
1181 I->getKindAsEnum() == Attribute::NoDuplicate ||
1182 I->getKindAsEnum() == Attribute::Builtin ||
1183 I->getKindAsEnum() == Attribute::NoBuiltin ||
1184 I->getKindAsEnum() == Attribute::Cold ||
1185 I->getKindAsEnum() == Attribute::OptimizeNone ||
1186 I->getKindAsEnum() == Attribute::JumpTable) {
1188 CheckFailed("Attribute '" + I->getAsString() +
1189 "' only applies to functions!", V);
1192 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1193 I->getKindAsEnum() == Attribute::ReadNone) {
1195 CheckFailed("Attribute '" + I->getAsString() +
1196 "' does not apply to function returns");
1199 } else if (isFunction) {
1200 CheckFailed("Attribute '" + I->getAsString() +
1201 "' does not apply to functions!", V);
1207 // VerifyParameterAttrs - Check the given attributes for an argument or return
1208 // value of the specified type. The value V is printed in error messages.
1209 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1210 bool isReturnValue, const Value *V) {
1211 if (!Attrs.hasAttributes(Idx))
1214 VerifyAttributeTypes(Attrs, Idx, false, V);
1217 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1218 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1219 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1220 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1221 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1222 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1223 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1224 "'returned' do not apply to return values!",
1227 // Check for mutually incompatible attributes. Only inreg is compatible with
1229 unsigned AttrCount = 0;
1230 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1231 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1232 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1233 Attrs.hasAttribute(Idx, Attribute::InReg);
1234 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1235 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1236 "and 'sret' are incompatible!",
1239 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1240 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1242 "'inalloca and readonly' are incompatible!",
1245 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1246 Attrs.hasAttribute(Idx, Attribute::Returned)),
1248 "'sret and returned' are incompatible!",
1251 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1252 Attrs.hasAttribute(Idx, Attribute::SExt)),
1254 "'zeroext and signext' are incompatible!",
1257 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1258 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1260 "'readnone and readonly' are incompatible!",
1263 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1264 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1266 "'noinline and alwaysinline' are incompatible!",
1269 Assert(!AttrBuilder(Attrs, Idx)
1270 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1271 "Wrong types for attribute: " +
1272 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1275 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1276 SmallPtrSet<const Type*, 4> Visited;
1277 if (!PTy->getElementType()->isSized(&Visited)) {
1278 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1279 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1280 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1284 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1285 "Attribute 'byval' only applies to parameters with pointer type!",
1290 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1291 // The value V is printed in error messages.
1292 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1294 if (Attrs.isEmpty())
1297 bool SawNest = false;
1298 bool SawReturned = false;
1299 bool SawSRet = false;
1301 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1302 unsigned Idx = Attrs.getSlotIndex(i);
1306 Ty = FT->getReturnType();
1307 else if (Idx-1 < FT->getNumParams())
1308 Ty = FT->getParamType(Idx-1);
1310 break; // VarArgs attributes, verified elsewhere.
1312 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1317 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1318 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1322 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1323 Assert(!SawReturned, "More than one parameter has attribute returned!",
1325 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1327 "argument and return types for 'returned' attribute",
1332 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1333 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1334 Assert(Idx == 1 || Idx == 2,
1335 "Attribute 'sret' is not on first or second parameter!", V);
1339 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1340 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1345 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1348 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1351 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1352 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1353 "Attributes 'readnone and readonly' are incompatible!", V);
1356 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1357 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1358 Attribute::AlwaysInline)),
1359 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1361 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1362 Attribute::OptimizeNone)) {
1363 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1364 "Attribute 'optnone' requires 'noinline'!", V);
1366 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1367 Attribute::OptimizeForSize),
1368 "Attributes 'optsize and optnone' are incompatible!", V);
1370 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1371 "Attributes 'minsize and optnone' are incompatible!", V);
1374 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1375 Attribute::JumpTable)) {
1376 const GlobalValue *GV = cast<GlobalValue>(V);
1377 Assert(GV->hasUnnamedAddr(),
1378 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1382 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1383 if (CE->getOpcode() != Instruction::BitCast)
1386 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1388 "Invalid bitcast", CE);
1391 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1392 if (Attrs.getNumSlots() == 0)
1395 unsigned LastSlot = Attrs.getNumSlots() - 1;
1396 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1397 if (LastIndex <= Params
1398 || (LastIndex == AttributeSet::FunctionIndex
1399 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1405 /// \brief Verify that statepoint intrinsic is well formed.
1406 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1407 assert(CS.getCalledFunction() &&
1408 CS.getCalledFunction()->getIntrinsicID() ==
1409 Intrinsic::experimental_gc_statepoint);
1411 const Instruction &CI = *CS.getInstruction();
1413 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1414 "gc.statepoint must read and write memory to preserve "
1415 "reordering restrictions required by safepoint semantics",
1418 const Value *Target = CS.getArgument(0);
1419 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1420 Assert(PT && PT->getElementType()->isFunctionTy(),
1421 "gc.statepoint callee must be of function pointer type", &CI, Target);
1422 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1424 const Value *NumCallArgsV = CS.getArgument(1);
1425 Assert(isa<ConstantInt>(NumCallArgsV),
1426 "gc.statepoint number of arguments to underlying call "
1427 "must be constant integer",
1429 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1430 Assert(NumCallArgs >= 0,
1431 "gc.statepoint number of arguments to underlying call "
1434 const int NumParams = (int)TargetFuncType->getNumParams();
1435 if (TargetFuncType->isVarArg()) {
1436 Assert(NumCallArgs >= NumParams,
1437 "gc.statepoint mismatch in number of vararg call args", &CI);
1439 // TODO: Remove this limitation
1440 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1441 "gc.statepoint doesn't support wrapping non-void "
1442 "vararg functions yet",
1445 Assert(NumCallArgs == NumParams,
1446 "gc.statepoint mismatch in number of call args", &CI);
1448 const Value *Unused = CS.getArgument(2);
1449 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1450 "gc.statepoint parameter #3 must be zero", &CI);
1452 // Verify that the types of the call parameter arguments match
1453 // the type of the wrapped callee.
1454 for (int i = 0; i < NumParams; i++) {
1455 Type *ParamType = TargetFuncType->getParamType(i);
1456 Type *ArgType = CS.getArgument(3+i)->getType();
1457 Assert(ArgType == ParamType,
1458 "gc.statepoint call argument does not match wrapped "
1462 const int EndCallArgsInx = 2+NumCallArgs;
1463 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1464 Assert(isa<ConstantInt>(NumDeoptArgsV),
1465 "gc.statepoint number of deoptimization arguments "
1466 "must be constant integer",
1468 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1469 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1473 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1474 "gc.statepoint too few arguments according to length fields", &CI);
1476 // Check that the only uses of this gc.statepoint are gc.result or
1477 // gc.relocate calls which are tied to this statepoint and thus part
1478 // of the same statepoint sequence
1479 for (const User *U : CI.users()) {
1480 const CallInst *Call = dyn_cast<const CallInst>(U);
1481 Assert(Call, "illegal use of statepoint token", &CI, U);
1482 if (!Call) continue;
1483 Assert(isGCRelocate(Call) || isGCResult(Call),
1484 "gc.result or gc.relocate are the only value uses"
1485 "of a gc.statepoint",
1487 if (isGCResult(Call)) {
1488 Assert(Call->getArgOperand(0) == &CI,
1489 "gc.result connected to wrong gc.statepoint", &CI, Call);
1490 } else if (isGCRelocate(Call)) {
1491 Assert(Call->getArgOperand(0) == &CI,
1492 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1496 // Note: It is legal for a single derived pointer to be listed multiple
1497 // times. It's non-optimal, but it is legal. It can also happen after
1498 // insertion if we strip a bitcast away.
1499 // Note: It is really tempting to check that each base is relocated and
1500 // that a derived pointer is never reused as a base pointer. This turns
1501 // out to be problematic since optimizations run after safepoint insertion
1502 // can recognize equality properties that the insertion logic doesn't know
1503 // about. See example statepoint.ll in the verifier subdirectory
1506 void Verifier::verifyFrameRecoverIndices() {
1507 for (auto &Counts : FrameEscapeInfo) {
1508 Function *F = Counts.first;
1509 unsigned EscapedObjectCount = Counts.second.first;
1510 unsigned MaxRecoveredIndex = Counts.second.second;
1511 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1512 "all indices passed to llvm.framerecover must be less than the "
1513 "number of arguments passed ot llvm.frameescape in the parent "
1519 // visitFunction - Verify that a function is ok.
1521 void Verifier::visitFunction(const Function &F) {
1522 // Check function arguments.
1523 FunctionType *FT = F.getFunctionType();
1524 unsigned NumArgs = F.arg_size();
1526 Assert(Context == &F.getContext(),
1527 "Function context does not match Module context!", &F);
1529 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1530 Assert(FT->getNumParams() == NumArgs,
1531 "# formal arguments must match # of arguments for function type!", &F,
1533 Assert(F.getReturnType()->isFirstClassType() ||
1534 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1535 "Functions cannot return aggregate values!", &F);
1537 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1538 "Invalid struct return type!", &F);
1540 AttributeSet Attrs = F.getAttributes();
1542 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1543 "Attribute after last parameter!", &F);
1545 // Check function attributes.
1546 VerifyFunctionAttrs(FT, Attrs, &F);
1548 // On function declarations/definitions, we do not support the builtin
1549 // attribute. We do not check this in VerifyFunctionAttrs since that is
1550 // checking for Attributes that can/can not ever be on functions.
1551 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1552 "Attribute 'builtin' can only be applied to a callsite.", &F);
1554 // Check that this function meets the restrictions on this calling convention.
1555 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1556 // restrictions can be lifted.
1557 switch (F.getCallingConv()) {
1559 case CallingConv::C:
1561 case CallingConv::Fast:
1562 case CallingConv::Cold:
1563 case CallingConv::Intel_OCL_BI:
1564 case CallingConv::PTX_Kernel:
1565 case CallingConv::PTX_Device:
1566 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1567 "perfect forwarding!",
1572 bool isLLVMdotName = F.getName().size() >= 5 &&
1573 F.getName().substr(0, 5) == "llvm.";
1575 // Check that the argument values match the function type for this function...
1577 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1579 Assert(I->getType() == FT->getParamType(i),
1580 "Argument value does not match function argument type!", I,
1581 FT->getParamType(i));
1582 Assert(I->getType()->isFirstClassType(),
1583 "Function arguments must have first-class types!", I);
1585 Assert(!I->getType()->isMetadataTy(),
1586 "Function takes metadata but isn't an intrinsic", I, &F);
1589 if (F.isMaterializable()) {
1590 // Function has a body somewhere we can't see.
1591 } else if (F.isDeclaration()) {
1592 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1593 "invalid linkage type for function declaration", &F);
1595 // Verify that this function (which has a body) is not named "llvm.*". It
1596 // is not legal to define intrinsics.
1597 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1599 // Check the entry node
1600 const BasicBlock *Entry = &F.getEntryBlock();
1601 Assert(pred_empty(Entry),
1602 "Entry block to function must not have predecessors!", Entry);
1604 // The address of the entry block cannot be taken, unless it is dead.
1605 if (Entry->hasAddressTaken()) {
1606 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1607 "blockaddress may not be used with the entry block!", Entry);
1611 // If this function is actually an intrinsic, verify that it is only used in
1612 // direct call/invokes, never having its "address taken".
1613 if (F.getIntrinsicID()) {
1615 if (F.hasAddressTaken(&U))
1616 Assert(0, "Invalid user of intrinsic instruction!", U);
1619 Assert(!F.hasDLLImportStorageClass() ||
1620 (F.isDeclaration() && F.hasExternalLinkage()) ||
1621 F.hasAvailableExternallyLinkage(),
1622 "Function is marked as dllimport, but not external.", &F);
1625 // verifyBasicBlock - Verify that a basic block is well formed...
1627 void Verifier::visitBasicBlock(BasicBlock &BB) {
1628 InstsInThisBlock.clear();
1630 // Ensure that basic blocks have terminators!
1631 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1633 // Check constraints that this basic block imposes on all of the PHI nodes in
1635 if (isa<PHINode>(BB.front())) {
1636 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1637 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1638 std::sort(Preds.begin(), Preds.end());
1640 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1641 // Ensure that PHI nodes have at least one entry!
1642 Assert(PN->getNumIncomingValues() != 0,
1643 "PHI nodes must have at least one entry. If the block is dead, "
1644 "the PHI should be removed!",
1646 Assert(PN->getNumIncomingValues() == Preds.size(),
1647 "PHINode should have one entry for each predecessor of its "
1648 "parent basic block!",
1651 // Get and sort all incoming values in the PHI node...
1653 Values.reserve(PN->getNumIncomingValues());
1654 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1655 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1656 PN->getIncomingValue(i)));
1657 std::sort(Values.begin(), Values.end());
1659 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1660 // Check to make sure that if there is more than one entry for a
1661 // particular basic block in this PHI node, that the incoming values are
1664 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1665 Values[i].second == Values[i - 1].second,
1666 "PHI node has multiple entries for the same basic block with "
1667 "different incoming values!",
1668 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1670 // Check to make sure that the predecessors and PHI node entries are
1672 Assert(Values[i].first == Preds[i],
1673 "PHI node entries do not match predecessors!", PN,
1674 Values[i].first, Preds[i]);
1679 // Check that all instructions have their parent pointers set up correctly.
1682 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1686 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1687 // Ensure that terminators only exist at the end of the basic block.
1688 Assert(&I == I.getParent()->getTerminator(),
1689 "Terminator found in the middle of a basic block!", I.getParent());
1690 visitInstruction(I);
1693 void Verifier::visitBranchInst(BranchInst &BI) {
1694 if (BI.isConditional()) {
1695 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1696 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1698 visitTerminatorInst(BI);
1701 void Verifier::visitReturnInst(ReturnInst &RI) {
1702 Function *F = RI.getParent()->getParent();
1703 unsigned N = RI.getNumOperands();
1704 if (F->getReturnType()->isVoidTy())
1706 "Found return instr that returns non-void in Function of void "
1708 &RI, F->getReturnType());
1710 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1711 "Function return type does not match operand "
1712 "type of return inst!",
1713 &RI, F->getReturnType());
1715 // Check to make sure that the return value has necessary properties for
1717 visitTerminatorInst(RI);
1720 void Verifier::visitSwitchInst(SwitchInst &SI) {
1721 // Check to make sure that all of the constants in the switch instruction
1722 // have the same type as the switched-on value.
1723 Type *SwitchTy = SI.getCondition()->getType();
1724 SmallPtrSet<ConstantInt*, 32> Constants;
1725 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1726 Assert(i.getCaseValue()->getType() == SwitchTy,
1727 "Switch constants must all be same type as switch value!", &SI);
1728 Assert(Constants.insert(i.getCaseValue()).second,
1729 "Duplicate integer as switch case", &SI, i.getCaseValue());
1732 visitTerminatorInst(SI);
1735 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1736 Assert(BI.getAddress()->getType()->isPointerTy(),
1737 "Indirectbr operand must have pointer type!", &BI);
1738 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1739 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1740 "Indirectbr destinations must all have pointer type!", &BI);
1742 visitTerminatorInst(BI);
1745 void Verifier::visitSelectInst(SelectInst &SI) {
1746 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1748 "Invalid operands for select instruction!", &SI);
1750 Assert(SI.getTrueValue()->getType() == SI.getType(),
1751 "Select values must have same type as select instruction!", &SI);
1752 visitInstruction(SI);
1755 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1756 /// a pass, if any exist, it's an error.
1758 void Verifier::visitUserOp1(Instruction &I) {
1759 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1762 void Verifier::visitTruncInst(TruncInst &I) {
1763 // Get the source and destination types
1764 Type *SrcTy = I.getOperand(0)->getType();
1765 Type *DestTy = I.getType();
1767 // Get the size of the types in bits, we'll need this later
1768 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1769 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1771 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1772 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1773 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1774 "trunc source and destination must both be a vector or neither", &I);
1775 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1777 visitInstruction(I);
1780 void Verifier::visitZExtInst(ZExtInst &I) {
1781 // Get the source and destination types
1782 Type *SrcTy = I.getOperand(0)->getType();
1783 Type *DestTy = I.getType();
1785 // Get the size of the types in bits, we'll need this later
1786 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1787 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1788 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1789 "zext source and destination must both be a vector or neither", &I);
1790 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1791 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1793 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1795 visitInstruction(I);
1798 void Verifier::visitSExtInst(SExtInst &I) {
1799 // Get the source and destination types
1800 Type *SrcTy = I.getOperand(0)->getType();
1801 Type *DestTy = I.getType();
1803 // Get the size of the types in bits, we'll need this later
1804 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1805 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1807 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1808 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1809 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1810 "sext source and destination must both be a vector or neither", &I);
1811 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1813 visitInstruction(I);
1816 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1817 // Get the source and destination types
1818 Type *SrcTy = I.getOperand(0)->getType();
1819 Type *DestTy = I.getType();
1820 // Get the size of the types in bits, we'll need this later
1821 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1822 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1824 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1825 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1826 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1827 "fptrunc source and destination must both be a vector or neither", &I);
1828 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1830 visitInstruction(I);
1833 void Verifier::visitFPExtInst(FPExtInst &I) {
1834 // Get the source and destination types
1835 Type *SrcTy = I.getOperand(0)->getType();
1836 Type *DestTy = I.getType();
1838 // Get the size of the types in bits, we'll need this later
1839 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1840 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1842 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1843 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1844 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1845 "fpext source and destination must both be a vector or neither", &I);
1846 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1848 visitInstruction(I);
1851 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1852 // Get the source and destination types
1853 Type *SrcTy = I.getOperand(0)->getType();
1854 Type *DestTy = I.getType();
1856 bool SrcVec = SrcTy->isVectorTy();
1857 bool DstVec = DestTy->isVectorTy();
1859 Assert(SrcVec == DstVec,
1860 "UIToFP source and dest must both be vector or scalar", &I);
1861 Assert(SrcTy->isIntOrIntVectorTy(),
1862 "UIToFP source must be integer or integer vector", &I);
1863 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1866 if (SrcVec && DstVec)
1867 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1868 cast<VectorType>(DestTy)->getNumElements(),
1869 "UIToFP source and dest vector length mismatch", &I);
1871 visitInstruction(I);
1874 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1875 // Get the source and destination types
1876 Type *SrcTy = I.getOperand(0)->getType();
1877 Type *DestTy = I.getType();
1879 bool SrcVec = SrcTy->isVectorTy();
1880 bool DstVec = DestTy->isVectorTy();
1882 Assert(SrcVec == DstVec,
1883 "SIToFP source and dest must both be vector or scalar", &I);
1884 Assert(SrcTy->isIntOrIntVectorTy(),
1885 "SIToFP source must be integer or integer vector", &I);
1886 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1889 if (SrcVec && DstVec)
1890 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1891 cast<VectorType>(DestTy)->getNumElements(),
1892 "SIToFP source and dest vector length mismatch", &I);
1894 visitInstruction(I);
1897 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1898 // Get the source and destination types
1899 Type *SrcTy = I.getOperand(0)->getType();
1900 Type *DestTy = I.getType();
1902 bool SrcVec = SrcTy->isVectorTy();
1903 bool DstVec = DestTy->isVectorTy();
1905 Assert(SrcVec == DstVec,
1906 "FPToUI source and dest must both be vector or scalar", &I);
1907 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1909 Assert(DestTy->isIntOrIntVectorTy(),
1910 "FPToUI result must be integer or integer vector", &I);
1912 if (SrcVec && DstVec)
1913 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1914 cast<VectorType>(DestTy)->getNumElements(),
1915 "FPToUI source and dest vector length mismatch", &I);
1917 visitInstruction(I);
1920 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1921 // Get the source and destination types
1922 Type *SrcTy = I.getOperand(0)->getType();
1923 Type *DestTy = I.getType();
1925 bool SrcVec = SrcTy->isVectorTy();
1926 bool DstVec = DestTy->isVectorTy();
1928 Assert(SrcVec == DstVec,
1929 "FPToSI source and dest must both be vector or scalar", &I);
1930 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
1932 Assert(DestTy->isIntOrIntVectorTy(),
1933 "FPToSI result must be integer or integer vector", &I);
1935 if (SrcVec && DstVec)
1936 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1937 cast<VectorType>(DestTy)->getNumElements(),
1938 "FPToSI source and dest vector length mismatch", &I);
1940 visitInstruction(I);
1943 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1944 // Get the source and destination types
1945 Type *SrcTy = I.getOperand(0)->getType();
1946 Type *DestTy = I.getType();
1948 Assert(SrcTy->getScalarType()->isPointerTy(),
1949 "PtrToInt source must be pointer", &I);
1950 Assert(DestTy->getScalarType()->isIntegerTy(),
1951 "PtrToInt result must be integral", &I);
1952 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
1955 if (SrcTy->isVectorTy()) {
1956 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1957 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1958 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1959 "PtrToInt Vector width mismatch", &I);
1962 visitInstruction(I);
1965 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1966 // Get the source and destination types
1967 Type *SrcTy = I.getOperand(0)->getType();
1968 Type *DestTy = I.getType();
1970 Assert(SrcTy->getScalarType()->isIntegerTy(),
1971 "IntToPtr source must be an integral", &I);
1972 Assert(DestTy->getScalarType()->isPointerTy(),
1973 "IntToPtr result must be a pointer", &I);
1974 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
1976 if (SrcTy->isVectorTy()) {
1977 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1978 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1979 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1980 "IntToPtr Vector width mismatch", &I);
1982 visitInstruction(I);
1985 void Verifier::visitBitCastInst(BitCastInst &I) {
1987 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1988 "Invalid bitcast", &I);
1989 visitInstruction(I);
1992 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1993 Type *SrcTy = I.getOperand(0)->getType();
1994 Type *DestTy = I.getType();
1996 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
1998 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2000 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2001 "AddrSpaceCast must be between different address spaces", &I);
2002 if (SrcTy->isVectorTy())
2003 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2004 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2005 visitInstruction(I);
2008 /// visitPHINode - Ensure that a PHI node is well formed.
2010 void Verifier::visitPHINode(PHINode &PN) {
2011 // Ensure that the PHI nodes are all grouped together at the top of the block.
2012 // This can be tested by checking whether the instruction before this is
2013 // either nonexistent (because this is begin()) or is a PHI node. If not,
2014 // then there is some other instruction before a PHI.
2015 Assert(&PN == &PN.getParent()->front() ||
2016 isa<PHINode>(--BasicBlock::iterator(&PN)),
2017 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2019 // Check that all of the values of the PHI node have the same type as the
2020 // result, and that the incoming blocks are really basic blocks.
2021 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2022 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
2023 "PHI node operands are not the same type as the result!", &PN);
2026 // All other PHI node constraints are checked in the visitBasicBlock method.
2028 visitInstruction(PN);
2031 void Verifier::VerifyCallSite(CallSite CS) {
2032 Instruction *I = CS.getInstruction();
2034 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2035 "Called function must be a pointer!", I);
2036 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2038 Assert(FPTy->getElementType()->isFunctionTy(),
2039 "Called function is not pointer to function type!", I);
2040 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
2042 // Verify that the correct number of arguments are being passed
2043 if (FTy->isVarArg())
2044 Assert(CS.arg_size() >= FTy->getNumParams(),
2045 "Called function requires more parameters than were provided!", I);
2047 Assert(CS.arg_size() == FTy->getNumParams(),
2048 "Incorrect number of arguments passed to called function!", I);
2050 // Verify that all arguments to the call match the function type.
2051 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2052 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2053 "Call parameter type does not match function signature!",
2054 CS.getArgument(i), FTy->getParamType(i), I);
2056 AttributeSet Attrs = CS.getAttributes();
2058 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2059 "Attribute after last parameter!", I);
2061 // Verify call attributes.
2062 VerifyFunctionAttrs(FTy, Attrs, I);
2064 // Conservatively check the inalloca argument.
2065 // We have a bug if we can find that there is an underlying alloca without
2067 if (CS.hasInAllocaArgument()) {
2068 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2069 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2070 Assert(AI->isUsedWithInAlloca(),
2071 "inalloca argument for call has mismatched alloca", AI, I);
2074 if (FTy->isVarArg()) {
2075 // FIXME? is 'nest' even legal here?
2076 bool SawNest = false;
2077 bool SawReturned = false;
2079 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2080 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2082 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2086 // Check attributes on the varargs part.
2087 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2088 Type *Ty = CS.getArgument(Idx-1)->getType();
2089 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2091 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2092 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2096 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2097 Assert(!SawReturned, "More than one parameter has attribute returned!",
2099 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2100 "Incompatible argument and return types for 'returned' "
2106 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2107 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2109 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2110 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2114 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2115 if (CS.getCalledFunction() == nullptr ||
2116 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2117 for (FunctionType::param_iterator PI = FTy->param_begin(),
2118 PE = FTy->param_end(); PI != PE; ++PI)
2119 Assert(!(*PI)->isMetadataTy(),
2120 "Function has metadata parameter but isn't an intrinsic", I);
2123 visitInstruction(*I);
2126 /// Two types are "congruent" if they are identical, or if they are both pointer
2127 /// types with different pointee types and the same address space.
2128 static bool isTypeCongruent(Type *L, Type *R) {
2131 PointerType *PL = dyn_cast<PointerType>(L);
2132 PointerType *PR = dyn_cast<PointerType>(R);
2135 return PL->getAddressSpace() == PR->getAddressSpace();
2138 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2139 static const Attribute::AttrKind ABIAttrs[] = {
2140 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2141 Attribute::InReg, Attribute::Returned};
2143 for (auto AK : ABIAttrs) {
2144 if (Attrs.hasAttribute(I + 1, AK))
2145 Copy.addAttribute(AK);
2147 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2148 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2152 void Verifier::verifyMustTailCall(CallInst &CI) {
2153 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2155 // - The caller and callee prototypes must match. Pointer types of
2156 // parameters or return types may differ in pointee type, but not
2158 Function *F = CI.getParent()->getParent();
2159 auto GetFnTy = [](Value *V) {
2160 return cast<FunctionType>(
2161 cast<PointerType>(V->getType())->getElementType());
2163 FunctionType *CallerTy = GetFnTy(F);
2164 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2165 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2166 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2167 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2168 "cannot guarantee tail call due to mismatched varargs", &CI);
2169 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2170 "cannot guarantee tail call due to mismatched return types", &CI);
2171 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2173 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2174 "cannot guarantee tail call due to mismatched parameter types", &CI);
2177 // - The calling conventions of the caller and callee must match.
2178 Assert(F->getCallingConv() == CI.getCallingConv(),
2179 "cannot guarantee tail call due to mismatched calling conv", &CI);
2181 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2182 // returned, and inalloca, must match.
2183 AttributeSet CallerAttrs = F->getAttributes();
2184 AttributeSet CalleeAttrs = CI.getAttributes();
2185 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2186 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2187 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2188 Assert(CallerABIAttrs == CalleeABIAttrs,
2189 "cannot guarantee tail call due to mismatched ABI impacting "
2190 "function attributes",
2191 &CI, CI.getOperand(I));
2194 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2195 // or a pointer bitcast followed by a ret instruction.
2196 // - The ret instruction must return the (possibly bitcasted) value
2197 // produced by the call or void.
2198 Value *RetVal = &CI;
2199 Instruction *Next = CI.getNextNode();
2201 // Handle the optional bitcast.
2202 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2203 Assert(BI->getOperand(0) == RetVal,
2204 "bitcast following musttail call must use the call", BI);
2206 Next = BI->getNextNode();
2209 // Check the return.
2210 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2211 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2213 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2214 "musttail call result must be returned", Ret);
2217 void Verifier::visitCallInst(CallInst &CI) {
2218 VerifyCallSite(&CI);
2220 if (CI.isMustTailCall())
2221 verifyMustTailCall(CI);
2223 if (Function *F = CI.getCalledFunction())
2224 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2225 visitIntrinsicFunctionCall(ID, CI);
2228 void Verifier::visitInvokeInst(InvokeInst &II) {
2229 VerifyCallSite(&II);
2231 // Verify that there is a landingpad instruction as the first non-PHI
2232 // instruction of the 'unwind' destination.
2233 Assert(II.getUnwindDest()->isLandingPad(),
2234 "The unwind destination does not have a landingpad instruction!", &II);
2236 if (Function *F = II.getCalledFunction())
2237 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2238 // CallInst as an input parameter. It not woth updating this whole
2239 // function only to support statepoint verification.
2240 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2241 VerifyStatepoint(ImmutableCallSite(&II));
2243 visitTerminatorInst(II);
2246 /// visitBinaryOperator - Check that both arguments to the binary operator are
2247 /// of the same type!
2249 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2250 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2251 "Both operands to a binary operator are not of the same type!", &B);
2253 switch (B.getOpcode()) {
2254 // Check that integer arithmetic operators are only used with
2255 // integral operands.
2256 case Instruction::Add:
2257 case Instruction::Sub:
2258 case Instruction::Mul:
2259 case Instruction::SDiv:
2260 case Instruction::UDiv:
2261 case Instruction::SRem:
2262 case Instruction::URem:
2263 Assert(B.getType()->isIntOrIntVectorTy(),
2264 "Integer arithmetic operators only work with integral types!", &B);
2265 Assert(B.getType() == B.getOperand(0)->getType(),
2266 "Integer arithmetic operators must have same type "
2267 "for operands and result!",
2270 // Check that floating-point arithmetic operators are only used with
2271 // floating-point operands.
2272 case Instruction::FAdd:
2273 case Instruction::FSub:
2274 case Instruction::FMul:
2275 case Instruction::FDiv:
2276 case Instruction::FRem:
2277 Assert(B.getType()->isFPOrFPVectorTy(),
2278 "Floating-point arithmetic operators only work with "
2279 "floating-point types!",
2281 Assert(B.getType() == B.getOperand(0)->getType(),
2282 "Floating-point arithmetic operators must have same type "
2283 "for operands and result!",
2286 // Check that logical operators are only used with integral operands.
2287 case Instruction::And:
2288 case Instruction::Or:
2289 case Instruction::Xor:
2290 Assert(B.getType()->isIntOrIntVectorTy(),
2291 "Logical operators only work with integral types!", &B);
2292 Assert(B.getType() == B.getOperand(0)->getType(),
2293 "Logical operators must have same type for operands and result!",
2296 case Instruction::Shl:
2297 case Instruction::LShr:
2298 case Instruction::AShr:
2299 Assert(B.getType()->isIntOrIntVectorTy(),
2300 "Shifts only work with integral types!", &B);
2301 Assert(B.getType() == B.getOperand(0)->getType(),
2302 "Shift return type must be same as operands!", &B);
2305 llvm_unreachable("Unknown BinaryOperator opcode!");
2308 visitInstruction(B);
2311 void Verifier::visitICmpInst(ICmpInst &IC) {
2312 // Check that the operands are the same type
2313 Type *Op0Ty = IC.getOperand(0)->getType();
2314 Type *Op1Ty = IC.getOperand(1)->getType();
2315 Assert(Op0Ty == Op1Ty,
2316 "Both operands to ICmp instruction are not of the same type!", &IC);
2317 // Check that the operands are the right type
2318 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2319 "Invalid operand types for ICmp instruction", &IC);
2320 // Check that the predicate is valid.
2321 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2322 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2323 "Invalid predicate in ICmp instruction!", &IC);
2325 visitInstruction(IC);
2328 void Verifier::visitFCmpInst(FCmpInst &FC) {
2329 // Check that the operands are the same type
2330 Type *Op0Ty = FC.getOperand(0)->getType();
2331 Type *Op1Ty = FC.getOperand(1)->getType();
2332 Assert(Op0Ty == Op1Ty,
2333 "Both operands to FCmp instruction are not of the same type!", &FC);
2334 // Check that the operands are the right type
2335 Assert(Op0Ty->isFPOrFPVectorTy(),
2336 "Invalid operand types for FCmp instruction", &FC);
2337 // Check that the predicate is valid.
2338 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2339 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2340 "Invalid predicate in FCmp instruction!", &FC);
2342 visitInstruction(FC);
2345 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2347 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2348 "Invalid extractelement operands!", &EI);
2349 visitInstruction(EI);
2352 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2353 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2355 "Invalid insertelement operands!", &IE);
2356 visitInstruction(IE);
2359 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2360 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2362 "Invalid shufflevector operands!", &SV);
2363 visitInstruction(SV);
2366 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2367 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2369 Assert(isa<PointerType>(TargetTy),
2370 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2371 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2372 "GEP into unsized type!", &GEP);
2373 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2374 GEP.getType()->isVectorTy(),
2375 "Vector GEP must return a vector value", &GEP);
2377 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2379 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2380 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2382 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2383 cast<PointerType>(GEP.getType()->getScalarType())
2384 ->getElementType() == ElTy,
2385 "GEP is not of right type for indices!", &GEP, ElTy);
2387 if (GEP.getPointerOperandType()->isVectorTy()) {
2388 // Additional checks for vector GEPs.
2389 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2390 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2391 "Vector GEP result width doesn't match operand's", &GEP);
2392 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2393 Type *IndexTy = Idxs[i]->getType();
2394 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2396 unsigned IndexWidth = IndexTy->getVectorNumElements();
2397 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2400 visitInstruction(GEP);
2403 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2404 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2407 void Verifier::visitRangeMetadata(Instruction& I,
2408 MDNode* Range, Type* Ty) {
2410 Range == I.getMetadata(LLVMContext::MD_range) &&
2411 "precondition violation");
2413 unsigned NumOperands = Range->getNumOperands();
2414 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2415 unsigned NumRanges = NumOperands / 2;
2416 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2418 ConstantRange LastRange(1); // Dummy initial value
2419 for (unsigned i = 0; i < NumRanges; ++i) {
2421 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2422 Assert(Low, "The lower limit must be an integer!", Low);
2424 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2425 Assert(High, "The upper limit must be an integer!", High);
2426 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2427 "Range types must match instruction type!", &I);
2429 APInt HighV = High->getValue();
2430 APInt LowV = Low->getValue();
2431 ConstantRange CurRange(LowV, HighV);
2432 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2433 "Range must not be empty!", Range);
2435 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2436 "Intervals are overlapping", Range);
2437 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2439 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2442 LastRange = ConstantRange(LowV, HighV);
2444 if (NumRanges > 2) {
2446 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2448 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2449 ConstantRange FirstRange(FirstLow, FirstHigh);
2450 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2451 "Intervals are overlapping", Range);
2452 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2457 void Verifier::visitLoadInst(LoadInst &LI) {
2458 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2459 Assert(PTy, "Load operand must be a pointer.", &LI);
2460 Type *ElTy = PTy->getElementType();
2461 Assert(ElTy == LI.getType(),
2462 "Load result type does not match pointer operand type!", &LI, ElTy);
2463 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2464 "huge alignment values are unsupported", &LI);
2465 if (LI.isAtomic()) {
2466 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2467 "Load cannot have Release ordering", &LI);
2468 Assert(LI.getAlignment() != 0,
2469 "Atomic load must specify explicit alignment", &LI);
2470 if (!ElTy->isPointerTy()) {
2471 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2473 unsigned Size = ElTy->getPrimitiveSizeInBits();
2474 Assert(Size >= 8 && !(Size & (Size - 1)),
2475 "atomic load operand must be power-of-two byte-sized integer", &LI,
2479 Assert(LI.getSynchScope() == CrossThread,
2480 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2483 visitInstruction(LI);
2486 void Verifier::visitStoreInst(StoreInst &SI) {
2487 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2488 Assert(PTy, "Store operand must be a pointer.", &SI);
2489 Type *ElTy = PTy->getElementType();
2490 Assert(ElTy == SI.getOperand(0)->getType(),
2491 "Stored value type does not match pointer operand type!", &SI, ElTy);
2492 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2493 "huge alignment values are unsupported", &SI);
2494 if (SI.isAtomic()) {
2495 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2496 "Store cannot have Acquire ordering", &SI);
2497 Assert(SI.getAlignment() != 0,
2498 "Atomic store must specify explicit alignment", &SI);
2499 if (!ElTy->isPointerTy()) {
2500 Assert(ElTy->isIntegerTy(),
2501 "atomic store operand must have integer type!", &SI, ElTy);
2502 unsigned Size = ElTy->getPrimitiveSizeInBits();
2503 Assert(Size >= 8 && !(Size & (Size - 1)),
2504 "atomic store operand must be power-of-two byte-sized integer",
2508 Assert(SI.getSynchScope() == CrossThread,
2509 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2511 visitInstruction(SI);
2514 void Verifier::visitAllocaInst(AllocaInst &AI) {
2515 SmallPtrSet<const Type*, 4> Visited;
2516 PointerType *PTy = AI.getType();
2517 Assert(PTy->getAddressSpace() == 0,
2518 "Allocation instruction pointer not in the generic address space!",
2520 Assert(PTy->getElementType()->isSized(&Visited),
2521 "Cannot allocate unsized type", &AI);
2522 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2523 "Alloca array size must have integer type", &AI);
2524 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2525 "huge alignment values are unsupported", &AI);
2527 visitInstruction(AI);
2530 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2532 // FIXME: more conditions???
2533 Assert(CXI.getSuccessOrdering() != NotAtomic,
2534 "cmpxchg instructions must be atomic.", &CXI);
2535 Assert(CXI.getFailureOrdering() != NotAtomic,
2536 "cmpxchg instructions must be atomic.", &CXI);
2537 Assert(CXI.getSuccessOrdering() != Unordered,
2538 "cmpxchg instructions cannot be unordered.", &CXI);
2539 Assert(CXI.getFailureOrdering() != Unordered,
2540 "cmpxchg instructions cannot be unordered.", &CXI);
2541 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2542 "cmpxchg instructions be at least as constrained on success as fail",
2544 Assert(CXI.getFailureOrdering() != Release &&
2545 CXI.getFailureOrdering() != AcquireRelease,
2546 "cmpxchg failure ordering cannot include release semantics", &CXI);
2548 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2549 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2550 Type *ElTy = PTy->getElementType();
2551 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2553 unsigned Size = ElTy->getPrimitiveSizeInBits();
2554 Assert(Size >= 8 && !(Size & (Size - 1)),
2555 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2556 Assert(ElTy == CXI.getOperand(1)->getType(),
2557 "Expected value type does not match pointer operand type!", &CXI,
2559 Assert(ElTy == CXI.getOperand(2)->getType(),
2560 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2561 visitInstruction(CXI);
2564 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2565 Assert(RMWI.getOrdering() != NotAtomic,
2566 "atomicrmw instructions must be atomic.", &RMWI);
2567 Assert(RMWI.getOrdering() != Unordered,
2568 "atomicrmw instructions cannot be unordered.", &RMWI);
2569 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2570 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2571 Type *ElTy = PTy->getElementType();
2572 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2574 unsigned Size = ElTy->getPrimitiveSizeInBits();
2575 Assert(Size >= 8 && !(Size & (Size - 1)),
2576 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2578 Assert(ElTy == RMWI.getOperand(1)->getType(),
2579 "Argument value type does not match pointer operand type!", &RMWI,
2581 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2582 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2583 "Invalid binary operation!", &RMWI);
2584 visitInstruction(RMWI);
2587 void Verifier::visitFenceInst(FenceInst &FI) {
2588 const AtomicOrdering Ordering = FI.getOrdering();
2589 Assert(Ordering == Acquire || Ordering == Release ||
2590 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2591 "fence instructions may only have "
2592 "acquire, release, acq_rel, or seq_cst ordering.",
2594 visitInstruction(FI);
2597 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2598 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2599 EVI.getIndices()) == EVI.getType(),
2600 "Invalid ExtractValueInst operands!", &EVI);
2602 visitInstruction(EVI);
2605 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2606 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2607 IVI.getIndices()) ==
2608 IVI.getOperand(1)->getType(),
2609 "Invalid InsertValueInst operands!", &IVI);
2611 visitInstruction(IVI);
2614 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2615 BasicBlock *BB = LPI.getParent();
2617 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2619 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2620 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2622 // The landingpad instruction defines its parent as a landing pad block. The
2623 // landing pad block may be branched to only by the unwind edge of an invoke.
2624 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2625 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2626 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2627 "Block containing LandingPadInst must be jumped to "
2628 "only by the unwind edge of an invoke.",
2632 // The landingpad instruction must be the first non-PHI instruction in the
2634 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2635 "LandingPadInst not the first non-PHI instruction in the block.",
2638 // The personality functions for all landingpad instructions within the same
2639 // function should match.
2641 Assert(LPI.getPersonalityFn() == PersonalityFn,
2642 "Personality function doesn't match others in function", &LPI);
2643 PersonalityFn = LPI.getPersonalityFn();
2645 // All operands must be constants.
2646 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2648 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2649 Constant *Clause = LPI.getClause(i);
2650 if (LPI.isCatch(i)) {
2651 Assert(isa<PointerType>(Clause->getType()),
2652 "Catch operand does not have pointer type!", &LPI);
2654 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2655 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2656 "Filter operand is not an array of constants!", &LPI);
2660 visitInstruction(LPI);
2663 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2664 Instruction *Op = cast<Instruction>(I.getOperand(i));
2665 // If the we have an invalid invoke, don't try to compute the dominance.
2666 // We already reject it in the invoke specific checks and the dominance
2667 // computation doesn't handle multiple edges.
2668 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2669 if (II->getNormalDest() == II->getUnwindDest())
2673 const Use &U = I.getOperandUse(i);
2674 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2675 "Instruction does not dominate all uses!", Op, &I);
2678 /// verifyInstruction - Verify that an instruction is well formed.
2680 void Verifier::visitInstruction(Instruction &I) {
2681 BasicBlock *BB = I.getParent();
2682 Assert(BB, "Instruction not embedded in basic block!", &I);
2684 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2685 for (User *U : I.users()) {
2686 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2687 "Only PHI nodes may reference their own value!", &I);
2691 // Check that void typed values don't have names
2692 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2693 "Instruction has a name, but provides a void value!", &I);
2695 // Check that the return value of the instruction is either void or a legal
2697 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2698 "Instruction returns a non-scalar type!", &I);
2700 // Check that the instruction doesn't produce metadata. Calls are already
2701 // checked against the callee type.
2702 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2703 "Invalid use of metadata!", &I);
2705 // Check that all uses of the instruction, if they are instructions
2706 // themselves, actually have parent basic blocks. If the use is not an
2707 // instruction, it is an error!
2708 for (Use &U : I.uses()) {
2709 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2710 Assert(Used->getParent() != nullptr,
2711 "Instruction referencing"
2712 " instruction not embedded in a basic block!",
2715 CheckFailed("Use of instruction is not an instruction!", U);
2720 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2721 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2723 // Check to make sure that only first-class-values are operands to
2725 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2726 Assert(0, "Instruction operands must be first-class values!", &I);
2729 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2730 // Check to make sure that the "address of" an intrinsic function is never
2733 !F->isIntrinsic() ||
2734 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2735 "Cannot take the address of an intrinsic!", &I);
2737 !F->isIntrinsic() || isa<CallInst>(I) ||
2738 F->getIntrinsicID() == Intrinsic::donothing ||
2739 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2740 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2741 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2742 "Cannot invoke an intrinsinc other than"
2743 " donothing or patchpoint",
2745 Assert(F->getParent() == M, "Referencing function in another module!",
2747 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2748 Assert(OpBB->getParent() == BB->getParent(),
2749 "Referring to a basic block in another function!", &I);
2750 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2751 Assert(OpArg->getParent() == BB->getParent(),
2752 "Referring to an argument in another function!", &I);
2753 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2754 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2755 } else if (isa<Instruction>(I.getOperand(i))) {
2756 verifyDominatesUse(I, i);
2757 } else if (isa<InlineAsm>(I.getOperand(i))) {
2758 Assert((i + 1 == e && isa<CallInst>(I)) ||
2759 (i + 3 == e && isa<InvokeInst>(I)),
2760 "Cannot take the address of an inline asm!", &I);
2761 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2762 if (CE->getType()->isPtrOrPtrVectorTy()) {
2763 // If we have a ConstantExpr pointer, we need to see if it came from an
2764 // illegal bitcast (inttoptr <constant int> )
2765 SmallVector<const ConstantExpr *, 4> Stack;
2766 SmallPtrSet<const ConstantExpr *, 4> Visited;
2767 Stack.push_back(CE);
2769 while (!Stack.empty()) {
2770 const ConstantExpr *V = Stack.pop_back_val();
2771 if (!Visited.insert(V).second)
2774 VerifyConstantExprBitcastType(V);
2776 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2777 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2778 Stack.push_back(Op);
2785 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2786 Assert(I.getType()->isFPOrFPVectorTy(),
2787 "fpmath requires a floating point result!", &I);
2788 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2789 if (ConstantFP *CFP0 =
2790 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2791 APFloat Accuracy = CFP0->getValueAPF();
2792 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2793 "fpmath accuracy not a positive number!", &I);
2795 Assert(false, "invalid fpmath accuracy!", &I);
2799 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2800 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2801 "Ranges are only for loads, calls and invokes!", &I);
2802 visitRangeMetadata(I, Range, I.getType());
2805 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2806 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2808 Assert(isa<LoadInst>(I),
2809 "nonnull applies only to load instructions, use attributes"
2810 " for calls or invokes",
2814 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2815 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2819 InstsInThisBlock.insert(&I);
2822 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2823 /// intrinsic argument or return value) matches the type constraints specified
2824 /// by the .td file (e.g. an "any integer" argument really is an integer).
2826 /// This return true on error but does not print a message.
2827 bool Verifier::VerifyIntrinsicType(Type *Ty,
2828 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2829 SmallVectorImpl<Type*> &ArgTys) {
2830 using namespace Intrinsic;
2832 // If we ran out of descriptors, there are too many arguments.
2833 if (Infos.empty()) return true;
2834 IITDescriptor D = Infos.front();
2835 Infos = Infos.slice(1);
2838 case IITDescriptor::Void: return !Ty->isVoidTy();
2839 case IITDescriptor::VarArg: return true;
2840 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2841 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2842 case IITDescriptor::Half: return !Ty->isHalfTy();
2843 case IITDescriptor::Float: return !Ty->isFloatTy();
2844 case IITDescriptor::Double: return !Ty->isDoubleTy();
2845 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2846 case IITDescriptor::Vector: {
2847 VectorType *VT = dyn_cast<VectorType>(Ty);
2848 return !VT || VT->getNumElements() != D.Vector_Width ||
2849 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2851 case IITDescriptor::Pointer: {
2852 PointerType *PT = dyn_cast<PointerType>(Ty);
2853 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2854 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2857 case IITDescriptor::Struct: {
2858 StructType *ST = dyn_cast<StructType>(Ty);
2859 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2862 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2863 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2868 case IITDescriptor::Argument:
2869 // Two cases here - If this is the second occurrence of an argument, verify
2870 // that the later instance matches the previous instance.
2871 if (D.getArgumentNumber() < ArgTys.size())
2872 return Ty != ArgTys[D.getArgumentNumber()];
2874 // Otherwise, if this is the first instance of an argument, record it and
2875 // verify the "Any" kind.
2876 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2877 ArgTys.push_back(Ty);
2879 switch (D.getArgumentKind()) {
2880 case IITDescriptor::AK_Any: return false; // Success
2881 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2882 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2883 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2884 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2886 llvm_unreachable("all argument kinds not covered");
2888 case IITDescriptor::ExtendArgument: {
2889 // This may only be used when referring to a previous vector argument.
2890 if (D.getArgumentNumber() >= ArgTys.size())
2893 Type *NewTy = ArgTys[D.getArgumentNumber()];
2894 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2895 NewTy = VectorType::getExtendedElementVectorType(VTy);
2896 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2897 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2903 case IITDescriptor::TruncArgument: {
2904 // This may only be used when referring to a previous vector argument.
2905 if (D.getArgumentNumber() >= ArgTys.size())
2908 Type *NewTy = ArgTys[D.getArgumentNumber()];
2909 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2910 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2911 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2912 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2918 case IITDescriptor::HalfVecArgument:
2919 // This may only be used when referring to a previous vector argument.
2920 return D.getArgumentNumber() >= ArgTys.size() ||
2921 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2922 VectorType::getHalfElementsVectorType(
2923 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2924 case IITDescriptor::SameVecWidthArgument: {
2925 if (D.getArgumentNumber() >= ArgTys.size())
2927 VectorType * ReferenceType =
2928 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2929 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2930 if (!ThisArgType || !ReferenceType ||
2931 (ReferenceType->getVectorNumElements() !=
2932 ThisArgType->getVectorNumElements()))
2934 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2937 case IITDescriptor::PtrToArgument: {
2938 if (D.getArgumentNumber() >= ArgTys.size())
2940 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2941 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2942 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2944 case IITDescriptor::VecOfPtrsToElt: {
2945 if (D.getArgumentNumber() >= ArgTys.size())
2947 VectorType * ReferenceType =
2948 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2949 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2950 if (!ThisArgVecTy || !ReferenceType ||
2951 (ReferenceType->getVectorNumElements() !=
2952 ThisArgVecTy->getVectorNumElements()))
2954 PointerType *ThisArgEltTy =
2955 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2958 return (!(ThisArgEltTy->getElementType() ==
2959 ReferenceType->getVectorElementType()));
2962 llvm_unreachable("unhandled");
2965 /// \brief Verify if the intrinsic has variable arguments.
2966 /// This method is intended to be called after all the fixed arguments have been
2969 /// This method returns true on error and does not print an error message.
2971 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2972 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2973 using namespace Intrinsic;
2975 // If there are no descriptors left, then it can't be a vararg.
2979 // There should be only one descriptor remaining at this point.
2980 if (Infos.size() != 1)
2983 // Check and verify the descriptor.
2984 IITDescriptor D = Infos.front();
2985 Infos = Infos.slice(1);
2986 if (D.Kind == IITDescriptor::VarArg)
2992 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2994 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2995 Function *IF = CI.getCalledFunction();
2996 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2999 // Verify that the intrinsic prototype lines up with what the .td files
3001 FunctionType *IFTy = IF->getFunctionType();
3002 bool IsVarArg = IFTy->isVarArg();
3004 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3005 getIntrinsicInfoTableEntries(ID, Table);
3006 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3008 SmallVector<Type *, 4> ArgTys;
3009 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3010 "Intrinsic has incorrect return type!", IF);
3011 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3012 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3013 "Intrinsic has incorrect argument type!", IF);
3015 // Verify if the intrinsic call matches the vararg property.
3017 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3018 "Intrinsic was not defined with variable arguments!", IF);
3020 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3021 "Callsite was not defined with variable arguments!", IF);
3023 // All descriptors should be absorbed by now.
3024 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3026 // Now that we have the intrinsic ID and the actual argument types (and we
3027 // know they are legal for the intrinsic!) get the intrinsic name through the
3028 // usual means. This allows us to verify the mangling of argument types into
3030 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3031 Assert(ExpectedName == IF->getName(),
3032 "Intrinsic name not mangled correctly for type arguments! "
3037 // If the intrinsic takes MDNode arguments, verify that they are either global
3038 // or are local to *this* function.
3039 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3040 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3041 visitMetadataAsValue(*MD, CI.getParent()->getParent());
3046 case Intrinsic::ctlz: // llvm.ctlz
3047 case Intrinsic::cttz: // llvm.cttz
3048 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3049 "is_zero_undef argument of bit counting intrinsics must be a "
3053 case Intrinsic::dbg_declare: // llvm.dbg.declare
3054 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3055 "invalid llvm.dbg.declare intrinsic call 1", &CI);
3056 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
3058 case Intrinsic::dbg_value: // llvm.dbg.value
3059 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
3061 case Intrinsic::memcpy:
3062 case Intrinsic::memmove:
3063 case Intrinsic::memset: {
3064 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3066 "alignment argument of memory intrinsics must be a constant int",
3068 const APInt &AlignVal = AlignCI->getValue();
3069 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3070 "alignment argument of memory intrinsics must be a power of 2", &CI);
3071 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3072 "isvolatile argument of memory intrinsics must be a constant int",
3076 case Intrinsic::gcroot:
3077 case Intrinsic::gcwrite:
3078 case Intrinsic::gcread:
3079 if (ID == Intrinsic::gcroot) {
3081 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3082 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3083 Assert(isa<Constant>(CI.getArgOperand(1)),
3084 "llvm.gcroot parameter #2 must be a constant.", &CI);
3085 if (!AI->getType()->getElementType()->isPointerTy()) {
3086 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3087 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3088 "or argument #2 must be a non-null constant.",
3093 Assert(CI.getParent()->getParent()->hasGC(),
3094 "Enclosing function does not use GC.", &CI);
3096 case Intrinsic::init_trampoline:
3097 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3098 "llvm.init_trampoline parameter #2 must resolve to a function.",
3101 case Intrinsic::prefetch:
3102 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3103 isa<ConstantInt>(CI.getArgOperand(2)) &&
3104 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3105 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3106 "invalid arguments to llvm.prefetch", &CI);
3108 case Intrinsic::stackprotector:
3109 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3110 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3112 case Intrinsic::lifetime_start:
3113 case Intrinsic::lifetime_end:
3114 case Intrinsic::invariant_start:
3115 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3116 "size argument of memory use markers must be a constant integer",
3119 case Intrinsic::invariant_end:
3120 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3121 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3124 case Intrinsic::frameescape: {
3125 BasicBlock *BB = CI.getParent();
3126 Assert(BB == &BB->getParent()->front(),
3127 "llvm.frameescape used outside of entry block", &CI);
3128 Assert(!SawFrameEscape,
3129 "multiple calls to llvm.frameescape in one function", &CI);
3130 for (Value *Arg : CI.arg_operands()) {
3131 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3132 Assert(AI && AI->isStaticAlloca(),
3133 "llvm.frameescape only accepts static allocas", &CI);
3135 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3136 SawFrameEscape = true;
3139 case Intrinsic::framerecover: {
3140 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3141 Function *Fn = dyn_cast<Function>(FnArg);
3142 Assert(Fn && !Fn->isDeclaration(),
3143 "llvm.framerecover first "
3144 "argument must be function defined in this module",
3146 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3147 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3149 auto &Entry = FrameEscapeInfo[Fn];
3150 Entry.second = unsigned(
3151 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3155 case Intrinsic::eh_parentframe: {
3156 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3157 Assert(AI && AI->isStaticAlloca(),
3158 "llvm.eh.parentframe requires a static alloca", &CI);
3162 case Intrinsic::eh_unwindhelp: {
3163 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3164 Assert(AI && AI->isStaticAlloca(),
3165 "llvm.eh.unwindhelp requires a static alloca", &CI);
3169 case Intrinsic::experimental_gc_statepoint:
3170 Assert(!CI.isInlineAsm(),
3171 "gc.statepoint support for inline assembly unimplemented", &CI);
3172 Assert(CI.getParent()->getParent()->hasGC(),
3173 "Enclosing function does not use GC.", &CI);
3175 VerifyStatepoint(ImmutableCallSite(&CI));
3177 case Intrinsic::experimental_gc_result_int:
3178 case Intrinsic::experimental_gc_result_float:
3179 case Intrinsic::experimental_gc_result_ptr:
3180 case Intrinsic::experimental_gc_result: {
3181 Assert(CI.getParent()->getParent()->hasGC(),
3182 "Enclosing function does not use GC.", &CI);
3183 // Are we tied to a statepoint properly?
3184 CallSite StatepointCS(CI.getArgOperand(0));
3185 const Function *StatepointFn =
3186 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3187 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3188 StatepointFn->getIntrinsicID() ==
3189 Intrinsic::experimental_gc_statepoint,
3190 "gc.result operand #1 must be from a statepoint", &CI,
3191 CI.getArgOperand(0));
3193 // Assert that result type matches wrapped callee.
3194 const Value *Target = StatepointCS.getArgument(0);
3195 const PointerType *PT = cast<PointerType>(Target->getType());
3196 const FunctionType *TargetFuncType =
3197 cast<FunctionType>(PT->getElementType());
3198 Assert(CI.getType() == TargetFuncType->getReturnType(),
3199 "gc.result result type does not match wrapped callee", &CI);
3202 case Intrinsic::experimental_gc_relocate: {
3203 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3205 // Check that this relocate is correctly tied to the statepoint
3207 // This is case for relocate on the unwinding path of an invoke statepoint
3208 if (ExtractValueInst *ExtractValue =
3209 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3210 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3211 "gc relocate on unwind path incorrectly linked to the statepoint",
3214 const BasicBlock *invokeBB =
3215 ExtractValue->getParent()->getUniquePredecessor();
3217 // Landingpad relocates should have only one predecessor with invoke
3218 // statepoint terminator
3219 Assert(invokeBB, "safepoints should have unique landingpads",
3220 ExtractValue->getParent());
3221 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3223 Assert(isStatepoint(invokeBB->getTerminator()),
3224 "gc relocate should be linked to a statepoint", invokeBB);
3227 // In all other cases relocate should be tied to the statepoint directly.
3228 // This covers relocates on a normal return path of invoke statepoint and
3229 // relocates of a call statepoint
3230 auto Token = CI.getArgOperand(0);
3231 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3232 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3235 // Verify rest of the relocate arguments
3237 GCRelocateOperands ops(&CI);
3238 ImmutableCallSite StatepointCS(ops.statepoint());
3240 // Both the base and derived must be piped through the safepoint
3241 Value* Base = CI.getArgOperand(1);
3242 Assert(isa<ConstantInt>(Base),
3243 "gc.relocate operand #2 must be integer offset", &CI);
3245 Value* Derived = CI.getArgOperand(2);
3246 Assert(isa<ConstantInt>(Derived),
3247 "gc.relocate operand #3 must be integer offset", &CI);
3249 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3250 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3252 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3253 "gc.relocate: statepoint base index out of bounds", &CI);
3254 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3255 "gc.relocate: statepoint derived index out of bounds", &CI);
3257 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3258 // section of the statepoint's argument
3259 Assert(StatepointCS.arg_size() > 0,
3260 "gc.statepoint: insufficient arguments");
3261 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3262 "gc.statement: number of call arguments must be constant integer");
3263 const unsigned NumCallArgs =
3264 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3265 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3266 "gc.statepoint: mismatch in number of call arguments");
3267 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3268 "gc.statepoint: number of deoptimization arguments must be "
3269 "a constant integer");
3270 const int NumDeoptArgs =
3271 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3272 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3273 const int GCParamArgsEnd = StatepointCS.arg_size();
3274 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3275 "gc.relocate: statepoint base index doesn't fall within the "
3276 "'gc parameters' section of the statepoint call",
3278 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3279 "gc.relocate: statepoint derived index doesn't fall within the "
3280 "'gc parameters' section of the statepoint call",
3283 // Assert that the result type matches the type of the relocated pointer
3284 GCRelocateOperands Operands(&CI);
3285 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3286 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3292 template <class DbgIntrinsicTy>
3293 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3294 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3295 Assert(isa<ValueAsMetadata>(MD) ||
3296 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3297 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3298 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3299 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3300 DII.getRawVariable());
3301 Assert(isa<MDExpression>(DII.getRawExpression()),
3302 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3303 DII.getRawExpression());
3306 void Verifier::verifyDebugInfo() {
3307 // Run the debug info verifier only if the regular verifier succeeds, since
3308 // sometimes checks that have already failed will cause crashes here.
3309 if (EverBroken || !VerifyDebugInfo)
3312 DebugInfoFinder Finder;
3313 Finder.processModule(*M);
3314 processInstructions(Finder);
3316 // Verify Debug Info.
3318 // NOTE: The loud braces are necessary for MSVC compatibility.
3319 for (DICompileUnit CU : Finder.compile_units()) {
3320 Assert(CU.Verify(), "DICompileUnit does not Verify!", CU);
3322 for (DISubprogram S : Finder.subprograms()) {
3323 Assert(S.Verify(), "DISubprogram does not Verify!", S);
3325 for (DIGlobalVariable GV : Finder.global_variables()) {
3326 Assert(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3328 for (DIType T : Finder.types()) {
3329 Assert(T.Verify(), "DIType does not Verify!", T);
3331 for (DIScope S : Finder.scopes()) {
3332 Assert(S.Verify(), "DIScope does not Verify!", S);
3336 void Verifier::processInstructions(DebugInfoFinder &Finder) {
3337 for (const Function &F : *M)
3338 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3339 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3340 Finder.processLocation(*M, DILocation(MD));
3341 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3342 processCallInst(Finder, *CI);
3346 void Verifier::processCallInst(DebugInfoFinder &Finder, const CallInst &CI) {
3347 if (Function *F = CI.getCalledFunction())
3348 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3350 case Intrinsic::dbg_declare:
3351 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
3353 case Intrinsic::dbg_value:
3354 Finder.processValue(*M, cast<DbgValueInst>(&CI));
3361 //===----------------------------------------------------------------------===//
3362 // Implement the public interfaces to this file...
3363 //===----------------------------------------------------------------------===//
3365 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3366 Function &F = const_cast<Function &>(f);
3367 assert(!F.isDeclaration() && "Cannot verify external functions");
3369 raw_null_ostream NullStr;
3370 Verifier V(OS ? *OS : NullStr);
3372 // Note that this function's return value is inverted from what you would
3373 // expect of a function called "verify".
3374 return !V.verify(F);
3377 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3378 raw_null_ostream NullStr;
3379 Verifier V(OS ? *OS : NullStr);
3381 bool Broken = false;
3382 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3383 if (!I->isDeclaration() && !I->isMaterializable())
3384 Broken |= !V.verify(*I);
3386 // Note that this function's return value is inverted from what you would
3387 // expect of a function called "verify".
3388 return !V.verify(M) || Broken;
3392 struct VerifierLegacyPass : public FunctionPass {
3398 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3399 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3401 explicit VerifierLegacyPass(bool FatalErrors)
3402 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3403 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3406 bool runOnFunction(Function &F) override {
3407 if (!V.verify(F) && FatalErrors)
3408 report_fatal_error("Broken function found, compilation aborted!");
3413 bool doFinalization(Module &M) override {
3414 if (!V.verify(M) && FatalErrors)
3415 report_fatal_error("Broken module found, compilation aborted!");
3420 void getAnalysisUsage(AnalysisUsage &AU) const override {
3421 AU.setPreservesAll();
3426 char VerifierLegacyPass::ID = 0;
3427 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3429 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3430 return new VerifierLegacyPass(FatalErrors);
3433 PreservedAnalyses VerifierPass::run(Module &M) {
3434 if (verifyModule(M, &dbgs()) && FatalErrors)
3435 report_fatal_error("Broken module found, compilation aborted!");
3437 return PreservedAnalyses::all();
3440 PreservedAnalyses VerifierPass::run(Function &F) {
3441 if (verifyFunction(F, &dbgs()) && FatalErrors)
3442 report_fatal_error("Broken function found, compilation aborted!");
3444 return PreservedAnalyses::all();