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/IR/CallingConv.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/InlineAsm.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/IR/Metadata.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/InstVisitor.h"
65 #include "llvm/Pass.h"
66 #include "llvm/PassManager.h"
67 #include "llvm/Support/CFG.h"
68 #include "llvm/Support/CallSite.h"
69 #include "llvm/Support/ConstantRange.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/raw_ostream.h"
77 namespace { // Anonymous namespace for class
78 struct PreVerifier : public FunctionPass {
79 static char ID; // Pass ID, replacement for typeid
81 PreVerifier() : FunctionPass(ID) {
82 initializePreVerifierPass(*PassRegistry::getPassRegistry());
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 // Check that the prerequisites for successful DominatorTree construction
91 bool runOnFunction(Function &F) {
94 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
95 if (I->empty() || !I->back().isTerminator()) {
96 dbgs() << "Basic Block in function '" << F.getName()
97 << "' does not have terminator!\n";
98 WriteAsOperand(dbgs(), I, true);
105 report_fatal_error("Broken module, no Basic Block terminator!");
112 char PreVerifier::ID = 0;
113 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
115 static char &PreVerifyID = PreVerifier::ID;
118 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
119 static char ID; // Pass ID, replacement for typeid
120 bool Broken; // Is this module found to be broken?
121 VerifierFailureAction action;
122 // What to do if verification fails.
123 Module *Mod; // Module we are verifying right now
124 LLVMContext *Context; // Context within which we are verifying
125 DominatorTree *DT; // Dominator Tree, caution can be null!
127 std::string Messages;
128 raw_string_ostream MessagesStr;
130 /// InstInThisBlock - when verifying a basic block, keep track of all of the
131 /// instructions we have seen so far. This allows us to do efficient
132 /// dominance checks for the case when an instruction has an operand that is
133 /// an instruction in the same block.
134 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
136 /// MDNodes - keep track of the metadata nodes that have been checked
138 SmallPtrSet<MDNode *, 32> MDNodes;
140 /// PersonalityFn - The personality function referenced by the
141 /// LandingPadInsts. All LandingPadInsts within the same function must use
142 /// the same personality function.
143 const Value *PersonalityFn;
146 : FunctionPass(ID), Broken(false),
147 action(AbortProcessAction), Mod(0), Context(0), DT(0),
148 MessagesStr(Messages), PersonalityFn(0) {
149 initializeVerifierPass(*PassRegistry::getPassRegistry());
151 explicit Verifier(VerifierFailureAction ctn)
152 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
153 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
154 initializeVerifierPass(*PassRegistry::getPassRegistry());
157 bool doInitialization(Module &M) {
159 Context = &M.getContext();
161 // We must abort before returning back to the pass manager, or else the
162 // pass manager may try to run other passes on the broken module.
163 return abortIfBroken();
166 bool runOnFunction(Function &F) {
167 // Get dominator information if we are being run by PassManager
168 DT = &getAnalysis<DominatorTree>();
171 if (!Context) Context = &F.getContext();
174 InstsInThisBlock.clear();
177 // We must abort before returning back to the pass manager, or else the
178 // pass manager may try to run other passes on the broken module.
179 return abortIfBroken();
182 bool doFinalization(Module &M) {
183 // Scan through, checking all of the external function's linkage now...
184 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
185 visitGlobalValue(*I);
187 // Check to make sure function prototypes are okay.
188 if (I->isDeclaration()) visitFunction(*I);
191 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
193 visitGlobalVariable(*I);
195 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
197 visitGlobalAlias(*I);
199 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
200 E = M.named_metadata_end(); I != E; ++I)
201 visitNamedMDNode(*I);
205 // If the module is broken, abort at this time.
206 return abortIfBroken();
209 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
210 AU.setPreservesAll();
211 AU.addRequiredID(PreVerifyID);
212 AU.addRequired<DominatorTree>();
215 /// abortIfBroken - If the module is broken and we are supposed to abort on
216 /// this condition, do so.
218 bool abortIfBroken() {
219 if (!Broken) return false;
220 MessagesStr << "Broken module found, ";
222 case AbortProcessAction:
223 MessagesStr << "compilation aborted!\n";
224 dbgs() << MessagesStr.str();
225 // Client should choose different reaction if abort is not desired
227 case PrintMessageAction:
228 MessagesStr << "verification continues.\n";
229 dbgs() << MessagesStr.str();
231 case ReturnStatusAction:
232 MessagesStr << "compilation terminated.\n";
235 llvm_unreachable("Invalid action");
239 // Verification methods...
240 void visitGlobalValue(GlobalValue &GV);
241 void visitGlobalVariable(GlobalVariable &GV);
242 void visitGlobalAlias(GlobalAlias &GA);
243 void visitNamedMDNode(NamedMDNode &NMD);
244 void visitMDNode(MDNode &MD, Function *F);
245 void visitModuleFlags(Module &M);
246 void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
247 SmallVectorImpl<MDNode*> &Requirements);
248 void visitFunction(Function &F);
249 void visitBasicBlock(BasicBlock &BB);
250 using InstVisitor<Verifier>::visit;
252 void visit(Instruction &I);
254 void visitTruncInst(TruncInst &I);
255 void visitZExtInst(ZExtInst &I);
256 void visitSExtInst(SExtInst &I);
257 void visitFPTruncInst(FPTruncInst &I);
258 void visitFPExtInst(FPExtInst &I);
259 void visitFPToUIInst(FPToUIInst &I);
260 void visitFPToSIInst(FPToSIInst &I);
261 void visitUIToFPInst(UIToFPInst &I);
262 void visitSIToFPInst(SIToFPInst &I);
263 void visitIntToPtrInst(IntToPtrInst &I);
264 void visitPtrToIntInst(PtrToIntInst &I);
265 void visitBitCastInst(BitCastInst &I);
266 void visitPHINode(PHINode &PN);
267 void visitBinaryOperator(BinaryOperator &B);
268 void visitICmpInst(ICmpInst &IC);
269 void visitFCmpInst(FCmpInst &FC);
270 void visitExtractElementInst(ExtractElementInst &EI);
271 void visitInsertElementInst(InsertElementInst &EI);
272 void visitShuffleVectorInst(ShuffleVectorInst &EI);
273 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
274 void visitCallInst(CallInst &CI);
275 void visitInvokeInst(InvokeInst &II);
276 void visitGetElementPtrInst(GetElementPtrInst &GEP);
277 void visitLoadInst(LoadInst &LI);
278 void visitStoreInst(StoreInst &SI);
279 void verifyDominatesUse(Instruction &I, unsigned i);
280 void visitInstruction(Instruction &I);
281 void visitTerminatorInst(TerminatorInst &I);
282 void visitBranchInst(BranchInst &BI);
283 void visitReturnInst(ReturnInst &RI);
284 void visitSwitchInst(SwitchInst &SI);
285 void visitIndirectBrInst(IndirectBrInst &BI);
286 void visitSelectInst(SelectInst &SI);
287 void visitUserOp1(Instruction &I);
288 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
289 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
290 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
291 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
292 void visitFenceInst(FenceInst &FI);
293 void visitAllocaInst(AllocaInst &AI);
294 void visitExtractValueInst(ExtractValueInst &EVI);
295 void visitInsertValueInst(InsertValueInst &IVI);
296 void visitLandingPadInst(LandingPadInst &LPI);
298 void VerifyCallSite(CallSite CS);
299 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
300 int VT, unsigned ArgNo, std::string &Suffix);
301 bool VerifyIntrinsicType(Type *Ty,
302 ArrayRef<Intrinsic::IITDescriptor> &Infos,
303 SmallVectorImpl<Type*> &ArgTys);
304 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
305 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
306 bool isFunction, const Value *V);
307 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
308 bool isReturnValue, const Value *V);
309 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
312 void WriteValue(const Value *V) {
314 if (isa<Instruction>(V)) {
315 MessagesStr << *V << '\n';
317 WriteAsOperand(MessagesStr, V, true, Mod);
322 void WriteType(Type *T) {
324 MessagesStr << ' ' << *T;
328 // CheckFailed - A check failed, so print out the condition and the message
329 // that failed. This provides a nice place to put a breakpoint if you want
330 // to see why something is not correct.
331 void CheckFailed(const Twine &Message,
332 const Value *V1 = 0, const Value *V2 = 0,
333 const Value *V3 = 0, const Value *V4 = 0) {
334 MessagesStr << Message.str() << "\n";
342 void CheckFailed(const Twine &Message, const Value *V1,
343 Type *T2, const Value *V3 = 0) {
344 MessagesStr << Message.str() << "\n";
351 void CheckFailed(const Twine &Message, Type *T1,
352 Type *T2 = 0, Type *T3 = 0) {
353 MessagesStr << Message.str() << "\n";
360 } // End anonymous namespace
362 char Verifier::ID = 0;
363 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
364 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
365 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
366 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
368 // Assert - We know that cond should be true, if not print an error message.
369 #define Assert(C, M) \
370 do { if (!(C)) { CheckFailed(M); return; } } while (0)
371 #define Assert1(C, M, V1) \
372 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
373 #define Assert2(C, M, V1, V2) \
374 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
375 #define Assert3(C, M, V1, V2, V3) \
376 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
377 #define Assert4(C, M, V1, V2, V3, V4) \
378 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
380 void Verifier::visit(Instruction &I) {
381 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
382 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
383 InstVisitor<Verifier>::visit(I);
387 void Verifier::visitGlobalValue(GlobalValue &GV) {
388 Assert1(!GV.isDeclaration() ||
389 GV.isMaterializable() ||
390 GV.hasExternalLinkage() ||
391 GV.hasDLLImportLinkage() ||
392 GV.hasExternalWeakLinkage() ||
393 (isa<GlobalAlias>(GV) &&
394 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
395 "Global is external, but doesn't have external or dllimport or weak linkage!",
398 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
399 "Global is marked as dllimport, but not external", &GV);
401 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
402 "Only global variables can have appending linkage!", &GV);
404 if (GV.hasAppendingLinkage()) {
405 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
406 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
407 "Only global arrays can have appending linkage!", GVar);
410 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
411 "linkonce_odr_auto_hide can only have default visibility!",
415 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
416 if (GV.hasInitializer()) {
417 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
418 "Global variable initializer type does not match global "
419 "variable type!", &GV);
421 // If the global has common linkage, it must have a zero initializer and
422 // cannot be constant.
423 if (GV.hasCommonLinkage()) {
424 Assert1(GV.getInitializer()->isNullValue(),
425 "'common' global must have a zero initializer!", &GV);
426 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
430 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
431 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 Assert1(!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())) {
442 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
443 PointerType *FuncPtrTy =
444 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
445 Assert1(STy && STy->getNumElements() == 2 &&
446 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
447 STy->getTypeAtIndex(1) == FuncPtrTy,
448 "wrong type for intrinsic global variable", &GV);
452 if (GV.hasName() && (GV.getName() == "llvm.used")) {
453 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
454 "invalid linkage for intrinsic global variable", &GV);
455 Type *GVType = GV.getType()->getElementType();
456 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
457 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
458 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
459 if (GV.hasInitializer()) {
460 Constant *Init = GV.getInitializer();
461 ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
462 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
464 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
465 Value *V = Init->getOperand(i)->stripPointerCasts();
466 // stripPointerCasts strips aliases, so we only need to check for
467 // variables and functions.
468 Assert1(isa<GlobalVariable>(V) || isa<Function>(V),
469 "invalid llvm.used member", V);
475 visitGlobalValue(GV);
478 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
479 Assert1(!GA.getName().empty(),
480 "Alias name cannot be empty!", &GA);
481 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
483 "Alias should have external or external weak linkage!", &GA);
484 Assert1(GA.getAliasee(),
485 "Aliasee cannot be NULL!", &GA);
486 Assert1(GA.getType() == GA.getAliasee()->getType(),
487 "Alias and aliasee types should match!", &GA);
488 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
490 if (!isa<GlobalValue>(GA.getAliasee())) {
491 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
493 (CE->getOpcode() == Instruction::BitCast ||
494 CE->getOpcode() == Instruction::GetElementPtr) &&
495 isa<GlobalValue>(CE->getOperand(0)),
496 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
500 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
502 "Aliasing chain should end with function or global variable", &GA);
504 visitGlobalValue(GA);
507 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
508 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
509 MDNode *MD = NMD.getOperand(i);
513 Assert1(!MD->isFunctionLocal(),
514 "Named metadata operand cannot be function local!", MD);
519 void Verifier::visitMDNode(MDNode &MD, Function *F) {
520 // Only visit each node once. Metadata can be mutually recursive, so this
521 // avoids infinite recursion here, as well as being an optimization.
522 if (!MDNodes.insert(&MD))
525 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
526 Value *Op = MD.getOperand(i);
529 if (isa<Constant>(Op) || isa<MDString>(Op))
531 if (MDNode *N = dyn_cast<MDNode>(Op)) {
532 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
533 "Global metadata operand cannot be function local!", &MD, N);
537 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
539 // If this was an instruction, bb, or argument, verify that it is in the
540 // function that we expect.
541 Function *ActualF = 0;
542 if (Instruction *I = dyn_cast<Instruction>(Op))
543 ActualF = I->getParent()->getParent();
544 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
545 ActualF = BB->getParent();
546 else if (Argument *A = dyn_cast<Argument>(Op))
547 ActualF = A->getParent();
548 assert(ActualF && "Unimplemented function local metadata case!");
550 Assert2(ActualF == F, "function-local metadata used in wrong function",
555 void Verifier::visitModuleFlags(Module &M) {
556 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
559 // Scan each flag, and track the flags and requirements.
560 DenseMap<MDString*, MDNode*> SeenIDs;
561 SmallVector<MDNode*, 16> Requirements;
562 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
563 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
566 // Validate that the requirements in the module are valid.
567 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
568 MDNode *Requirement = Requirements[I];
569 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
570 Value *ReqValue = Requirement->getOperand(1);
572 MDNode *Op = SeenIDs.lookup(Flag);
574 CheckFailed("invalid requirement on flag, flag is not present in module",
579 if (Op->getOperand(2) != ReqValue) {
580 CheckFailed(("invalid requirement on flag, "
581 "flag does not have the required value"),
588 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
589 SmallVectorImpl<MDNode*> &Requirements) {
590 // Each module flag should have three arguments, the merge behavior (a
591 // constant int), the flag ID (an MDString), and the value.
592 Assert1(Op->getNumOperands() == 3,
593 "incorrect number of operands in module flag", Op);
594 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
595 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
597 "invalid behavior operand in module flag (expected constant integer)",
599 unsigned BehaviorValue = Behavior->getZExtValue();
601 "invalid ID operand in module flag (expected metadata string)",
604 // Sanity check the values for behaviors with additional requirements.
605 switch (BehaviorValue) {
608 "invalid behavior operand in module flag (unexpected constant)",
613 case Module::Warning:
614 case Module::Override:
615 // These behavior types accept any value.
618 case Module::Require: {
619 // The value should itself be an MDNode with two operands, a flag ID (an
620 // MDString), and a value.
621 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
622 Assert1(Value && Value->getNumOperands() == 2,
623 "invalid value for 'require' module flag (expected metadata pair)",
625 Assert1(isa<MDString>(Value->getOperand(0)),
626 ("invalid value for 'require' module flag "
627 "(first value operand should be a string)"),
628 Value->getOperand(0));
630 // Append it to the list of requirements, to check once all module flags are
632 Requirements.push_back(Value);
637 case Module::AppendUnique: {
638 // These behavior types require the operand be an MDNode.
639 Assert1(isa<MDNode>(Op->getOperand(2)),
640 "invalid value for 'append'-type module flag "
641 "(expected a metadata node)", Op->getOperand(2));
646 // Unless this is a "requires" flag, check the ID is unique.
647 if (BehaviorValue != Module::Require) {
648 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
650 "module flag identifiers must be unique (or of 'require' type)",
655 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
656 bool isFunction, const Value* V) {
658 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
659 if (Attrs.getSlotIndex(I) == Idx) {
664 assert(Slot != ~0U && "Attribute set inconsistency!");
666 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
668 if (I->isStringAttribute())
671 if (I->getKindAsEnum() == Attribute::NoReturn ||
672 I->getKindAsEnum() == Attribute::NoUnwind ||
673 I->getKindAsEnum() == Attribute::ReadNone ||
674 I->getKindAsEnum() == Attribute::ReadOnly ||
675 I->getKindAsEnum() == Attribute::NoInline ||
676 I->getKindAsEnum() == Attribute::AlwaysInline ||
677 I->getKindAsEnum() == Attribute::OptimizeForSize ||
678 I->getKindAsEnum() == Attribute::StackProtect ||
679 I->getKindAsEnum() == Attribute::StackProtectReq ||
680 I->getKindAsEnum() == Attribute::StackProtectStrong ||
681 I->getKindAsEnum() == Attribute::NoRedZone ||
682 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
683 I->getKindAsEnum() == Attribute::Naked ||
684 I->getKindAsEnum() == Attribute::InlineHint ||
685 I->getKindAsEnum() == Attribute::StackAlignment ||
686 I->getKindAsEnum() == Attribute::UWTable ||
687 I->getKindAsEnum() == Attribute::NonLazyBind ||
688 I->getKindAsEnum() == Attribute::ReturnsTwice ||
689 I->getKindAsEnum() == Attribute::SanitizeAddress ||
690 I->getKindAsEnum() == Attribute::SanitizeThread ||
691 I->getKindAsEnum() == Attribute::SanitizeMemory ||
692 I->getKindAsEnum() == Attribute::MinSize ||
693 I->getKindAsEnum() == Attribute::NoDuplicate ||
694 I->getKindAsEnum() == Attribute::NoBuiltin) {
696 CheckFailed("Attribute '" + I->getKindAsString() +
697 "' only applies to functions!", V);
699 } else if (isFunction) {
700 CheckFailed("Attribute '" + I->getKindAsString() +
701 "' does not apply to functions!", V);
707 // VerifyParameterAttrs - Check the given attributes for an argument or return
708 // value of the specified type. The value V is printed in error messages.
709 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
710 bool isReturnValue, const Value *V) {
711 if (!Attrs.hasAttributes(Idx))
714 VerifyAttributeTypes(Attrs, Idx, false, V);
717 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
718 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
719 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
720 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
721 !Attrs.hasAttribute(Idx, Attribute::Returned),
722 "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
723 "do not apply to return values!", V);
725 // Check for mutually incompatible attributes.
726 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
727 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
728 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
729 Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
730 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
731 Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
732 "'byval, nest, and sret' are incompatible!", V);
734 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
735 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
736 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
737 Attrs.hasAttribute(Idx, Attribute::InReg)) ||
738 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
739 Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
740 "'byval, nest, and inreg' are incompatible!", V);
742 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
743 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
744 "'zeroext and signext' are incompatible!", V);
746 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
747 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
748 "'readnone and readonly' are incompatible!", V);
750 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
751 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
752 "'noinline and alwaysinline' are incompatible!", V);
754 Assert1(!AttrBuilder(Attrs, Idx).
755 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
756 "Wrong types for attribute: " +
757 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
759 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
760 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
761 PTy->getElementType()->isSized(),
762 "Attribute 'byval' does not support unsized types!", V);
764 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
765 "Attribute 'byval' only applies to parameters with pointer type!",
769 // VerifyFunctionAttrs - Check parameter attributes against a function type.
770 // The value V is printed in error messages.
771 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
776 bool SawNest = false;
777 bool SawReturned = false;
779 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
780 unsigned Idx = Attrs.getSlotIndex(i);
784 Ty = FT->getReturnType();
785 else if (Idx-1 < FT->getNumParams())
786 Ty = FT->getParamType(Idx-1);
788 break; // VarArgs attributes, verified elsewhere.
790 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
795 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
796 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
800 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
801 Assert1(!SawReturned, "More than one parameter has attribute returned!",
803 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
804 "argument and return types for 'returned' attribute", V);
808 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
809 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
812 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
815 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
817 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
818 Attribute::ReadNone) &&
819 Attrs.hasAttribute(AttributeSet::FunctionIndex,
820 Attribute::ReadOnly)),
821 "Attributes 'readnone and readonly' are incompatible!", V);
823 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
824 Attribute::NoInline) &&
825 Attrs.hasAttribute(AttributeSet::FunctionIndex,
826 Attribute::AlwaysInline)),
827 "Attributes 'noinline and alwaysinline' are incompatible!", V);
830 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
831 if (Attrs.getNumSlots() == 0)
834 unsigned LastSlot = Attrs.getNumSlots() - 1;
835 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
836 if (LastIndex <= Params
837 || (LastIndex == AttributeSet::FunctionIndex
838 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
844 // visitFunction - Verify that a function is ok.
846 void Verifier::visitFunction(Function &F) {
847 // Check function arguments.
848 FunctionType *FT = F.getFunctionType();
849 unsigned NumArgs = F.arg_size();
851 Assert1(Context == &F.getContext(),
852 "Function context does not match Module context!", &F);
854 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
855 Assert2(FT->getNumParams() == NumArgs,
856 "# formal arguments must match # of arguments for function type!",
858 Assert1(F.getReturnType()->isFirstClassType() ||
859 F.getReturnType()->isVoidTy() ||
860 F.getReturnType()->isStructTy(),
861 "Functions cannot return aggregate values!", &F);
863 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
864 "Invalid struct return type!", &F);
866 AttributeSet Attrs = F.getAttributes();
868 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
869 "Attribute after last parameter!", &F);
871 // Check function attributes.
872 VerifyFunctionAttrs(FT, Attrs, &F);
874 // Check that this function meets the restrictions on this calling convention.
875 switch (F.getCallingConv()) {
880 case CallingConv::Fast:
881 case CallingConv::Cold:
882 case CallingConv::X86_FastCall:
883 case CallingConv::X86_ThisCall:
884 case CallingConv::Intel_OCL_BI:
885 case CallingConv::PTX_Kernel:
886 case CallingConv::PTX_Device:
887 Assert1(!F.isVarArg(),
888 "Varargs functions must have C calling conventions!", &F);
892 bool isLLVMdotName = F.getName().size() >= 5 &&
893 F.getName().substr(0, 5) == "llvm.";
895 // Check that the argument values match the function type for this function...
897 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
899 Assert2(I->getType() == FT->getParamType(i),
900 "Argument value does not match function argument type!",
901 I, FT->getParamType(i));
902 Assert1(I->getType()->isFirstClassType(),
903 "Function arguments must have first-class types!", I);
905 Assert2(!I->getType()->isMetadataTy(),
906 "Function takes metadata but isn't an intrinsic", I, &F);
909 if (F.isMaterializable()) {
910 // Function has a body somewhere we can't see.
911 } else if (F.isDeclaration()) {
912 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
913 F.hasExternalWeakLinkage(),
914 "invalid linkage type for function declaration", &F);
916 // Verify that this function (which has a body) is not named "llvm.*". It
917 // is not legal to define intrinsics.
918 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
920 // Check the entry node
921 BasicBlock *Entry = &F.getEntryBlock();
922 Assert1(pred_begin(Entry) == pred_end(Entry),
923 "Entry block to function must not have predecessors!", Entry);
925 // The address of the entry block cannot be taken, unless it is dead.
926 if (Entry->hasAddressTaken()) {
927 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
928 "blockaddress may not be used with the entry block!", Entry);
932 // If this function is actually an intrinsic, verify that it is only used in
933 // direct call/invokes, never having its "address taken".
934 if (F.getIntrinsicID()) {
936 if (F.hasAddressTaken(&U))
937 Assert1(0, "Invalid user of intrinsic instruction!", U);
941 // verifyBasicBlock - Verify that a basic block is well formed...
943 void Verifier::visitBasicBlock(BasicBlock &BB) {
944 InstsInThisBlock.clear();
946 // Ensure that basic blocks have terminators!
947 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
949 // Check constraints that this basic block imposes on all of the PHI nodes in
951 if (isa<PHINode>(BB.front())) {
952 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
953 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
954 std::sort(Preds.begin(), Preds.end());
956 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
957 // Ensure that PHI nodes have at least one entry!
958 Assert1(PN->getNumIncomingValues() != 0,
959 "PHI nodes must have at least one entry. If the block is dead, "
960 "the PHI should be removed!", PN);
961 Assert1(PN->getNumIncomingValues() == Preds.size(),
962 "PHINode should have one entry for each predecessor of its "
963 "parent basic block!", PN);
965 // Get and sort all incoming values in the PHI node...
967 Values.reserve(PN->getNumIncomingValues());
968 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
969 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
970 PN->getIncomingValue(i)));
971 std::sort(Values.begin(), Values.end());
973 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
974 // Check to make sure that if there is more than one entry for a
975 // particular basic block in this PHI node, that the incoming values are
978 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
979 Values[i].second == Values[i-1].second,
980 "PHI node has multiple entries for the same basic block with "
981 "different incoming values!", PN, Values[i].first,
982 Values[i].second, Values[i-1].second);
984 // Check to make sure that the predecessors and PHI node entries are
986 Assert3(Values[i].first == Preds[i],
987 "PHI node entries do not match predecessors!", PN,
988 Values[i].first, Preds[i]);
994 void Verifier::visitTerminatorInst(TerminatorInst &I) {
995 // Ensure that terminators only exist at the end of the basic block.
996 Assert1(&I == I.getParent()->getTerminator(),
997 "Terminator found in the middle of a basic block!", I.getParent());
1001 void Verifier::visitBranchInst(BranchInst &BI) {
1002 if (BI.isConditional()) {
1003 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1004 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1006 visitTerminatorInst(BI);
1009 void Verifier::visitReturnInst(ReturnInst &RI) {
1010 Function *F = RI.getParent()->getParent();
1011 unsigned N = RI.getNumOperands();
1012 if (F->getReturnType()->isVoidTy())
1014 "Found return instr that returns non-void in Function of void "
1015 "return type!", &RI, F->getReturnType());
1017 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1018 "Function return type does not match operand "
1019 "type of return inst!", &RI, F->getReturnType());
1021 // Check to make sure that the return value has necessary properties for
1023 visitTerminatorInst(RI);
1026 void Verifier::visitSwitchInst(SwitchInst &SI) {
1027 // Check to make sure that all of the constants in the switch instruction
1028 // have the same type as the switched-on value.
1029 Type *SwitchTy = SI.getCondition()->getType();
1030 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
1031 IntegersSubsetToBB Mapping;
1032 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
1033 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1034 IntegersSubset CaseRanges = i.getCaseValueEx();
1035 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
1036 IntegersSubset::Range r = CaseRanges.getItem(ri);
1037 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
1038 "Switch constants must all be same type as switch value!", &SI);
1039 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
1040 "Switch constants must all be same type as switch value!", &SI);
1042 RangeSetMap[r] = i.getCaseIndex();
1046 IntegersSubsetToBB::RangeIterator errItem;
1047 if (!Mapping.verify(errItem)) {
1048 unsigned CaseIndex = RangeSetMap[errItem->first];
1049 SwitchInst::CaseIt i(&SI, CaseIndex);
1050 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
1053 visitTerminatorInst(SI);
1056 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1057 Assert1(BI.getAddress()->getType()->isPointerTy(),
1058 "Indirectbr operand must have pointer type!", &BI);
1059 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1060 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1061 "Indirectbr destinations must all have pointer type!", &BI);
1063 visitTerminatorInst(BI);
1066 void Verifier::visitSelectInst(SelectInst &SI) {
1067 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1069 "Invalid operands for select instruction!", &SI);
1071 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1072 "Select values must have same type as select instruction!", &SI);
1073 visitInstruction(SI);
1076 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1077 /// a pass, if any exist, it's an error.
1079 void Verifier::visitUserOp1(Instruction &I) {
1080 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1083 void Verifier::visitTruncInst(TruncInst &I) {
1084 // Get the source and destination types
1085 Type *SrcTy = I.getOperand(0)->getType();
1086 Type *DestTy = I.getType();
1088 // Get the size of the types in bits, we'll need this later
1089 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1090 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1092 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1093 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1094 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1095 "trunc source and destination must both be a vector or neither", &I);
1096 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1098 visitInstruction(I);
1101 void Verifier::visitZExtInst(ZExtInst &I) {
1102 // Get the source and destination types
1103 Type *SrcTy = I.getOperand(0)->getType();
1104 Type *DestTy = I.getType();
1106 // Get the size of the types in bits, we'll need this later
1107 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1108 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1109 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1110 "zext source and destination must both be a vector or neither", &I);
1111 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1112 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1114 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1116 visitInstruction(I);
1119 void Verifier::visitSExtInst(SExtInst &I) {
1120 // Get the source and destination types
1121 Type *SrcTy = I.getOperand(0)->getType();
1122 Type *DestTy = I.getType();
1124 // Get the size of the types in bits, we'll need this later
1125 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1126 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1128 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1129 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1130 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1131 "sext source and destination must both be a vector or neither", &I);
1132 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1134 visitInstruction(I);
1137 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1138 // Get the source and destination types
1139 Type *SrcTy = I.getOperand(0)->getType();
1140 Type *DestTy = I.getType();
1141 // Get the size of the types in bits, we'll need this later
1142 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1143 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1145 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1146 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1147 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1148 "fptrunc source and destination must both be a vector or neither",&I);
1149 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1151 visitInstruction(I);
1154 void Verifier::visitFPExtInst(FPExtInst &I) {
1155 // Get the source and destination types
1156 Type *SrcTy = I.getOperand(0)->getType();
1157 Type *DestTy = I.getType();
1159 // Get the size of the types in bits, we'll need this later
1160 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1161 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1163 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1164 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1165 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1166 "fpext source and destination must both be a vector or neither", &I);
1167 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1169 visitInstruction(I);
1172 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1173 // Get the source and destination types
1174 Type *SrcTy = I.getOperand(0)->getType();
1175 Type *DestTy = I.getType();
1177 bool SrcVec = SrcTy->isVectorTy();
1178 bool DstVec = DestTy->isVectorTy();
1180 Assert1(SrcVec == DstVec,
1181 "UIToFP source and dest must both be vector or scalar", &I);
1182 Assert1(SrcTy->isIntOrIntVectorTy(),
1183 "UIToFP source must be integer or integer vector", &I);
1184 Assert1(DestTy->isFPOrFPVectorTy(),
1185 "UIToFP result must be FP or FP vector", &I);
1187 if (SrcVec && DstVec)
1188 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1189 cast<VectorType>(DestTy)->getNumElements(),
1190 "UIToFP source and dest vector length mismatch", &I);
1192 visitInstruction(I);
1195 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1196 // Get the source and destination types
1197 Type *SrcTy = I.getOperand(0)->getType();
1198 Type *DestTy = I.getType();
1200 bool SrcVec = SrcTy->isVectorTy();
1201 bool DstVec = DestTy->isVectorTy();
1203 Assert1(SrcVec == DstVec,
1204 "SIToFP source and dest must both be vector or scalar", &I);
1205 Assert1(SrcTy->isIntOrIntVectorTy(),
1206 "SIToFP source must be integer or integer vector", &I);
1207 Assert1(DestTy->isFPOrFPVectorTy(),
1208 "SIToFP result must be FP or FP vector", &I);
1210 if (SrcVec && DstVec)
1211 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1212 cast<VectorType>(DestTy)->getNumElements(),
1213 "SIToFP source and dest vector length mismatch", &I);
1215 visitInstruction(I);
1218 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1219 // Get the source and destination types
1220 Type *SrcTy = I.getOperand(0)->getType();
1221 Type *DestTy = I.getType();
1223 bool SrcVec = SrcTy->isVectorTy();
1224 bool DstVec = DestTy->isVectorTy();
1226 Assert1(SrcVec == DstVec,
1227 "FPToUI source and dest must both be vector or scalar", &I);
1228 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1230 Assert1(DestTy->isIntOrIntVectorTy(),
1231 "FPToUI result must be integer or integer vector", &I);
1233 if (SrcVec && DstVec)
1234 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1235 cast<VectorType>(DestTy)->getNumElements(),
1236 "FPToUI source and dest vector length mismatch", &I);
1238 visitInstruction(I);
1241 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1242 // Get the source and destination types
1243 Type *SrcTy = I.getOperand(0)->getType();
1244 Type *DestTy = I.getType();
1246 bool SrcVec = SrcTy->isVectorTy();
1247 bool DstVec = DestTy->isVectorTy();
1249 Assert1(SrcVec == DstVec,
1250 "FPToSI source and dest must both be vector or scalar", &I);
1251 Assert1(SrcTy->isFPOrFPVectorTy(),
1252 "FPToSI source must be FP or FP vector", &I);
1253 Assert1(DestTy->isIntOrIntVectorTy(),
1254 "FPToSI result must be integer or integer vector", &I);
1256 if (SrcVec && DstVec)
1257 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1258 cast<VectorType>(DestTy)->getNumElements(),
1259 "FPToSI source and dest vector length mismatch", &I);
1261 visitInstruction(I);
1264 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1265 // Get the source and destination types
1266 Type *SrcTy = I.getOperand(0)->getType();
1267 Type *DestTy = I.getType();
1269 Assert1(SrcTy->getScalarType()->isPointerTy(),
1270 "PtrToInt source must be pointer", &I);
1271 Assert1(DestTy->getScalarType()->isIntegerTy(),
1272 "PtrToInt result must be integral", &I);
1273 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1274 "PtrToInt type mismatch", &I);
1276 if (SrcTy->isVectorTy()) {
1277 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1278 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1279 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1280 "PtrToInt Vector width mismatch", &I);
1283 visitInstruction(I);
1286 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1287 // Get the source and destination types
1288 Type *SrcTy = I.getOperand(0)->getType();
1289 Type *DestTy = I.getType();
1291 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1292 "IntToPtr source must be an integral", &I);
1293 Assert1(DestTy->getScalarType()->isPointerTy(),
1294 "IntToPtr result must be a pointer",&I);
1295 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1296 "IntToPtr type mismatch", &I);
1297 if (SrcTy->isVectorTy()) {
1298 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1299 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1300 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1301 "IntToPtr Vector width mismatch", &I);
1303 visitInstruction(I);
1306 void Verifier::visitBitCastInst(BitCastInst &I) {
1307 // Get the source and destination types
1308 Type *SrcTy = I.getOperand(0)->getType();
1309 Type *DestTy = I.getType();
1311 // Get the size of the types in bits, we'll need this later
1312 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1313 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1315 // BitCast implies a no-op cast of type only. No bits change.
1316 // However, you can't cast pointers to anything but pointers.
1317 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1318 "Bitcast requires both operands to be pointer or neither", &I);
1319 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1321 // Disallow aggregates.
1322 Assert1(!SrcTy->isAggregateType(),
1323 "Bitcast operand must not be aggregate", &I);
1324 Assert1(!DestTy->isAggregateType(),
1325 "Bitcast type must not be aggregate", &I);
1327 visitInstruction(I);
1330 /// visitPHINode - Ensure that a PHI node is well formed.
1332 void Verifier::visitPHINode(PHINode &PN) {
1333 // Ensure that the PHI nodes are all grouped together at the top of the block.
1334 // This can be tested by checking whether the instruction before this is
1335 // either nonexistent (because this is begin()) or is a PHI node. If not,
1336 // then there is some other instruction before a PHI.
1337 Assert2(&PN == &PN.getParent()->front() ||
1338 isa<PHINode>(--BasicBlock::iterator(&PN)),
1339 "PHI nodes not grouped at top of basic block!",
1340 &PN, PN.getParent());
1342 // Check that all of the values of the PHI node have the same type as the
1343 // result, and that the incoming blocks are really basic blocks.
1344 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1345 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1346 "PHI node operands are not the same type as the result!", &PN);
1349 // All other PHI node constraints are checked in the visitBasicBlock method.
1351 visitInstruction(PN);
1354 void Verifier::VerifyCallSite(CallSite CS) {
1355 Instruction *I = CS.getInstruction();
1357 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1358 "Called function must be a pointer!", I);
1359 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1361 Assert1(FPTy->getElementType()->isFunctionTy(),
1362 "Called function is not pointer to function type!", I);
1363 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1365 // Verify that the correct number of arguments are being passed
1366 if (FTy->isVarArg())
1367 Assert1(CS.arg_size() >= FTy->getNumParams(),
1368 "Called function requires more parameters than were provided!",I);
1370 Assert1(CS.arg_size() == FTy->getNumParams(),
1371 "Incorrect number of arguments passed to called function!", I);
1373 // Verify that all arguments to the call match the function type.
1374 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1375 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1376 "Call parameter type does not match function signature!",
1377 CS.getArgument(i), FTy->getParamType(i), I);
1379 AttributeSet Attrs = CS.getAttributes();
1381 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1382 "Attribute after last parameter!", I);
1384 // Verify call attributes.
1385 VerifyFunctionAttrs(FTy, Attrs, I);
1387 if (FTy->isVarArg()) {
1388 // FIXME? is 'nest' even legal here?
1389 bool SawNest = false;
1390 bool SawReturned = false;
1392 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1393 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1395 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1399 // Check attributes on the varargs part.
1400 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1401 Type *Ty = CS.getArgument(Idx-1)->getType();
1402 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1404 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1405 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1409 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1410 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1412 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1413 "Incompatible argument and return types for 'returned' "
1418 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1419 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1423 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1424 if (CS.getCalledFunction() == 0 ||
1425 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1426 for (FunctionType::param_iterator PI = FTy->param_begin(),
1427 PE = FTy->param_end(); PI != PE; ++PI)
1428 Assert1(!(*PI)->isMetadataTy(),
1429 "Function has metadata parameter but isn't an intrinsic", I);
1432 visitInstruction(*I);
1435 void Verifier::visitCallInst(CallInst &CI) {
1436 VerifyCallSite(&CI);
1438 if (Function *F = CI.getCalledFunction())
1439 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1440 visitIntrinsicFunctionCall(ID, CI);
1443 void Verifier::visitInvokeInst(InvokeInst &II) {
1444 VerifyCallSite(&II);
1446 // Verify that there is a landingpad instruction as the first non-PHI
1447 // instruction of the 'unwind' destination.
1448 Assert1(II.getUnwindDest()->isLandingPad(),
1449 "The unwind destination does not have a landingpad instruction!",&II);
1451 visitTerminatorInst(II);
1454 /// visitBinaryOperator - Check that both arguments to the binary operator are
1455 /// of the same type!
1457 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1458 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1459 "Both operands to a binary operator are not of the same type!", &B);
1461 switch (B.getOpcode()) {
1462 // Check that integer arithmetic operators are only used with
1463 // integral operands.
1464 case Instruction::Add:
1465 case Instruction::Sub:
1466 case Instruction::Mul:
1467 case Instruction::SDiv:
1468 case Instruction::UDiv:
1469 case Instruction::SRem:
1470 case Instruction::URem:
1471 Assert1(B.getType()->isIntOrIntVectorTy(),
1472 "Integer arithmetic operators only work with integral types!", &B);
1473 Assert1(B.getType() == B.getOperand(0)->getType(),
1474 "Integer arithmetic operators must have same type "
1475 "for operands and result!", &B);
1477 // Check that floating-point arithmetic operators are only used with
1478 // floating-point operands.
1479 case Instruction::FAdd:
1480 case Instruction::FSub:
1481 case Instruction::FMul:
1482 case Instruction::FDiv:
1483 case Instruction::FRem:
1484 Assert1(B.getType()->isFPOrFPVectorTy(),
1485 "Floating-point arithmetic operators only work with "
1486 "floating-point types!", &B);
1487 Assert1(B.getType() == B.getOperand(0)->getType(),
1488 "Floating-point arithmetic operators must have same type "
1489 "for operands and result!", &B);
1491 // Check that logical operators are only used with integral operands.
1492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor:
1495 Assert1(B.getType()->isIntOrIntVectorTy(),
1496 "Logical operators only work with integral types!", &B);
1497 Assert1(B.getType() == B.getOperand(0)->getType(),
1498 "Logical operators must have same type for operands and result!",
1501 case Instruction::Shl:
1502 case Instruction::LShr:
1503 case Instruction::AShr:
1504 Assert1(B.getType()->isIntOrIntVectorTy(),
1505 "Shifts only work with integral types!", &B);
1506 Assert1(B.getType() == B.getOperand(0)->getType(),
1507 "Shift return type must be same as operands!", &B);
1510 llvm_unreachable("Unknown BinaryOperator opcode!");
1513 visitInstruction(B);
1516 void Verifier::visitICmpInst(ICmpInst &IC) {
1517 // Check that the operands are the same type
1518 Type *Op0Ty = IC.getOperand(0)->getType();
1519 Type *Op1Ty = IC.getOperand(1)->getType();
1520 Assert1(Op0Ty == Op1Ty,
1521 "Both operands to ICmp instruction are not of the same type!", &IC);
1522 // Check that the operands are the right type
1523 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1524 "Invalid operand types for ICmp instruction", &IC);
1525 // Check that the predicate is valid.
1526 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1527 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1528 "Invalid predicate in ICmp instruction!", &IC);
1530 visitInstruction(IC);
1533 void Verifier::visitFCmpInst(FCmpInst &FC) {
1534 // Check that the operands are the same type
1535 Type *Op0Ty = FC.getOperand(0)->getType();
1536 Type *Op1Ty = FC.getOperand(1)->getType();
1537 Assert1(Op0Ty == Op1Ty,
1538 "Both operands to FCmp instruction are not of the same type!", &FC);
1539 // Check that the operands are the right type
1540 Assert1(Op0Ty->isFPOrFPVectorTy(),
1541 "Invalid operand types for FCmp instruction", &FC);
1542 // Check that the predicate is valid.
1543 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1544 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1545 "Invalid predicate in FCmp instruction!", &FC);
1547 visitInstruction(FC);
1550 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1551 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1553 "Invalid extractelement operands!", &EI);
1554 visitInstruction(EI);
1557 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1558 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1561 "Invalid insertelement operands!", &IE);
1562 visitInstruction(IE);
1565 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1566 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1568 "Invalid shufflevector operands!", &SV);
1569 visitInstruction(SV);
1572 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1573 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1575 Assert1(isa<PointerType>(TargetTy),
1576 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1577 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1578 "GEP into unsized type!", &GEP);
1579 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1580 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1583 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1585 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1586 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1588 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1589 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1590 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1592 if (GEP.getPointerOperandType()->isVectorTy()) {
1593 // Additional checks for vector GEPs.
1594 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1595 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1596 "Vector GEP result width doesn't match operand's", &GEP);
1597 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1598 Type *IndexTy = Idxs[i]->getType();
1599 Assert1(IndexTy->isVectorTy(),
1600 "Vector GEP must have vector indices!", &GEP);
1601 unsigned IndexWidth = IndexTy->getVectorNumElements();
1602 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1605 visitInstruction(GEP);
1608 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1609 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1612 void Verifier::visitLoadInst(LoadInst &LI) {
1613 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1614 Assert1(PTy, "Load operand must be a pointer.", &LI);
1615 Type *ElTy = PTy->getElementType();
1616 Assert2(ElTy == LI.getType(),
1617 "Load result type does not match pointer operand type!", &LI, ElTy);
1618 if (LI.isAtomic()) {
1619 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1620 "Load cannot have Release ordering", &LI);
1621 Assert1(LI.getAlignment() != 0,
1622 "Atomic load must specify explicit alignment", &LI);
1623 if (!ElTy->isPointerTy()) {
1624 Assert2(ElTy->isIntegerTy(),
1625 "atomic store operand must have integer type!",
1627 unsigned Size = ElTy->getPrimitiveSizeInBits();
1628 Assert2(Size >= 8 && !(Size & (Size - 1)),
1629 "atomic store operand must be power-of-two byte-sized integer",
1633 Assert1(LI.getSynchScope() == CrossThread,
1634 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1637 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1638 unsigned NumOperands = Range->getNumOperands();
1639 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1640 unsigned NumRanges = NumOperands / 2;
1641 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1643 ConstantRange LastRange(1); // Dummy initial value
1644 for (unsigned i = 0; i < NumRanges; ++i) {
1645 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1646 Assert1(Low, "The lower limit must be an integer!", Low);
1647 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1648 Assert1(High, "The upper limit must be an integer!", High);
1649 Assert1(High->getType() == Low->getType() &&
1650 High->getType() == ElTy, "Range types must match load type!",
1653 APInt HighV = High->getValue();
1654 APInt LowV = Low->getValue();
1655 ConstantRange CurRange(LowV, HighV);
1656 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1657 "Range must not be empty!", Range);
1659 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1660 "Intervals are overlapping", Range);
1661 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1663 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1666 LastRange = ConstantRange(LowV, HighV);
1668 if (NumRanges > 2) {
1670 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1672 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1673 ConstantRange FirstRange(FirstLow, FirstHigh);
1674 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1675 "Intervals are overlapping", Range);
1676 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1683 visitInstruction(LI);
1686 void Verifier::visitStoreInst(StoreInst &SI) {
1687 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1688 Assert1(PTy, "Store operand must be a pointer.", &SI);
1689 Type *ElTy = PTy->getElementType();
1690 Assert2(ElTy == SI.getOperand(0)->getType(),
1691 "Stored value type does not match pointer operand type!",
1693 if (SI.isAtomic()) {
1694 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1695 "Store cannot have Acquire ordering", &SI);
1696 Assert1(SI.getAlignment() != 0,
1697 "Atomic store must specify explicit alignment", &SI);
1698 if (!ElTy->isPointerTy()) {
1699 Assert2(ElTy->isIntegerTy(),
1700 "atomic store operand must have integer type!",
1702 unsigned Size = ElTy->getPrimitiveSizeInBits();
1703 Assert2(Size >= 8 && !(Size & (Size - 1)),
1704 "atomic store operand must be power-of-two byte-sized integer",
1708 Assert1(SI.getSynchScope() == CrossThread,
1709 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1711 visitInstruction(SI);
1714 void Verifier::visitAllocaInst(AllocaInst &AI) {
1715 PointerType *PTy = AI.getType();
1716 Assert1(PTy->getAddressSpace() == 0,
1717 "Allocation instruction pointer not in the generic address space!",
1719 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1721 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1722 "Alloca array size must have integer type", &AI);
1723 visitInstruction(AI);
1726 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1727 Assert1(CXI.getOrdering() != NotAtomic,
1728 "cmpxchg instructions must be atomic.", &CXI);
1729 Assert1(CXI.getOrdering() != Unordered,
1730 "cmpxchg instructions cannot be unordered.", &CXI);
1731 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1732 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1733 Type *ElTy = PTy->getElementType();
1734 Assert2(ElTy->isIntegerTy(),
1735 "cmpxchg operand must have integer type!",
1737 unsigned Size = ElTy->getPrimitiveSizeInBits();
1738 Assert2(Size >= 8 && !(Size & (Size - 1)),
1739 "cmpxchg operand must be power-of-two byte-sized integer",
1741 Assert2(ElTy == CXI.getOperand(1)->getType(),
1742 "Expected value type does not match pointer operand type!",
1744 Assert2(ElTy == CXI.getOperand(2)->getType(),
1745 "Stored value type does not match pointer operand type!",
1747 visitInstruction(CXI);
1750 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1751 Assert1(RMWI.getOrdering() != NotAtomic,
1752 "atomicrmw instructions must be atomic.", &RMWI);
1753 Assert1(RMWI.getOrdering() != Unordered,
1754 "atomicrmw instructions cannot be unordered.", &RMWI);
1755 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1756 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1757 Type *ElTy = PTy->getElementType();
1758 Assert2(ElTy->isIntegerTy(),
1759 "atomicrmw operand must have integer type!",
1761 unsigned Size = ElTy->getPrimitiveSizeInBits();
1762 Assert2(Size >= 8 && !(Size & (Size - 1)),
1763 "atomicrmw operand must be power-of-two byte-sized integer",
1765 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1766 "Argument value type does not match pointer operand type!",
1768 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1769 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1770 "Invalid binary operation!", &RMWI);
1771 visitInstruction(RMWI);
1774 void Verifier::visitFenceInst(FenceInst &FI) {
1775 const AtomicOrdering Ordering = FI.getOrdering();
1776 Assert1(Ordering == Acquire || Ordering == Release ||
1777 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1778 "fence instructions may only have "
1779 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1780 visitInstruction(FI);
1783 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1784 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1785 EVI.getIndices()) ==
1787 "Invalid ExtractValueInst operands!", &EVI);
1789 visitInstruction(EVI);
1792 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1793 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1794 IVI.getIndices()) ==
1795 IVI.getOperand(1)->getType(),
1796 "Invalid InsertValueInst operands!", &IVI);
1798 visitInstruction(IVI);
1801 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1802 BasicBlock *BB = LPI.getParent();
1804 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1806 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1807 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1809 // The landingpad instruction defines its parent as a landing pad block. The
1810 // landing pad block may be branched to only by the unwind edge of an invoke.
1811 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1812 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1813 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1814 "Block containing LandingPadInst must be jumped to "
1815 "only by the unwind edge of an invoke.", &LPI);
1818 // The landingpad instruction must be the first non-PHI instruction in the
1820 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1821 "LandingPadInst not the first non-PHI instruction in the block.",
1824 // The personality functions for all landingpad instructions within the same
1825 // function should match.
1827 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1828 "Personality function doesn't match others in function", &LPI);
1829 PersonalityFn = LPI.getPersonalityFn();
1831 // All operands must be constants.
1832 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1834 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1835 Value *Clause = LPI.getClause(i);
1836 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1837 if (LPI.isCatch(i)) {
1838 Assert1(isa<PointerType>(Clause->getType()),
1839 "Catch operand does not have pointer type!", &LPI);
1841 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1842 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1843 "Filter operand is not an array of constants!", &LPI);
1847 visitInstruction(LPI);
1850 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1851 Instruction *Op = cast<Instruction>(I.getOperand(i));
1852 // If the we have an invalid invoke, don't try to compute the dominance.
1853 // We already reject it in the invoke specific checks and the dominance
1854 // computation doesn't handle multiple edges.
1855 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1856 if (II->getNormalDest() == II->getUnwindDest())
1860 const Use &U = I.getOperandUse(i);
1861 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1862 "Instruction does not dominate all uses!", Op, &I);
1865 /// verifyInstruction - Verify that an instruction is well formed.
1867 void Verifier::visitInstruction(Instruction &I) {
1868 BasicBlock *BB = I.getParent();
1869 Assert1(BB, "Instruction not embedded in basic block!", &I);
1871 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1872 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1874 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1875 "Only PHI nodes may reference their own value!", &I);
1878 // Check that void typed values don't have names
1879 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1880 "Instruction has a name, but provides a void value!", &I);
1882 // Check that the return value of the instruction is either void or a legal
1884 Assert1(I.getType()->isVoidTy() ||
1885 I.getType()->isFirstClassType(),
1886 "Instruction returns a non-scalar type!", &I);
1888 // Check that the instruction doesn't produce metadata. Calls are already
1889 // checked against the callee type.
1890 Assert1(!I.getType()->isMetadataTy() ||
1891 isa<CallInst>(I) || isa<InvokeInst>(I),
1892 "Invalid use of metadata!", &I);
1894 // Check that all uses of the instruction, if they are instructions
1895 // themselves, actually have parent basic blocks. If the use is not an
1896 // instruction, it is an error!
1897 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1899 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1900 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1901 " embedded in a basic block!", &I, Used);
1903 CheckFailed("Use of instruction is not an instruction!", *UI);
1908 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1909 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1911 // Check to make sure that only first-class-values are operands to
1913 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1914 Assert1(0, "Instruction operands must be first-class values!", &I);
1917 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1918 // Check to make sure that the "address of" an intrinsic function is never
1920 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1921 "Cannot take the address of an intrinsic!", &I);
1922 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1923 F->getIntrinsicID() == Intrinsic::donothing,
1924 "Cannot invoke an intrinsinc other than donothing", &I);
1925 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1927 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1928 Assert1(OpBB->getParent() == BB->getParent(),
1929 "Referring to a basic block in another function!", &I);
1930 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1931 Assert1(OpArg->getParent() == BB->getParent(),
1932 "Referring to an argument in another function!", &I);
1933 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1934 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1936 } else if (isa<Instruction>(I.getOperand(i))) {
1937 verifyDominatesUse(I, i);
1938 } else if (isa<InlineAsm>(I.getOperand(i))) {
1939 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1940 (i + 3 == e && isa<InvokeInst>(I)),
1941 "Cannot take the address of an inline asm!", &I);
1945 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1946 Assert1(I.getType()->isFPOrFPVectorTy(),
1947 "fpmath requires a floating point result!", &I);
1948 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1949 Value *Op0 = MD->getOperand(0);
1950 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1951 APFloat Accuracy = CFP0->getValueAPF();
1952 Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
1953 "fpmath accuracy not a positive number!", &I);
1955 Assert1(false, "invalid fpmath accuracy!", &I);
1959 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1960 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1962 InstsInThisBlock.insert(&I);
1965 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
1966 /// intrinsic argument or return value) matches the type constraints specified
1967 /// by the .td file (e.g. an "any integer" argument really is an integer).
1969 /// This return true on error but does not print a message.
1970 bool Verifier::VerifyIntrinsicType(Type *Ty,
1971 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1972 SmallVectorImpl<Type*> &ArgTys) {
1973 using namespace Intrinsic;
1975 // If we ran out of descriptors, there are too many arguments.
1976 if (Infos.empty()) return true;
1977 IITDescriptor D = Infos.front();
1978 Infos = Infos.slice(1);
1981 case IITDescriptor::Void: return !Ty->isVoidTy();
1982 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1983 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1984 case IITDescriptor::Half: return !Ty->isHalfTy();
1985 case IITDescriptor::Float: return !Ty->isFloatTy();
1986 case IITDescriptor::Double: return !Ty->isDoubleTy();
1987 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1988 case IITDescriptor::Vector: {
1989 VectorType *VT = dyn_cast<VectorType>(Ty);
1990 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
1991 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
1993 case IITDescriptor::Pointer: {
1994 PointerType *PT = dyn_cast<PointerType>(Ty);
1995 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1996 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
1999 case IITDescriptor::Struct: {
2000 StructType *ST = dyn_cast<StructType>(Ty);
2001 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2004 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2005 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2010 case IITDescriptor::Argument:
2011 // Two cases here - If this is the second occurrence of an argument, verify
2012 // that the later instance matches the previous instance.
2013 if (D.getArgumentNumber() < ArgTys.size())
2014 return Ty != ArgTys[D.getArgumentNumber()];
2016 // Otherwise, if this is the first instance of an argument, record it and
2017 // verify the "Any" kind.
2018 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2019 ArgTys.push_back(Ty);
2021 switch (D.getArgumentKind()) {
2022 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2023 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2024 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2025 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2027 llvm_unreachable("all argument kinds not covered");
2029 case IITDescriptor::ExtendVecArgument:
2030 // This may only be used when referring to a previous vector argument.
2031 return D.getArgumentNumber() >= ArgTys.size() ||
2032 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2033 VectorType::getExtendedElementVectorType(
2034 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2036 case IITDescriptor::TruncVecArgument:
2037 // This may only be used when referring to a previous vector argument.
2038 return D.getArgumentNumber() >= ArgTys.size() ||
2039 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2040 VectorType::getTruncatedElementVectorType(
2041 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2043 llvm_unreachable("unhandled");
2046 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2048 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2049 Function *IF = CI.getCalledFunction();
2050 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2053 // Verify that the intrinsic prototype lines up with what the .td files
2055 FunctionType *IFTy = IF->getFunctionType();
2056 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
2058 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2059 getIntrinsicInfoTableEntries(ID, Table);
2060 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2062 SmallVector<Type *, 4> ArgTys;
2063 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2064 "Intrinsic has incorrect return type!", IF);
2065 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2066 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2067 "Intrinsic has incorrect argument type!", IF);
2068 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2070 // Now that we have the intrinsic ID and the actual argument types (and we
2071 // know they are legal for the intrinsic!) get the intrinsic name through the
2072 // usual means. This allows us to verify the mangling of argument types into
2074 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2075 "Intrinsic name not mangled correctly for type arguments!", IF);
2077 // If the intrinsic takes MDNode arguments, verify that they are either global
2078 // or are local to *this* function.
2079 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2080 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2081 visitMDNode(*MD, CI.getParent()->getParent());
2086 case Intrinsic::ctlz: // llvm.ctlz
2087 case Intrinsic::cttz: // llvm.cttz
2088 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2089 "is_zero_undef argument of bit counting intrinsics must be a "
2090 "constant int", &CI);
2092 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2093 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2094 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2095 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2096 Assert1(MD->getNumOperands() == 1,
2097 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2099 case Intrinsic::memcpy:
2100 case Intrinsic::memmove:
2101 case Intrinsic::memset:
2102 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2103 "alignment argument of memory intrinsics must be a constant int",
2105 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2106 "isvolatile argument of memory intrinsics must be a constant int",
2109 case Intrinsic::gcroot:
2110 case Intrinsic::gcwrite:
2111 case Intrinsic::gcread:
2112 if (ID == Intrinsic::gcroot) {
2114 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2115 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2116 Assert1(isa<Constant>(CI.getArgOperand(1)),
2117 "llvm.gcroot parameter #2 must be a constant.", &CI);
2118 if (!AI->getType()->getElementType()->isPointerTy()) {
2119 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2120 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2121 "or argument #2 must be a non-null constant.", &CI);
2125 Assert1(CI.getParent()->getParent()->hasGC(),
2126 "Enclosing function does not use GC.", &CI);
2128 case Intrinsic::init_trampoline:
2129 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2130 "llvm.init_trampoline parameter #2 must resolve to a function.",
2133 case Intrinsic::prefetch:
2134 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2135 isa<ConstantInt>(CI.getArgOperand(2)) &&
2136 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2137 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2138 "invalid arguments to llvm.prefetch",
2141 case Intrinsic::stackprotector:
2142 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2143 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2146 case Intrinsic::lifetime_start:
2147 case Intrinsic::lifetime_end:
2148 case Intrinsic::invariant_start:
2149 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2150 "size argument of memory use markers must be a constant integer",
2153 case Intrinsic::invariant_end:
2154 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2155 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2160 //===----------------------------------------------------------------------===//
2161 // Implement the public interfaces to this file...
2162 //===----------------------------------------------------------------------===//
2164 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2165 return new Verifier(action);
2169 /// verifyFunction - Check a function for errors, printing messages on stderr.
2170 /// Return true if the function is corrupt.
2172 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2173 Function &F = const_cast<Function&>(f);
2174 assert(!F.isDeclaration() && "Cannot verify external functions");
2176 FunctionPassManager FPM(F.getParent());
2177 Verifier *V = new Verifier(action);
2183 /// verifyModule - Check a module for errors, printing messages on stderr.
2184 /// Return true if the module is corrupt.
2186 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2187 std::string *ErrorInfo) {
2189 Verifier *V = new Verifier(action);
2191 PM.run(const_cast<Module&>(M));
2193 if (ErrorInfo && V->Broken)
2194 *ErrorInfo = V->MessagesStr.str();