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/Analysis/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/Analysis/Dominators.h"
55 #include "llvm/Assembly/Writer.h"
56 #include "llvm/DebugInfo.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/InstVisitor.h"
67 #include "llvm/Pass.h"
68 #include "llvm/PassManager.h"
69 #include "llvm/Support/CFG.h"
70 #include "llvm/Support/CallSite.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
80 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
83 namespace { // Anonymous namespace for class
84 struct PreVerifier : public FunctionPass {
85 static char ID; // Pass ID, replacement for typeid
87 PreVerifier() : FunctionPass(ID) {
88 initializePreVerifierPass(*PassRegistry::getPassRegistry());
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 // Check that the prerequisites for successful DominatorTree construction
97 bool runOnFunction(Function &F) {
100 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
101 if (I->empty() || !I->back().isTerminator()) {
102 dbgs() << "Basic Block in function '" << F.getName()
103 << "' does not have terminator!\n";
104 WriteAsOperand(dbgs(), I, true);
111 report_fatal_error("Broken module, no Basic Block terminator!");
118 char PreVerifier::ID = 0;
119 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
121 static char &PreVerifyID = PreVerifier::ID;
124 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
125 static char ID; // Pass ID, replacement for typeid
126 bool Broken; // Is this module found to be broken?
127 VerifierFailureAction action;
128 // What to do if verification fails.
129 Module *Mod; // Module we are verifying right now
130 LLVMContext *Context; // Context within which we are verifying
131 DominatorTree *DT; // Dominator Tree, caution can be null!
132 const DataLayout *DL;
134 std::string Messages;
135 raw_string_ostream MessagesStr;
137 /// InstInThisBlock - when verifying a basic block, keep track of all of the
138 /// instructions we have seen so far. This allows us to do efficient
139 /// dominance checks for the case when an instruction has an operand that is
140 /// an instruction in the same block.
141 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
143 /// MDNodes - keep track of the metadata nodes that have been checked
145 SmallPtrSet<MDNode *, 32> MDNodes;
147 /// PersonalityFn - The personality function referenced by the
148 /// LandingPadInsts. All LandingPadInsts within the same function must use
149 /// the same personality function.
150 const Value *PersonalityFn;
152 /// Finder keeps track of all debug info MDNodes in a Module.
153 DebugInfoFinder Finder;
156 : FunctionPass(ID), Broken(false),
157 action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0),
158 MessagesStr(Messages), PersonalityFn(0) {
159 initializeVerifierPass(*PassRegistry::getPassRegistry());
161 explicit Verifier(VerifierFailureAction ctn)
162 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
163 Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) {
164 initializeVerifierPass(*PassRegistry::getPassRegistry());
167 bool doInitialization(Module &M) {
169 Context = &M.getContext();
172 DL = getAnalysisIfAvailable<DataLayout>();
173 if (!DisableDebugInfoVerifier)
174 Finder.processModule(M);
176 // We must abort before returning back to the pass manager, or else the
177 // pass manager may try to run other passes on the broken module.
178 return abortIfBroken();
181 bool runOnFunction(Function &F) {
182 // Get dominator information if we are being run by PassManager
183 DT = &getAnalysis<DominatorTree>();
186 if (!Context) Context = &F.getContext();
189 InstsInThisBlock.clear();
192 // We must abort before returning back to the pass manager, or else the
193 // pass manager may try to run other passes on the broken module.
194 return abortIfBroken();
197 bool doFinalization(Module &M) {
198 // Scan through, checking all of the external function's linkage now...
199 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
200 visitGlobalValue(*I);
202 // Check to make sure function prototypes are okay.
203 if (I->isDeclaration()) visitFunction(*I);
206 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
208 visitGlobalVariable(*I);
210 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
212 visitGlobalAlias(*I);
214 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
215 E = M.named_metadata_end(); I != E; ++I)
216 visitNamedMDNode(*I);
219 visitModuleIdents(M);
221 // Verify Debug Info.
224 // If the module is broken, abort at this time.
225 return abortIfBroken();
228 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
229 AU.setPreservesAll();
230 AU.addRequiredID(PreVerifyID);
231 AU.addRequired<DominatorTree>();
234 /// abortIfBroken - If the module is broken and we are supposed to abort on
235 /// this condition, do so.
237 bool abortIfBroken() {
238 if (!Broken) return false;
239 MessagesStr << "Broken module found, ";
241 case AbortProcessAction:
242 MessagesStr << "compilation aborted!\n";
243 dbgs() << MessagesStr.str();
244 // Client should choose different reaction if abort is not desired
246 case PrintMessageAction:
247 MessagesStr << "verification continues.\n";
248 dbgs() << MessagesStr.str();
250 case ReturnStatusAction:
251 MessagesStr << "compilation terminated.\n";
254 llvm_unreachable("Invalid action");
258 // Verification methods...
259 void visitGlobalValue(GlobalValue &GV);
260 void visitGlobalVariable(GlobalVariable &GV);
261 void visitGlobalAlias(GlobalAlias &GA);
262 void visitNamedMDNode(NamedMDNode &NMD);
263 void visitMDNode(MDNode &MD, Function *F);
264 void visitModuleIdents(Module &M);
265 void visitModuleFlags(Module &M);
266 void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
267 SmallVectorImpl<MDNode*> &Requirements);
268 void visitFunction(Function &F);
269 void visitBasicBlock(BasicBlock &BB);
270 using InstVisitor<Verifier>::visit;
272 void visit(Instruction &I);
274 void visitTruncInst(TruncInst &I);
275 void visitZExtInst(ZExtInst &I);
276 void visitSExtInst(SExtInst &I);
277 void visitFPTruncInst(FPTruncInst &I);
278 void visitFPExtInst(FPExtInst &I);
279 void visitFPToUIInst(FPToUIInst &I);
280 void visitFPToSIInst(FPToSIInst &I);
281 void visitUIToFPInst(UIToFPInst &I);
282 void visitSIToFPInst(SIToFPInst &I);
283 void visitIntToPtrInst(IntToPtrInst &I);
284 void visitPtrToIntInst(PtrToIntInst &I);
285 void visitBitCastInst(BitCastInst &I);
286 void visitPHINode(PHINode &PN);
287 void visitBinaryOperator(BinaryOperator &B);
288 void visitICmpInst(ICmpInst &IC);
289 void visitFCmpInst(FCmpInst &FC);
290 void visitExtractElementInst(ExtractElementInst &EI);
291 void visitInsertElementInst(InsertElementInst &EI);
292 void visitShuffleVectorInst(ShuffleVectorInst &EI);
293 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
294 void visitCallInst(CallInst &CI);
295 void visitInvokeInst(InvokeInst &II);
296 void visitGetElementPtrInst(GetElementPtrInst &GEP);
297 void visitLoadInst(LoadInst &LI);
298 void visitStoreInst(StoreInst &SI);
299 void verifyDominatesUse(Instruction &I, unsigned i);
300 void visitInstruction(Instruction &I);
301 void visitTerminatorInst(TerminatorInst &I);
302 void visitBranchInst(BranchInst &BI);
303 void visitReturnInst(ReturnInst &RI);
304 void visitSwitchInst(SwitchInst &SI);
305 void visitIndirectBrInst(IndirectBrInst &BI);
306 void visitSelectInst(SelectInst &SI);
307 void visitUserOp1(Instruction &I);
308 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
309 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
310 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
311 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
312 void visitFenceInst(FenceInst &FI);
313 void visitAllocaInst(AllocaInst &AI);
314 void visitExtractValueInst(ExtractValueInst &EVI);
315 void visitInsertValueInst(InsertValueInst &IVI);
316 void visitLandingPadInst(LandingPadInst &LPI);
318 void VerifyCallSite(CallSite CS);
319 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
320 int VT, unsigned ArgNo, std::string &Suffix);
321 bool VerifyIntrinsicType(Type *Ty,
322 ArrayRef<Intrinsic::IITDescriptor> &Infos,
323 SmallVectorImpl<Type*> &ArgTys);
324 bool VerifyIntrinsicIsVarArg(bool isVarArg,
325 ArrayRef<Intrinsic::IITDescriptor> &Infos);
326 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
327 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
328 bool isFunction, const Value *V);
329 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
330 bool isReturnValue, const Value *V);
331 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
334 void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
335 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
337 void verifyDebugInfo(Module &M);
339 void WriteValue(const Value *V) {
341 if (isa<Instruction>(V)) {
342 MessagesStr << *V << '\n';
344 WriteAsOperand(MessagesStr, V, true, Mod);
349 void WriteType(Type *T) {
351 MessagesStr << ' ' << *T;
355 // CheckFailed - A check failed, so print out the condition and the message
356 // that failed. This provides a nice place to put a breakpoint if you want
357 // to see why something is not correct.
358 void CheckFailed(const Twine &Message,
359 const Value *V1 = 0, const Value *V2 = 0,
360 const Value *V3 = 0, const Value *V4 = 0) {
361 MessagesStr << Message.str() << "\n";
369 void CheckFailed(const Twine &Message, const Value *V1,
370 Type *T2, const Value *V3 = 0) {
371 MessagesStr << Message.str() << "\n";
378 void CheckFailed(const Twine &Message, Type *T1,
379 Type *T2 = 0, Type *T3 = 0) {
380 MessagesStr << Message.str() << "\n";
387 } // End anonymous namespace
389 char Verifier::ID = 0;
390 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
391 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
392 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
393 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
395 // Assert - We know that cond should be true, if not print an error message.
396 #define Assert(C, M) \
397 do { if (!(C)) { CheckFailed(M); return; } } while (0)
398 #define Assert1(C, M, V1) \
399 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
400 #define Assert2(C, M, V1, V2) \
401 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
402 #define Assert3(C, M, V1, V2, V3) \
403 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
404 #define Assert4(C, M, V1, V2, V3, V4) \
405 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
407 void Verifier::visit(Instruction &I) {
408 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
409 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
410 InstVisitor<Verifier>::visit(I);
414 void Verifier::visitGlobalValue(GlobalValue &GV) {
415 Assert1(!GV.isDeclaration() ||
416 GV.isMaterializable() ||
417 GV.hasExternalLinkage() ||
418 GV.hasDLLImportLinkage() ||
419 GV.hasExternalWeakLinkage() ||
420 (isa<GlobalAlias>(GV) &&
421 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
422 "Global is external, but doesn't have external or dllimport or weak linkage!",
425 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
426 "Global is marked as dllimport, but not external", &GV);
428 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
429 "Only global variables can have appending linkage!", &GV);
431 if (GV.hasAppendingLinkage()) {
432 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
433 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
434 "Only global arrays can have appending linkage!", GVar);
437 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
438 "linkonce_odr_auto_hide can only have default visibility!",
442 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
443 if (GV.hasInitializer()) {
444 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
445 "Global variable initializer type does not match global "
446 "variable type!", &GV);
448 // If the global has common linkage, it must have a zero initializer and
449 // cannot be constant.
450 if (GV.hasCommonLinkage()) {
451 Assert1(GV.getInitializer()->isNullValue(),
452 "'common' global must have a zero initializer!", &GV);
453 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
457 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
458 GV.hasExternalWeakLinkage(),
459 "invalid linkage type for global declaration", &GV);
462 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
463 GV.getName() == "llvm.global_dtors")) {
464 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
465 "invalid linkage for intrinsic global variable", &GV);
466 // Don't worry about emitting an error for it not being an array,
467 // visitGlobalValue will complain on appending non-array.
468 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
469 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
470 PointerType *FuncPtrTy =
471 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
472 Assert1(STy && STy->getNumElements() == 2 &&
473 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
474 STy->getTypeAtIndex(1) == FuncPtrTy,
475 "wrong type for intrinsic global variable", &GV);
479 if (GV.hasName() && (GV.getName() == "llvm.used" ||
480 GV.getName() == "llvm.compiler.used")) {
481 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
482 "invalid linkage for intrinsic global variable", &GV);
483 Type *GVType = GV.getType()->getElementType();
484 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
485 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
486 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
487 if (GV.hasInitializer()) {
488 Constant *Init = GV.getInitializer();
489 ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
490 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
492 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
493 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
495 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
496 "invalid llvm.used member", V);
497 Assert1(V->hasName(), "members of llvm.used must be named", V);
503 if (!GV.hasInitializer()) {
504 visitGlobalValue(GV);
508 // Walk any aggregate initializers looking for bitcasts between address spaces
509 SmallPtrSet<const Value *, 4> Visited;
510 SmallVector<const Value *, 4> WorkStack;
511 WorkStack.push_back(cast<Value>(GV.getInitializer()));
513 while (!WorkStack.empty()) {
514 const Value *V = WorkStack.pop_back_val();
515 if (!Visited.insert(V))
518 if (const User *U = dyn_cast<User>(V)) {
519 for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
520 WorkStack.push_back(U->getOperand(I));
523 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
524 VerifyConstantExprBitcastType(CE);
530 visitGlobalValue(GV);
533 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
534 Assert1(!GA.getName().empty(),
535 "Alias name cannot be empty!", &GA);
536 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
537 "Alias should have external or external weak linkage!", &GA);
538 Assert1(GA.getAliasee(),
539 "Aliasee cannot be NULL!", &GA);
540 Assert1(GA.getType() == GA.getAliasee()->getType(),
541 "Alias and aliasee types should match!", &GA);
542 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
544 Constant *Aliasee = GA.getAliasee();
546 if (!isa<GlobalValue>(Aliasee)) {
547 ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
549 (CE->getOpcode() == Instruction::BitCast ||
550 CE->getOpcode() == Instruction::GetElementPtr) &&
551 isa<GlobalValue>(CE->getOperand(0)),
552 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
555 if (CE->getOpcode() == Instruction::BitCast) {
556 unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
557 unsigned DstAS = CE->getType()->getPointerAddressSpace();
559 Assert1(SrcAS == DstAS,
560 "Alias bitcasts cannot be between different address spaces",
565 const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
567 "Aliasing chain should end with function or global variable", &GA);
569 visitGlobalValue(GA);
572 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
573 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
574 MDNode *MD = NMD.getOperand(i);
578 Assert1(!MD->isFunctionLocal(),
579 "Named metadata operand cannot be function local!", MD);
584 void Verifier::visitMDNode(MDNode &MD, Function *F) {
585 // Only visit each node once. Metadata can be mutually recursive, so this
586 // avoids infinite recursion here, as well as being an optimization.
587 if (!MDNodes.insert(&MD))
590 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
591 Value *Op = MD.getOperand(i);
594 if (isa<Constant>(Op) || isa<MDString>(Op))
596 if (MDNode *N = dyn_cast<MDNode>(Op)) {
597 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
598 "Global metadata operand cannot be function local!", &MD, N);
602 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
604 // If this was an instruction, bb, or argument, verify that it is in the
605 // function that we expect.
606 Function *ActualF = 0;
607 if (Instruction *I = dyn_cast<Instruction>(Op))
608 ActualF = I->getParent()->getParent();
609 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
610 ActualF = BB->getParent();
611 else if (Argument *A = dyn_cast<Argument>(Op))
612 ActualF = A->getParent();
613 assert(ActualF && "Unimplemented function local metadata case!");
615 Assert2(ActualF == F, "function-local metadata used in wrong function",
620 void Verifier::visitModuleIdents(Module &M) {
621 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
625 // llvm.ident takes a list of metadata entry. Each entry has only one string.
626 // Scan each llvm.ident entry and make sure that this requirement is met.
627 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
628 const MDNode *N = Idents->getOperand(i);
629 Assert1(N->getNumOperands() == 1,
630 "incorrect number of operands in llvm.ident metadata", N);
631 Assert1(isa<MDString>(N->getOperand(0)),
632 ("invalid value for llvm.ident metadata entry operand"
633 "(the operand should be a string)"),
638 void Verifier::visitModuleFlags(Module &M) {
639 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
642 // Scan each flag, and track the flags and requirements.
643 DenseMap<MDString*, MDNode*> SeenIDs;
644 SmallVector<MDNode*, 16> Requirements;
645 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
646 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
649 // Validate that the requirements in the module are valid.
650 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
651 MDNode *Requirement = Requirements[I];
652 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
653 Value *ReqValue = Requirement->getOperand(1);
655 MDNode *Op = SeenIDs.lookup(Flag);
657 CheckFailed("invalid requirement on flag, flag is not present in module",
662 if (Op->getOperand(2) != ReqValue) {
663 CheckFailed(("invalid requirement on flag, "
664 "flag does not have the required value"),
671 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
672 SmallVectorImpl<MDNode*> &Requirements) {
673 // Each module flag should have three arguments, the merge behavior (a
674 // constant int), the flag ID (an MDString), and the value.
675 Assert1(Op->getNumOperands() == 3,
676 "incorrect number of operands in module flag", Op);
677 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
678 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
680 "invalid behavior operand in module flag (expected constant integer)",
682 unsigned BehaviorValue = Behavior->getZExtValue();
684 "invalid ID operand in module flag (expected metadata string)",
687 // Sanity check the values for behaviors with additional requirements.
688 switch (BehaviorValue) {
691 "invalid behavior operand in module flag (unexpected constant)",
696 case Module::Warning:
697 case Module::Override:
698 // These behavior types accept any value.
701 case Module::Require: {
702 // The value should itself be an MDNode with two operands, a flag ID (an
703 // MDString), and a value.
704 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
705 Assert1(Value && Value->getNumOperands() == 2,
706 "invalid value for 'require' module flag (expected metadata pair)",
708 Assert1(isa<MDString>(Value->getOperand(0)),
709 ("invalid value for 'require' module flag "
710 "(first value operand should be a string)"),
711 Value->getOperand(0));
713 // Append it to the list of requirements, to check once all module flags are
715 Requirements.push_back(Value);
720 case Module::AppendUnique: {
721 // These behavior types require the operand be an MDNode.
722 Assert1(isa<MDNode>(Op->getOperand(2)),
723 "invalid value for 'append'-type module flag "
724 "(expected a metadata node)", Op->getOperand(2));
729 // Unless this is a "requires" flag, check the ID is unique.
730 if (BehaviorValue != Module::Require) {
731 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
733 "module flag identifiers must be unique (or of 'require' type)",
738 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
739 bool isFunction, const Value *V) {
741 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
742 if (Attrs.getSlotIndex(I) == Idx) {
747 assert(Slot != ~0U && "Attribute set inconsistency!");
749 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
751 if (I->isStringAttribute())
754 if (I->getKindAsEnum() == Attribute::NoReturn ||
755 I->getKindAsEnum() == Attribute::NoUnwind ||
756 I->getKindAsEnum() == Attribute::NoInline ||
757 I->getKindAsEnum() == Attribute::AlwaysInline ||
758 I->getKindAsEnum() == Attribute::OptimizeForSize ||
759 I->getKindAsEnum() == Attribute::StackProtect ||
760 I->getKindAsEnum() == Attribute::StackProtectReq ||
761 I->getKindAsEnum() == Attribute::StackProtectStrong ||
762 I->getKindAsEnum() == Attribute::NoRedZone ||
763 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
764 I->getKindAsEnum() == Attribute::Naked ||
765 I->getKindAsEnum() == Attribute::InlineHint ||
766 I->getKindAsEnum() == Attribute::StackAlignment ||
767 I->getKindAsEnum() == Attribute::UWTable ||
768 I->getKindAsEnum() == Attribute::NonLazyBind ||
769 I->getKindAsEnum() == Attribute::ReturnsTwice ||
770 I->getKindAsEnum() == Attribute::SanitizeAddress ||
771 I->getKindAsEnum() == Attribute::SanitizeThread ||
772 I->getKindAsEnum() == Attribute::SanitizeMemory ||
773 I->getKindAsEnum() == Attribute::MinSize ||
774 I->getKindAsEnum() == Attribute::NoDuplicate ||
775 I->getKindAsEnum() == Attribute::Builtin ||
776 I->getKindAsEnum() == Attribute::NoBuiltin ||
777 I->getKindAsEnum() == Attribute::Cold ||
778 I->getKindAsEnum() == Attribute::OptimizeNone) {
780 CheckFailed("Attribute '" + I->getAsString() +
781 "' only applies to functions!", V);
784 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
785 I->getKindAsEnum() == Attribute::ReadNone) {
787 CheckFailed("Attribute '" + I->getAsString() +
788 "' does not apply to function returns");
791 } else if (isFunction) {
792 CheckFailed("Attribute '" + I->getAsString() +
793 "' does not apply to functions!", V);
799 // VerifyParameterAttrs - Check the given attributes for an argument or return
800 // value of the specified type. The value V is printed in error messages.
801 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
802 bool isReturnValue, const Value *V) {
803 if (!Attrs.hasAttributes(Idx))
806 VerifyAttributeTypes(Attrs, Idx, false, V);
809 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
810 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
811 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
812 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
813 !Attrs.hasAttribute(Idx, Attribute::Returned),
814 "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
815 "do not apply to return values!", V);
817 // Check for mutually incompatible attributes.
818 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
819 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
820 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
821 Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
822 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
823 Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
824 "'byval, nest, and sret' are incompatible!", V);
826 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
827 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
828 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
829 Attrs.hasAttribute(Idx, Attribute::InReg)) ||
830 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
831 Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
832 "'byval, nest, and inreg' are incompatible!", V);
834 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
835 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
836 "'sret and returned' are incompatible!", V);
838 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
839 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
840 "'zeroext and signext' are incompatible!", V);
842 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
843 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
844 "'readnone and readonly' are incompatible!", V);
846 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
847 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
848 "'noinline and alwaysinline' are incompatible!", V);
850 Assert1(!AttrBuilder(Attrs, Idx).
851 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
852 "Wrong types for attribute: " +
853 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
855 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
856 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
857 PTy->getElementType()->isSized(),
858 "Attribute 'byval' does not support unsized types!", V);
860 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
861 "Attribute 'byval' only applies to parameters with pointer type!",
865 // VerifyFunctionAttrs - Check parameter attributes against a function type.
866 // The value V is printed in error messages.
867 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
872 bool SawNest = false;
873 bool SawReturned = false;
875 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
876 unsigned Idx = Attrs.getSlotIndex(i);
880 Ty = FT->getReturnType();
881 else if (Idx-1 < FT->getNumParams())
882 Ty = FT->getParamType(Idx-1);
884 break; // VarArgs attributes, verified elsewhere.
886 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
891 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
892 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
896 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
897 Assert1(!SawReturned, "More than one parameter has attribute returned!",
899 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
900 "argument and return types for 'returned' attribute", V);
904 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
905 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
908 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
911 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
913 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
914 Attribute::ReadNone) &&
915 Attrs.hasAttribute(AttributeSet::FunctionIndex,
916 Attribute::ReadOnly)),
917 "Attributes 'readnone and readonly' are incompatible!", V);
919 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
920 Attribute::NoInline) &&
921 Attrs.hasAttribute(AttributeSet::FunctionIndex,
922 Attribute::AlwaysInline)),
923 "Attributes 'noinline and alwaysinline' are incompatible!", V);
925 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
926 Attribute::OptimizeNone)) {
927 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
928 Attribute::AlwaysInline),
929 "Attributes 'alwaysinline and optnone' are incompatible!", V);
931 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
932 Attribute::OptimizeForSize),
933 "Attributes 'optsize and optnone' are incompatible!", V);
935 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
937 "Attributes 'minsize and optnone' are incompatible!", V);
941 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
942 // Get the size of the types in bits, we'll need this later
943 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
944 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
946 // BitCast implies a no-op cast of type only. No bits change.
947 // However, you can't cast pointers to anything but pointers.
948 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
949 "Bitcast requires both operands to be pointer or neither", V);
950 Assert1(SrcBitSize == DestBitSize,
951 "Bitcast requires types of same width", V);
953 // Disallow aggregates.
954 Assert1(!SrcTy->isAggregateType(),
955 "Bitcast operand must not be aggregate", V);
956 Assert1(!DestTy->isAggregateType(),
957 "Bitcast type must not be aggregate", V);
959 // Without datalayout, assume all address spaces are the same size.
960 // Don't check if both types are not pointers.
961 // Skip casts between scalars and vectors.
963 !SrcTy->isPtrOrPtrVectorTy() ||
964 !DestTy->isPtrOrPtrVectorTy() ||
965 SrcTy->isVectorTy() != DestTy->isVectorTy()) {
969 unsigned SrcAS = SrcTy->getPointerAddressSpace();
970 unsigned DstAS = DestTy->getPointerAddressSpace();
972 unsigned SrcASSize = DL->getPointerSizeInBits(SrcAS);
973 unsigned DstASSize = DL->getPointerSizeInBits(DstAS);
974 Assert1(SrcASSize == DstASSize,
975 "Bitcasts between pointers of different address spaces must have "
976 "the same size pointers, otherwise use PtrToInt/IntToPtr.", V);
979 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
980 if (CE->getOpcode() == Instruction::BitCast) {
981 Type *SrcTy = CE->getOperand(0)->getType();
982 Type *DstTy = CE->getType();
983 VerifyBitcastType(CE, DstTy, SrcTy);
987 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
988 if (Attrs.getNumSlots() == 0)
991 unsigned LastSlot = Attrs.getNumSlots() - 1;
992 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
993 if (LastIndex <= Params
994 || (LastIndex == AttributeSet::FunctionIndex
995 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1001 // visitFunction - Verify that a function is ok.
1003 void Verifier::visitFunction(Function &F) {
1004 // Check function arguments.
1005 FunctionType *FT = F.getFunctionType();
1006 unsigned NumArgs = F.arg_size();
1008 Assert1(Context == &F.getContext(),
1009 "Function context does not match Module context!", &F);
1011 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1012 Assert2(FT->getNumParams() == NumArgs,
1013 "# formal arguments must match # of arguments for function type!",
1015 Assert1(F.getReturnType()->isFirstClassType() ||
1016 F.getReturnType()->isVoidTy() ||
1017 F.getReturnType()->isStructTy(),
1018 "Functions cannot return aggregate values!", &F);
1020 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1021 "Invalid struct return type!", &F);
1023 AttributeSet Attrs = F.getAttributes();
1025 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
1026 "Attribute after last parameter!", &F);
1028 // Check function attributes.
1029 VerifyFunctionAttrs(FT, Attrs, &F);
1031 // On function declarations/definitions, we do not support the builtin
1032 // attribute. We do not check this in VerifyFunctionAttrs since that is
1033 // checking for Attributes that can/can not ever be on functions.
1034 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1035 Attribute::Builtin),
1036 "Attribute 'builtin' can only be applied to a callsite.", &F);
1038 // Check that this function meets the restrictions on this calling convention.
1039 switch (F.getCallingConv()) {
1042 case CallingConv::C:
1044 case CallingConv::Fast:
1045 case CallingConv::Cold:
1046 case CallingConv::X86_FastCall:
1047 case CallingConv::X86_ThisCall:
1048 case CallingConv::Intel_OCL_BI:
1049 case CallingConv::PTX_Kernel:
1050 case CallingConv::PTX_Device:
1051 Assert1(!F.isVarArg(),
1052 "Varargs functions must have C calling conventions!", &F);
1056 bool isLLVMdotName = F.getName().size() >= 5 &&
1057 F.getName().substr(0, 5) == "llvm.";
1059 // Check that the argument values match the function type for this function...
1061 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1063 Assert2(I->getType() == FT->getParamType(i),
1064 "Argument value does not match function argument type!",
1065 I, FT->getParamType(i));
1066 Assert1(I->getType()->isFirstClassType(),
1067 "Function arguments must have first-class types!", I);
1069 Assert2(!I->getType()->isMetadataTy(),
1070 "Function takes metadata but isn't an intrinsic", I, &F);
1073 if (F.isMaterializable()) {
1074 // Function has a body somewhere we can't see.
1075 } else if (F.isDeclaration()) {
1076 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
1077 F.hasExternalWeakLinkage(),
1078 "invalid linkage type for function declaration", &F);
1080 // Verify that this function (which has a body) is not named "llvm.*". It
1081 // is not legal to define intrinsics.
1082 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1084 // Check the entry node
1085 BasicBlock *Entry = &F.getEntryBlock();
1086 Assert1(pred_begin(Entry) == pred_end(Entry),
1087 "Entry block to function must not have predecessors!", Entry);
1089 // The address of the entry block cannot be taken, unless it is dead.
1090 if (Entry->hasAddressTaken()) {
1091 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
1092 "blockaddress may not be used with the entry block!", Entry);
1096 // If this function is actually an intrinsic, verify that it is only used in
1097 // direct call/invokes, never having its "address taken".
1098 if (F.getIntrinsicID()) {
1100 if (F.hasAddressTaken(&U))
1101 Assert1(0, "Invalid user of intrinsic instruction!", U);
1105 // verifyBasicBlock - Verify that a basic block is well formed...
1107 void Verifier::visitBasicBlock(BasicBlock &BB) {
1108 InstsInThisBlock.clear();
1110 // Ensure that basic blocks have terminators!
1111 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1113 // Check constraints that this basic block imposes on all of the PHI nodes in
1115 if (isa<PHINode>(BB.front())) {
1116 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1117 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1118 std::sort(Preds.begin(), Preds.end());
1120 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1121 // Ensure that PHI nodes have at least one entry!
1122 Assert1(PN->getNumIncomingValues() != 0,
1123 "PHI nodes must have at least one entry. If the block is dead, "
1124 "the PHI should be removed!", PN);
1125 Assert1(PN->getNumIncomingValues() == Preds.size(),
1126 "PHINode should have one entry for each predecessor of its "
1127 "parent basic block!", PN);
1129 // Get and sort all incoming values in the PHI node...
1131 Values.reserve(PN->getNumIncomingValues());
1132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1133 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1134 PN->getIncomingValue(i)));
1135 std::sort(Values.begin(), Values.end());
1137 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1138 // Check to make sure that if there is more than one entry for a
1139 // particular basic block in this PHI node, that the incoming values are
1142 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1143 Values[i].second == Values[i-1].second,
1144 "PHI node has multiple entries for the same basic block with "
1145 "different incoming values!", PN, Values[i].first,
1146 Values[i].second, Values[i-1].second);
1148 // Check to make sure that the predecessors and PHI node entries are
1150 Assert3(Values[i].first == Preds[i],
1151 "PHI node entries do not match predecessors!", PN,
1152 Values[i].first, Preds[i]);
1158 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1159 // Ensure that terminators only exist at the end of the basic block.
1160 Assert1(&I == I.getParent()->getTerminator(),
1161 "Terminator found in the middle of a basic block!", I.getParent());
1162 visitInstruction(I);
1165 void Verifier::visitBranchInst(BranchInst &BI) {
1166 if (BI.isConditional()) {
1167 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1168 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1170 visitTerminatorInst(BI);
1173 void Verifier::visitReturnInst(ReturnInst &RI) {
1174 Function *F = RI.getParent()->getParent();
1175 unsigned N = RI.getNumOperands();
1176 if (F->getReturnType()->isVoidTy())
1178 "Found return instr that returns non-void in Function of void "
1179 "return type!", &RI, F->getReturnType());
1181 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1182 "Function return type does not match operand "
1183 "type of return inst!", &RI, F->getReturnType());
1185 // Check to make sure that the return value has necessary properties for
1187 visitTerminatorInst(RI);
1190 void Verifier::visitSwitchInst(SwitchInst &SI) {
1191 // Check to make sure that all of the constants in the switch instruction
1192 // have the same type as the switched-on value.
1193 Type *SwitchTy = SI.getCondition()->getType();
1194 SmallPtrSet<ConstantInt*, 32> Constants;
1195 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1196 Assert1(i.getCaseValue()->getType() == SwitchTy,
1197 "Switch constants must all be same type as switch value!", &SI);
1198 Assert2(Constants.insert(i.getCaseValue()),
1199 "Duplicate integer as switch case", &SI, i.getCaseValue());
1202 visitTerminatorInst(SI);
1205 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1206 Assert1(BI.getAddress()->getType()->isPointerTy(),
1207 "Indirectbr operand must have pointer type!", &BI);
1208 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1209 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1210 "Indirectbr destinations must all have pointer type!", &BI);
1212 visitTerminatorInst(BI);
1215 void Verifier::visitSelectInst(SelectInst &SI) {
1216 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1218 "Invalid operands for select instruction!", &SI);
1220 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1221 "Select values must have same type as select instruction!", &SI);
1222 visitInstruction(SI);
1225 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1226 /// a pass, if any exist, it's an error.
1228 void Verifier::visitUserOp1(Instruction &I) {
1229 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1232 void Verifier::visitTruncInst(TruncInst &I) {
1233 // Get the source and destination types
1234 Type *SrcTy = I.getOperand(0)->getType();
1235 Type *DestTy = I.getType();
1237 // Get the size of the types in bits, we'll need this later
1238 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1239 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1241 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1242 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1243 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1244 "trunc source and destination must both be a vector or neither", &I);
1245 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1247 visitInstruction(I);
1250 void Verifier::visitZExtInst(ZExtInst &I) {
1251 // Get the source and destination types
1252 Type *SrcTy = I.getOperand(0)->getType();
1253 Type *DestTy = I.getType();
1255 // Get the size of the types in bits, we'll need this later
1256 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1257 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1258 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1259 "zext source and destination must both be a vector or neither", &I);
1260 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1261 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1263 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1265 visitInstruction(I);
1268 void Verifier::visitSExtInst(SExtInst &I) {
1269 // Get the source and destination types
1270 Type *SrcTy = I.getOperand(0)->getType();
1271 Type *DestTy = I.getType();
1273 // Get the size of the types in bits, we'll need this later
1274 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1275 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1277 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1278 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1279 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1280 "sext source and destination must both be a vector or neither", &I);
1281 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1283 visitInstruction(I);
1286 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1287 // Get the source and destination types
1288 Type *SrcTy = I.getOperand(0)->getType();
1289 Type *DestTy = I.getType();
1290 // Get the size of the types in bits, we'll need this later
1291 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1292 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1294 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1295 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1296 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1297 "fptrunc source and destination must both be a vector or neither",&I);
1298 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1300 visitInstruction(I);
1303 void Verifier::visitFPExtInst(FPExtInst &I) {
1304 // Get the source and destination types
1305 Type *SrcTy = I.getOperand(0)->getType();
1306 Type *DestTy = I.getType();
1308 // Get the size of the types in bits, we'll need this later
1309 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1310 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1312 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1313 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1314 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1315 "fpext source and destination must both be a vector or neither", &I);
1316 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1318 visitInstruction(I);
1321 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1322 // Get the source and destination types
1323 Type *SrcTy = I.getOperand(0)->getType();
1324 Type *DestTy = I.getType();
1326 bool SrcVec = SrcTy->isVectorTy();
1327 bool DstVec = DestTy->isVectorTy();
1329 Assert1(SrcVec == DstVec,
1330 "UIToFP source and dest must both be vector or scalar", &I);
1331 Assert1(SrcTy->isIntOrIntVectorTy(),
1332 "UIToFP source must be integer or integer vector", &I);
1333 Assert1(DestTy->isFPOrFPVectorTy(),
1334 "UIToFP result must be FP or FP vector", &I);
1336 if (SrcVec && DstVec)
1337 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1338 cast<VectorType>(DestTy)->getNumElements(),
1339 "UIToFP source and dest vector length mismatch", &I);
1341 visitInstruction(I);
1344 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1345 // Get the source and destination types
1346 Type *SrcTy = I.getOperand(0)->getType();
1347 Type *DestTy = I.getType();
1349 bool SrcVec = SrcTy->isVectorTy();
1350 bool DstVec = DestTy->isVectorTy();
1352 Assert1(SrcVec == DstVec,
1353 "SIToFP source and dest must both be vector or scalar", &I);
1354 Assert1(SrcTy->isIntOrIntVectorTy(),
1355 "SIToFP source must be integer or integer vector", &I);
1356 Assert1(DestTy->isFPOrFPVectorTy(),
1357 "SIToFP result must be FP or FP vector", &I);
1359 if (SrcVec && DstVec)
1360 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1361 cast<VectorType>(DestTy)->getNumElements(),
1362 "SIToFP source and dest vector length mismatch", &I);
1364 visitInstruction(I);
1367 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1368 // Get the source and destination types
1369 Type *SrcTy = I.getOperand(0)->getType();
1370 Type *DestTy = I.getType();
1372 bool SrcVec = SrcTy->isVectorTy();
1373 bool DstVec = DestTy->isVectorTy();
1375 Assert1(SrcVec == DstVec,
1376 "FPToUI source and dest must both be vector or scalar", &I);
1377 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1379 Assert1(DestTy->isIntOrIntVectorTy(),
1380 "FPToUI result must be integer or integer vector", &I);
1382 if (SrcVec && DstVec)
1383 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1384 cast<VectorType>(DestTy)->getNumElements(),
1385 "FPToUI source and dest vector length mismatch", &I);
1387 visitInstruction(I);
1390 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1391 // Get the source and destination types
1392 Type *SrcTy = I.getOperand(0)->getType();
1393 Type *DestTy = I.getType();
1395 bool SrcVec = SrcTy->isVectorTy();
1396 bool DstVec = DestTy->isVectorTy();
1398 Assert1(SrcVec == DstVec,
1399 "FPToSI source and dest must both be vector or scalar", &I);
1400 Assert1(SrcTy->isFPOrFPVectorTy(),
1401 "FPToSI source must be FP or FP vector", &I);
1402 Assert1(DestTy->isIntOrIntVectorTy(),
1403 "FPToSI result must be integer or integer vector", &I);
1405 if (SrcVec && DstVec)
1406 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1407 cast<VectorType>(DestTy)->getNumElements(),
1408 "FPToSI source and dest vector length mismatch", &I);
1410 visitInstruction(I);
1413 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1414 // Get the source and destination types
1415 Type *SrcTy = I.getOperand(0)->getType();
1416 Type *DestTy = I.getType();
1418 Assert1(SrcTy->getScalarType()->isPointerTy(),
1419 "PtrToInt source must be pointer", &I);
1420 Assert1(DestTy->getScalarType()->isIntegerTy(),
1421 "PtrToInt result must be integral", &I);
1422 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1423 "PtrToInt type mismatch", &I);
1425 if (SrcTy->isVectorTy()) {
1426 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1427 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1428 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1429 "PtrToInt Vector width mismatch", &I);
1432 visitInstruction(I);
1435 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1436 // Get the source and destination types
1437 Type *SrcTy = I.getOperand(0)->getType();
1438 Type *DestTy = I.getType();
1440 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1441 "IntToPtr source must be an integral", &I);
1442 Assert1(DestTy->getScalarType()->isPointerTy(),
1443 "IntToPtr result must be a pointer",&I);
1444 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1445 "IntToPtr type mismatch", &I);
1446 if (SrcTy->isVectorTy()) {
1447 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1448 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1449 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1450 "IntToPtr Vector width mismatch", &I);
1452 visitInstruction(I);
1455 void Verifier::visitBitCastInst(BitCastInst &I) {
1456 Type *SrcTy = I.getOperand(0)->getType();
1457 Type *DestTy = I.getType();
1458 VerifyBitcastType(&I, DestTy, SrcTy);
1459 visitInstruction(I);
1462 /// visitPHINode - Ensure that a PHI node is well formed.
1464 void Verifier::visitPHINode(PHINode &PN) {
1465 // Ensure that the PHI nodes are all grouped together at the top of the block.
1466 // This can be tested by checking whether the instruction before this is
1467 // either nonexistent (because this is begin()) or is a PHI node. If not,
1468 // then there is some other instruction before a PHI.
1469 Assert2(&PN == &PN.getParent()->front() ||
1470 isa<PHINode>(--BasicBlock::iterator(&PN)),
1471 "PHI nodes not grouped at top of basic block!",
1472 &PN, PN.getParent());
1474 // Check that all of the values of the PHI node have the same type as the
1475 // result, and that the incoming blocks are really basic blocks.
1476 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1477 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1478 "PHI node operands are not the same type as the result!", &PN);
1481 // All other PHI node constraints are checked in the visitBasicBlock method.
1483 visitInstruction(PN);
1486 void Verifier::VerifyCallSite(CallSite CS) {
1487 Instruction *I = CS.getInstruction();
1489 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1490 "Called function must be a pointer!", I);
1491 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1493 Assert1(FPTy->getElementType()->isFunctionTy(),
1494 "Called function is not pointer to function type!", I);
1495 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1497 // Verify that the correct number of arguments are being passed
1498 if (FTy->isVarArg())
1499 Assert1(CS.arg_size() >= FTy->getNumParams(),
1500 "Called function requires more parameters than were provided!",I);
1502 Assert1(CS.arg_size() == FTy->getNumParams(),
1503 "Incorrect number of arguments passed to called function!", I);
1505 // Verify that all arguments to the call match the function type.
1506 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1507 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1508 "Call parameter type does not match function signature!",
1509 CS.getArgument(i), FTy->getParamType(i), I);
1511 AttributeSet Attrs = CS.getAttributes();
1513 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1514 "Attribute after last parameter!", I);
1516 // Verify call attributes.
1517 VerifyFunctionAttrs(FTy, Attrs, I);
1519 if (FTy->isVarArg()) {
1520 // FIXME? is 'nest' even legal here?
1521 bool SawNest = false;
1522 bool SawReturned = false;
1524 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1525 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1527 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1531 // Check attributes on the varargs part.
1532 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1533 Type *Ty = CS.getArgument(Idx-1)->getType();
1534 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1536 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1537 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1541 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1542 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1544 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1545 "Incompatible argument and return types for 'returned' "
1550 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1551 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1555 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1556 if (CS.getCalledFunction() == 0 ||
1557 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1558 for (FunctionType::param_iterator PI = FTy->param_begin(),
1559 PE = FTy->param_end(); PI != PE; ++PI)
1560 Assert1(!(*PI)->isMetadataTy(),
1561 "Function has metadata parameter but isn't an intrinsic", I);
1564 visitInstruction(*I);
1567 void Verifier::visitCallInst(CallInst &CI) {
1568 VerifyCallSite(&CI);
1570 if (Function *F = CI.getCalledFunction())
1571 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1572 visitIntrinsicFunctionCall(ID, CI);
1575 void Verifier::visitInvokeInst(InvokeInst &II) {
1576 VerifyCallSite(&II);
1578 // Verify that there is a landingpad instruction as the first non-PHI
1579 // instruction of the 'unwind' destination.
1580 Assert1(II.getUnwindDest()->isLandingPad(),
1581 "The unwind destination does not have a landingpad instruction!",&II);
1583 visitTerminatorInst(II);
1586 /// visitBinaryOperator - Check that both arguments to the binary operator are
1587 /// of the same type!
1589 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1590 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1591 "Both operands to a binary operator are not of the same type!", &B);
1593 switch (B.getOpcode()) {
1594 // Check that integer arithmetic operators are only used with
1595 // integral operands.
1596 case Instruction::Add:
1597 case Instruction::Sub:
1598 case Instruction::Mul:
1599 case Instruction::SDiv:
1600 case Instruction::UDiv:
1601 case Instruction::SRem:
1602 case Instruction::URem:
1603 Assert1(B.getType()->isIntOrIntVectorTy(),
1604 "Integer arithmetic operators only work with integral types!", &B);
1605 Assert1(B.getType() == B.getOperand(0)->getType(),
1606 "Integer arithmetic operators must have same type "
1607 "for operands and result!", &B);
1609 // Check that floating-point arithmetic operators are only used with
1610 // floating-point operands.
1611 case Instruction::FAdd:
1612 case Instruction::FSub:
1613 case Instruction::FMul:
1614 case Instruction::FDiv:
1615 case Instruction::FRem:
1616 Assert1(B.getType()->isFPOrFPVectorTy(),
1617 "Floating-point arithmetic operators only work with "
1618 "floating-point types!", &B);
1619 Assert1(B.getType() == B.getOperand(0)->getType(),
1620 "Floating-point arithmetic operators must have same type "
1621 "for operands and result!", &B);
1623 // Check that logical operators are only used with integral operands.
1624 case Instruction::And:
1625 case Instruction::Or:
1626 case Instruction::Xor:
1627 Assert1(B.getType()->isIntOrIntVectorTy(),
1628 "Logical operators only work with integral types!", &B);
1629 Assert1(B.getType() == B.getOperand(0)->getType(),
1630 "Logical operators must have same type for operands and result!",
1633 case Instruction::Shl:
1634 case Instruction::LShr:
1635 case Instruction::AShr:
1636 Assert1(B.getType()->isIntOrIntVectorTy(),
1637 "Shifts only work with integral types!", &B);
1638 Assert1(B.getType() == B.getOperand(0)->getType(),
1639 "Shift return type must be same as operands!", &B);
1642 llvm_unreachable("Unknown BinaryOperator opcode!");
1645 visitInstruction(B);
1648 void Verifier::visitICmpInst(ICmpInst &IC) {
1649 // Check that the operands are the same type
1650 Type *Op0Ty = IC.getOperand(0)->getType();
1651 Type *Op1Ty = IC.getOperand(1)->getType();
1652 Assert1(Op0Ty == Op1Ty,
1653 "Both operands to ICmp instruction are not of the same type!", &IC);
1654 // Check that the operands are the right type
1655 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1656 "Invalid operand types for ICmp instruction", &IC);
1657 // Check that the predicate is valid.
1658 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1659 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1660 "Invalid predicate in ICmp instruction!", &IC);
1662 visitInstruction(IC);
1665 void Verifier::visitFCmpInst(FCmpInst &FC) {
1666 // Check that the operands are the same type
1667 Type *Op0Ty = FC.getOperand(0)->getType();
1668 Type *Op1Ty = FC.getOperand(1)->getType();
1669 Assert1(Op0Ty == Op1Ty,
1670 "Both operands to FCmp instruction are not of the same type!", &FC);
1671 // Check that the operands are the right type
1672 Assert1(Op0Ty->isFPOrFPVectorTy(),
1673 "Invalid operand types for FCmp instruction", &FC);
1674 // Check that the predicate is valid.
1675 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1676 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1677 "Invalid predicate in FCmp instruction!", &FC);
1679 visitInstruction(FC);
1682 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1683 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1685 "Invalid extractelement operands!", &EI);
1686 visitInstruction(EI);
1689 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1690 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1693 "Invalid insertelement operands!", &IE);
1694 visitInstruction(IE);
1697 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1698 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1700 "Invalid shufflevector operands!", &SV);
1701 visitInstruction(SV);
1704 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1705 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1707 Assert1(isa<PointerType>(TargetTy),
1708 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1709 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1710 "GEP into unsized type!", &GEP);
1711 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1712 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1715 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1717 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1718 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1720 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1721 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1722 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1724 if (GEP.getPointerOperandType()->isVectorTy()) {
1725 // Additional checks for vector GEPs.
1726 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1727 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1728 "Vector GEP result width doesn't match operand's", &GEP);
1729 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1730 Type *IndexTy = Idxs[i]->getType();
1731 Assert1(IndexTy->isVectorTy(),
1732 "Vector GEP must have vector indices!", &GEP);
1733 unsigned IndexWidth = IndexTy->getVectorNumElements();
1734 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1737 visitInstruction(GEP);
1740 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1741 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1744 void Verifier::visitLoadInst(LoadInst &LI) {
1745 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1746 Assert1(PTy, "Load operand must be a pointer.", &LI);
1747 Type *ElTy = PTy->getElementType();
1748 Assert2(ElTy == LI.getType(),
1749 "Load result type does not match pointer operand type!", &LI, ElTy);
1750 if (LI.isAtomic()) {
1751 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1752 "Load cannot have Release ordering", &LI);
1753 Assert1(LI.getAlignment() != 0,
1754 "Atomic load must specify explicit alignment", &LI);
1755 if (!ElTy->isPointerTy()) {
1756 Assert2(ElTy->isIntegerTy(),
1757 "atomic store operand must have integer type!",
1759 unsigned Size = ElTy->getPrimitiveSizeInBits();
1760 Assert2(Size >= 8 && !(Size & (Size - 1)),
1761 "atomic store operand must be power-of-two byte-sized integer",
1765 Assert1(LI.getSynchScope() == CrossThread,
1766 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1769 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1770 unsigned NumOperands = Range->getNumOperands();
1771 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1772 unsigned NumRanges = NumOperands / 2;
1773 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1775 ConstantRange LastRange(1); // Dummy initial value
1776 for (unsigned i = 0; i < NumRanges; ++i) {
1777 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1778 Assert1(Low, "The lower limit must be an integer!", Low);
1779 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1780 Assert1(High, "The upper limit must be an integer!", High);
1781 Assert1(High->getType() == Low->getType() &&
1782 High->getType() == ElTy, "Range types must match load type!",
1785 APInt HighV = High->getValue();
1786 APInt LowV = Low->getValue();
1787 ConstantRange CurRange(LowV, HighV);
1788 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1789 "Range must not be empty!", Range);
1791 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1792 "Intervals are overlapping", Range);
1793 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1795 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1798 LastRange = ConstantRange(LowV, HighV);
1800 if (NumRanges > 2) {
1802 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1804 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1805 ConstantRange FirstRange(FirstLow, FirstHigh);
1806 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1807 "Intervals are overlapping", Range);
1808 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1815 visitInstruction(LI);
1818 void Verifier::visitStoreInst(StoreInst &SI) {
1819 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1820 Assert1(PTy, "Store operand must be a pointer.", &SI);
1821 Type *ElTy = PTy->getElementType();
1822 Assert2(ElTy == SI.getOperand(0)->getType(),
1823 "Stored value type does not match pointer operand type!",
1825 if (SI.isAtomic()) {
1826 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1827 "Store cannot have Acquire ordering", &SI);
1828 Assert1(SI.getAlignment() != 0,
1829 "Atomic store must specify explicit alignment", &SI);
1830 if (!ElTy->isPointerTy()) {
1831 Assert2(ElTy->isIntegerTy(),
1832 "atomic store operand must have integer type!",
1834 unsigned Size = ElTy->getPrimitiveSizeInBits();
1835 Assert2(Size >= 8 && !(Size & (Size - 1)),
1836 "atomic store operand must be power-of-two byte-sized integer",
1840 Assert1(SI.getSynchScope() == CrossThread,
1841 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1843 visitInstruction(SI);
1846 void Verifier::visitAllocaInst(AllocaInst &AI) {
1847 PointerType *PTy = AI.getType();
1848 Assert1(PTy->getAddressSpace() == 0,
1849 "Allocation instruction pointer not in the generic address space!",
1851 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1853 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1854 "Alloca array size must have integer type", &AI);
1855 visitInstruction(AI);
1858 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1859 Assert1(CXI.getOrdering() != NotAtomic,
1860 "cmpxchg instructions must be atomic.", &CXI);
1861 Assert1(CXI.getOrdering() != Unordered,
1862 "cmpxchg instructions cannot be unordered.", &CXI);
1863 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1864 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1865 Type *ElTy = PTy->getElementType();
1866 Assert2(ElTy->isIntegerTy(),
1867 "cmpxchg operand must have integer type!",
1869 unsigned Size = ElTy->getPrimitiveSizeInBits();
1870 Assert2(Size >= 8 && !(Size & (Size - 1)),
1871 "cmpxchg operand must be power-of-two byte-sized integer",
1873 Assert2(ElTy == CXI.getOperand(1)->getType(),
1874 "Expected value type does not match pointer operand type!",
1876 Assert2(ElTy == CXI.getOperand(2)->getType(),
1877 "Stored value type does not match pointer operand type!",
1879 visitInstruction(CXI);
1882 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1883 Assert1(RMWI.getOrdering() != NotAtomic,
1884 "atomicrmw instructions must be atomic.", &RMWI);
1885 Assert1(RMWI.getOrdering() != Unordered,
1886 "atomicrmw instructions cannot be unordered.", &RMWI);
1887 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1888 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1889 Type *ElTy = PTy->getElementType();
1890 Assert2(ElTy->isIntegerTy(),
1891 "atomicrmw operand must have integer type!",
1893 unsigned Size = ElTy->getPrimitiveSizeInBits();
1894 Assert2(Size >= 8 && !(Size & (Size - 1)),
1895 "atomicrmw operand must be power-of-two byte-sized integer",
1897 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1898 "Argument value type does not match pointer operand type!",
1900 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1901 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1902 "Invalid binary operation!", &RMWI);
1903 visitInstruction(RMWI);
1906 void Verifier::visitFenceInst(FenceInst &FI) {
1907 const AtomicOrdering Ordering = FI.getOrdering();
1908 Assert1(Ordering == Acquire || Ordering == Release ||
1909 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1910 "fence instructions may only have "
1911 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1912 visitInstruction(FI);
1915 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1916 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1917 EVI.getIndices()) ==
1919 "Invalid ExtractValueInst operands!", &EVI);
1921 visitInstruction(EVI);
1924 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1925 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1926 IVI.getIndices()) ==
1927 IVI.getOperand(1)->getType(),
1928 "Invalid InsertValueInst operands!", &IVI);
1930 visitInstruction(IVI);
1933 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1934 BasicBlock *BB = LPI.getParent();
1936 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1938 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1939 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1941 // The landingpad instruction defines its parent as a landing pad block. The
1942 // landing pad block may be branched to only by the unwind edge of an invoke.
1943 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1944 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1945 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1946 "Block containing LandingPadInst must be jumped to "
1947 "only by the unwind edge of an invoke.", &LPI);
1950 // The landingpad instruction must be the first non-PHI instruction in the
1952 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1953 "LandingPadInst not the first non-PHI instruction in the block.",
1956 // The personality functions for all landingpad instructions within the same
1957 // function should match.
1959 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1960 "Personality function doesn't match others in function", &LPI);
1961 PersonalityFn = LPI.getPersonalityFn();
1963 // All operands must be constants.
1964 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1966 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1967 Value *Clause = LPI.getClause(i);
1968 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1969 if (LPI.isCatch(i)) {
1970 Assert1(isa<PointerType>(Clause->getType()),
1971 "Catch operand does not have pointer type!", &LPI);
1973 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1974 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1975 "Filter operand is not an array of constants!", &LPI);
1979 visitInstruction(LPI);
1982 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1983 Instruction *Op = cast<Instruction>(I.getOperand(i));
1984 // If the we have an invalid invoke, don't try to compute the dominance.
1985 // We already reject it in the invoke specific checks and the dominance
1986 // computation doesn't handle multiple edges.
1987 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1988 if (II->getNormalDest() == II->getUnwindDest())
1992 const Use &U = I.getOperandUse(i);
1993 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1994 "Instruction does not dominate all uses!", Op, &I);
1997 /// verifyInstruction - Verify that an instruction is well formed.
1999 void Verifier::visitInstruction(Instruction &I) {
2000 BasicBlock *BB = I.getParent();
2001 Assert1(BB, "Instruction not embedded in basic block!", &I);
2003 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2004 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
2006 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
2007 "Only PHI nodes may reference their own value!", &I);
2010 // Check that void typed values don't have names
2011 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2012 "Instruction has a name, but provides a void value!", &I);
2014 // Check that the return value of the instruction is either void or a legal
2016 Assert1(I.getType()->isVoidTy() ||
2017 I.getType()->isFirstClassType(),
2018 "Instruction returns a non-scalar type!", &I);
2020 // Check that the instruction doesn't produce metadata. Calls are already
2021 // checked against the callee type.
2022 Assert1(!I.getType()->isMetadataTy() ||
2023 isa<CallInst>(I) || isa<InvokeInst>(I),
2024 "Invalid use of metadata!", &I);
2026 // Check that all uses of the instruction, if they are instructions
2027 // themselves, actually have parent basic blocks. If the use is not an
2028 // instruction, it is an error!
2029 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
2031 if (Instruction *Used = dyn_cast<Instruction>(*UI))
2032 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2033 " embedded in a basic block!", &I, Used);
2035 CheckFailed("Use of instruction is not an instruction!", *UI);
2040 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2041 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2043 // Check to make sure that only first-class-values are operands to
2045 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2046 Assert1(0, "Instruction operands must be first-class values!", &I);
2049 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2050 // Check to make sure that the "address of" an intrinsic function is never
2052 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2053 "Cannot take the address of an intrinsic!", &I);
2054 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2055 F->getIntrinsicID() == Intrinsic::donothing,
2056 "Cannot invoke an intrinsinc other than donothing", &I);
2057 Assert1(F->getParent() == Mod, "Referencing function in another module!",
2059 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2060 Assert1(OpBB->getParent() == BB->getParent(),
2061 "Referring to a basic block in another function!", &I);
2062 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2063 Assert1(OpArg->getParent() == BB->getParent(),
2064 "Referring to an argument in another function!", &I);
2065 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2066 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
2068 } else if (isa<Instruction>(I.getOperand(i))) {
2069 verifyDominatesUse(I, i);
2070 } else if (isa<InlineAsm>(I.getOperand(i))) {
2071 Assert1((i + 1 == e && isa<CallInst>(I)) ||
2072 (i + 3 == e && isa<InvokeInst>(I)),
2073 "Cannot take the address of an inline asm!", &I);
2074 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2075 if (CE->getType()->isPtrOrPtrVectorTy()) {
2076 // If we have a ConstantExpr pointer, we need to see if it came from an
2077 // illegal bitcast (inttoptr <constant int> )
2078 SmallVector<const ConstantExpr *, 4> Stack;
2079 SmallPtrSet<const ConstantExpr *, 4> Visited;
2080 Stack.push_back(CE);
2082 while (!Stack.empty()) {
2083 const ConstantExpr *V = Stack.pop_back_val();
2084 if (!Visited.insert(V))
2087 VerifyConstantExprBitcastType(V);
2089 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2090 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2091 Stack.push_back(Op);
2098 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2099 Assert1(I.getType()->isFPOrFPVectorTy(),
2100 "fpmath requires a floating point result!", &I);
2101 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2102 Value *Op0 = MD->getOperand(0);
2103 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2104 APFloat Accuracy = CFP0->getValueAPF();
2105 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2106 "fpmath accuracy not a positive number!", &I);
2108 Assert1(false, "invalid fpmath accuracy!", &I);
2112 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2113 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2115 if (!DisableDebugInfoVerifier) {
2116 MD = I.getMetadata(LLVMContext::MD_dbg);
2117 Finder.processLocation(DILocation(MD));
2120 InstsInThisBlock.insert(&I);
2123 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2124 /// intrinsic argument or return value) matches the type constraints specified
2125 /// by the .td file (e.g. an "any integer" argument really is an integer).
2127 /// This return true on error but does not print a message.
2128 bool Verifier::VerifyIntrinsicType(Type *Ty,
2129 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2130 SmallVectorImpl<Type*> &ArgTys) {
2131 using namespace Intrinsic;
2133 // If we ran out of descriptors, there are too many arguments.
2134 if (Infos.empty()) return true;
2135 IITDescriptor D = Infos.front();
2136 Infos = Infos.slice(1);
2139 case IITDescriptor::Void: return !Ty->isVoidTy();
2140 case IITDescriptor::VarArg: return true;
2141 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2142 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2143 case IITDescriptor::Half: return !Ty->isHalfTy();
2144 case IITDescriptor::Float: return !Ty->isFloatTy();
2145 case IITDescriptor::Double: return !Ty->isDoubleTy();
2146 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2147 case IITDescriptor::Vector: {
2148 VectorType *VT = dyn_cast<VectorType>(Ty);
2149 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2150 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2152 case IITDescriptor::Pointer: {
2153 PointerType *PT = dyn_cast<PointerType>(Ty);
2154 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2155 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2158 case IITDescriptor::Struct: {
2159 StructType *ST = dyn_cast<StructType>(Ty);
2160 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2163 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2164 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2169 case IITDescriptor::Argument:
2170 // Two cases here - If this is the second occurrence of an argument, verify
2171 // that the later instance matches the previous instance.
2172 if (D.getArgumentNumber() < ArgTys.size())
2173 return Ty != ArgTys[D.getArgumentNumber()];
2175 // Otherwise, if this is the first instance of an argument, record it and
2176 // verify the "Any" kind.
2177 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2178 ArgTys.push_back(Ty);
2180 switch (D.getArgumentKind()) {
2181 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2182 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2183 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2184 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2186 llvm_unreachable("all argument kinds not covered");
2188 case IITDescriptor::ExtendVecArgument:
2189 // This may only be used when referring to a previous vector argument.
2190 return D.getArgumentNumber() >= ArgTys.size() ||
2191 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2192 VectorType::getExtendedElementVectorType(
2193 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2195 case IITDescriptor::TruncVecArgument:
2196 // This may only be used when referring to a previous vector argument.
2197 return D.getArgumentNumber() >= ArgTys.size() ||
2198 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2199 VectorType::getTruncatedElementVectorType(
2200 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2202 llvm_unreachable("unhandled");
2205 /// \brief Verify if the intrinsic has variable arguments.
2206 /// This method is intended to be called after all the fixed arguments have been
2209 /// This method returns true on error and does not print an error message.
2211 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2212 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2213 using namespace Intrinsic;
2215 // If there are no descriptors left, then it can't be a vararg.
2217 return isVarArg ? true : false;
2219 // There should be only one descriptor remaining at this point.
2220 if (Infos.size() != 1)
2223 // Check and verify the descriptor.
2224 IITDescriptor D = Infos.front();
2225 Infos = Infos.slice(1);
2226 if (D.Kind == IITDescriptor::VarArg)
2227 return isVarArg ? false : true;
2232 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2234 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2235 Function *IF = CI.getCalledFunction();
2236 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2239 // Verify that the intrinsic prototype lines up with what the .td files
2241 FunctionType *IFTy = IF->getFunctionType();
2242 bool IsVarArg = IFTy->isVarArg();
2244 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2245 getIntrinsicInfoTableEntries(ID, Table);
2246 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2248 SmallVector<Type *, 4> ArgTys;
2249 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2250 "Intrinsic has incorrect return type!", IF);
2251 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2252 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2253 "Intrinsic has incorrect argument type!", IF);
2255 // Verify if the intrinsic call matches the vararg property.
2257 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2258 "Intrinsic was not defined with variable arguments!", IF);
2260 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2261 "Callsite was not defined with variable arguments!", IF);
2263 // All descriptors should be absorbed by now.
2264 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2266 // Now that we have the intrinsic ID and the actual argument types (and we
2267 // know they are legal for the intrinsic!) get the intrinsic name through the
2268 // usual means. This allows us to verify the mangling of argument types into
2270 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2271 "Intrinsic name not mangled correctly for type arguments!", IF);
2273 // If the intrinsic takes MDNode arguments, verify that they are either global
2274 // or are local to *this* function.
2275 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2276 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2277 visitMDNode(*MD, CI.getParent()->getParent());
2282 case Intrinsic::ctlz: // llvm.ctlz
2283 case Intrinsic::cttz: // llvm.cttz
2284 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2285 "is_zero_undef argument of bit counting intrinsics must be a "
2286 "constant int", &CI);
2288 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2289 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2290 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2291 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2292 Assert1(MD->getNumOperands() == 1,
2293 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2294 if (!DisableDebugInfoVerifier)
2295 Finder.processDeclare(cast<DbgDeclareInst>(&CI));
2297 case Intrinsic::dbg_value: { //llvm.dbg.value
2298 if (!DisableDebugInfoVerifier) {
2299 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2300 "invalid llvm.dbg.value intrinsic call 1", &CI);
2301 Finder.processValue(cast<DbgValueInst>(&CI));
2305 case Intrinsic::memcpy:
2306 case Intrinsic::memmove:
2307 case Intrinsic::memset:
2308 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2309 "alignment argument of memory intrinsics must be a constant int",
2311 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2312 "isvolatile argument of memory intrinsics must be a constant int",
2315 case Intrinsic::gcroot:
2316 case Intrinsic::gcwrite:
2317 case Intrinsic::gcread:
2318 if (ID == Intrinsic::gcroot) {
2320 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2321 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2322 Assert1(isa<Constant>(CI.getArgOperand(1)),
2323 "llvm.gcroot parameter #2 must be a constant.", &CI);
2324 if (!AI->getType()->getElementType()->isPointerTy()) {
2325 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2326 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2327 "or argument #2 must be a non-null constant.", &CI);
2331 Assert1(CI.getParent()->getParent()->hasGC(),
2332 "Enclosing function does not use GC.", &CI);
2334 case Intrinsic::init_trampoline:
2335 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2336 "llvm.init_trampoline parameter #2 must resolve to a function.",
2339 case Intrinsic::prefetch:
2340 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2341 isa<ConstantInt>(CI.getArgOperand(2)) &&
2342 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2343 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2344 "invalid arguments to llvm.prefetch",
2347 case Intrinsic::stackprotector:
2348 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2349 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2352 case Intrinsic::lifetime_start:
2353 case Intrinsic::lifetime_end:
2354 case Intrinsic::invariant_start:
2355 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2356 "size argument of memory use markers must be a constant integer",
2359 case Intrinsic::invariant_end:
2360 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2361 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2366 void Verifier::verifyDebugInfo(Module &M) {
2367 // Verify Debug Info.
2368 if (!DisableDebugInfoVerifier) {
2369 for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2370 E = Finder.compile_unit_end(); I != E; ++I)
2371 Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2372 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2373 E = Finder.subprogram_end(); I != E; ++I)
2374 Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2375 for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2376 E = Finder.global_variable_end(); I != E; ++I)
2377 Assert1(DIGlobalVariable(*I).Verify(),
2378 "DIGlobalVariable does not Verify!", *I);
2379 for (DebugInfoFinder::iterator I = Finder.type_begin(),
2380 E = Finder.type_end(); I != E; ++I)
2381 Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2382 for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2383 E = Finder.scope_end(); I != E; ++I)
2384 Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2388 //===----------------------------------------------------------------------===//
2389 // Implement the public interfaces to this file...
2390 //===----------------------------------------------------------------------===//
2392 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2393 return new Verifier(action);
2397 /// verifyFunction - Check a function for errors, printing messages on stderr.
2398 /// Return true if the function is corrupt.
2400 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2401 Function &F = const_cast<Function&>(f);
2402 assert(!F.isDeclaration() && "Cannot verify external functions");
2404 FunctionPassManager FPM(F.getParent());
2405 Verifier *V = new Verifier(action);
2407 FPM.doInitialization();
2409 FPM.doFinalization();
2413 /// verifyModule - Check a module for errors, printing messages on stderr.
2414 /// Return true if the module is corrupt.
2416 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2417 std::string *ErrorInfo) {
2419 Verifier *V = new Verifier(action);
2421 PM.run(const_cast<Module&>(M));
2423 if (ErrorInfo && V->Broken)
2424 *ErrorInfo = V->MessagesStr.str();