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/DerivedTypes.h"
60 #include "llvm/IR/InlineAsm.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/InstVisitor.h"
66 #include "llvm/Pass.h"
67 #include "llvm/PassManager.h"
68 #include "llvm/Support/CFG.h"
69 #include "llvm/Support/CallSite.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/ConstantRange.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/raw_ostream.h"
79 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
82 namespace { // Anonymous namespace for class
83 struct PreVerifier : public FunctionPass {
84 static char ID; // Pass ID, replacement for typeid
86 PreVerifier() : FunctionPass(ID) {
87 initializePreVerifierPass(*PassRegistry::getPassRegistry());
90 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 // Check that the prerequisites for successful DominatorTree construction
96 bool runOnFunction(Function &F) {
99 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
100 if (I->empty() || !I->back().isTerminator()) {
101 dbgs() << "Basic Block in function '" << F.getName()
102 << "' does not have terminator!\n";
103 WriteAsOperand(dbgs(), I, true);
110 report_fatal_error("Broken module, no Basic Block terminator!");
117 char PreVerifier::ID = 0;
118 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
120 static char &PreVerifyID = PreVerifier::ID;
123 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
124 static char ID; // Pass ID, replacement for typeid
125 bool Broken; // Is this module found to be broken?
126 VerifierFailureAction action;
127 // What to do if verification fails.
128 Module *Mod; // Module we are verifying right now
129 LLVMContext *Context; // Context within which we are verifying
130 DominatorTree *DT; // Dominator Tree, caution can be null!
132 std::string Messages;
133 raw_string_ostream MessagesStr;
135 /// InstInThisBlock - when verifying a basic block, keep track of all of the
136 /// instructions we have seen so far. This allows us to do efficient
137 /// dominance checks for the case when an instruction has an operand that is
138 /// an instruction in the same block.
139 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
141 /// MDNodes - keep track of the metadata nodes that have been checked
143 SmallPtrSet<MDNode *, 32> MDNodes;
145 /// PersonalityFn - The personality function referenced by the
146 /// LandingPadInsts. All LandingPadInsts within the same function must use
147 /// the same personality function.
148 const Value *PersonalityFn;
151 : FunctionPass(ID), Broken(false),
152 action(AbortProcessAction), Mod(0), Context(0), DT(0),
153 MessagesStr(Messages), PersonalityFn(0) {
154 initializeVerifierPass(*PassRegistry::getPassRegistry());
156 explicit Verifier(VerifierFailureAction ctn)
157 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
158 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
159 initializeVerifierPass(*PassRegistry::getPassRegistry());
162 bool doInitialization(Module &M) {
164 Context = &M.getContext();
166 // We must abort before returning back to the pass manager, or else the
167 // pass manager may try to run other passes on the broken module.
168 return abortIfBroken();
171 bool runOnFunction(Function &F) {
172 // Get dominator information if we are being run by PassManager
173 DT = &getAnalysis<DominatorTree>();
176 if (!Context) Context = &F.getContext();
179 InstsInThisBlock.clear();
182 // We must abort before returning back to the pass manager, or else the
183 // pass manager may try to run other passes on the broken module.
184 return abortIfBroken();
187 bool doFinalization(Module &M) {
188 // Scan through, checking all of the external function's linkage now...
189 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
190 visitGlobalValue(*I);
192 // Check to make sure function prototypes are okay.
193 if (I->isDeclaration()) visitFunction(*I);
196 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
198 visitGlobalVariable(*I);
200 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
202 visitGlobalAlias(*I);
204 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
205 E = M.named_metadata_end(); I != E; ++I)
206 visitNamedMDNode(*I);
210 // Verify Debug Info.
213 // If the module is broken, abort at this time.
214 return abortIfBroken();
217 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218 AU.setPreservesAll();
219 AU.addRequiredID(PreVerifyID);
220 AU.addRequired<DominatorTree>();
223 /// abortIfBroken - If the module is broken and we are supposed to abort on
224 /// this condition, do so.
226 bool abortIfBroken() {
227 if (!Broken) return false;
228 MessagesStr << "Broken module found, ";
230 case AbortProcessAction:
231 MessagesStr << "compilation aborted!\n";
232 dbgs() << MessagesStr.str();
233 // Client should choose different reaction if abort is not desired
235 case PrintMessageAction:
236 MessagesStr << "verification continues.\n";
237 dbgs() << MessagesStr.str();
239 case ReturnStatusAction:
240 MessagesStr << "compilation terminated.\n";
243 llvm_unreachable("Invalid action");
247 // Verification methods...
248 void visitGlobalValue(GlobalValue &GV);
249 void visitGlobalVariable(GlobalVariable &GV);
250 void visitGlobalAlias(GlobalAlias &GA);
251 void visitNamedMDNode(NamedMDNode &NMD);
252 void visitMDNode(MDNode &MD, Function *F);
253 void visitModuleFlags(Module &M);
254 void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
255 SmallVectorImpl<MDNode*> &Requirements);
256 void visitFunction(Function &F);
257 void visitBasicBlock(BasicBlock &BB);
258 using InstVisitor<Verifier>::visit;
260 void visit(Instruction &I);
262 void visitTruncInst(TruncInst &I);
263 void visitZExtInst(ZExtInst &I);
264 void visitSExtInst(SExtInst &I);
265 void visitFPTruncInst(FPTruncInst &I);
266 void visitFPExtInst(FPExtInst &I);
267 void visitFPToUIInst(FPToUIInst &I);
268 void visitFPToSIInst(FPToSIInst &I);
269 void visitUIToFPInst(UIToFPInst &I);
270 void visitSIToFPInst(SIToFPInst &I);
271 void visitIntToPtrInst(IntToPtrInst &I);
272 void visitPtrToIntInst(PtrToIntInst &I);
273 void visitBitCastInst(BitCastInst &I);
274 void visitPHINode(PHINode &PN);
275 void visitBinaryOperator(BinaryOperator &B);
276 void visitICmpInst(ICmpInst &IC);
277 void visitFCmpInst(FCmpInst &FC);
278 void visitExtractElementInst(ExtractElementInst &EI);
279 void visitInsertElementInst(InsertElementInst &EI);
280 void visitShuffleVectorInst(ShuffleVectorInst &EI);
281 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
282 void visitCallInst(CallInst &CI);
283 void visitInvokeInst(InvokeInst &II);
284 void visitGetElementPtrInst(GetElementPtrInst &GEP);
285 void visitLoadInst(LoadInst &LI);
286 void visitStoreInst(StoreInst &SI);
287 void verifyDominatesUse(Instruction &I, unsigned i);
288 void visitInstruction(Instruction &I);
289 void visitTerminatorInst(TerminatorInst &I);
290 void visitBranchInst(BranchInst &BI);
291 void visitReturnInst(ReturnInst &RI);
292 void visitSwitchInst(SwitchInst &SI);
293 void visitIndirectBrInst(IndirectBrInst &BI);
294 void visitSelectInst(SelectInst &SI);
295 void visitUserOp1(Instruction &I);
296 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
297 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
298 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
299 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
300 void visitFenceInst(FenceInst &FI);
301 void visitAllocaInst(AllocaInst &AI);
302 void visitExtractValueInst(ExtractValueInst &EVI);
303 void visitInsertValueInst(InsertValueInst &IVI);
304 void visitLandingPadInst(LandingPadInst &LPI);
306 void VerifyCallSite(CallSite CS);
307 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
308 int VT, unsigned ArgNo, std::string &Suffix);
309 bool VerifyIntrinsicType(Type *Ty,
310 ArrayRef<Intrinsic::IITDescriptor> &Infos,
311 SmallVectorImpl<Type*> &ArgTys);
312 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
313 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
314 bool isFunction, const Value *V);
315 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
316 bool isReturnValue, const Value *V);
317 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
320 void verifyDebugInfo(Module &M);
322 void WriteValue(const Value *V) {
324 if (isa<Instruction>(V)) {
325 MessagesStr << *V << '\n';
327 WriteAsOperand(MessagesStr, V, true, Mod);
332 void WriteType(Type *T) {
334 MessagesStr << ' ' << *T;
338 // CheckFailed - A check failed, so print out the condition and the message
339 // that failed. This provides a nice place to put a breakpoint if you want
340 // to see why something is not correct.
341 void CheckFailed(const Twine &Message,
342 const Value *V1 = 0, const Value *V2 = 0,
343 const Value *V3 = 0, const Value *V4 = 0) {
344 MessagesStr << Message.str() << "\n";
352 void CheckFailed(const Twine &Message, const Value *V1,
353 Type *T2, const Value *V3 = 0) {
354 MessagesStr << Message.str() << "\n";
361 void CheckFailed(const Twine &Message, Type *T1,
362 Type *T2 = 0, Type *T3 = 0) {
363 MessagesStr << Message.str() << "\n";
370 } // End anonymous namespace
372 char Verifier::ID = 0;
373 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
374 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
375 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
376 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
378 // Assert - We know that cond should be true, if not print an error message.
379 #define Assert(C, M) \
380 do { if (!(C)) { CheckFailed(M); return; } } while (0)
381 #define Assert1(C, M, V1) \
382 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
383 #define Assert2(C, M, V1, V2) \
384 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
385 #define Assert3(C, M, V1, V2, V3) \
386 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
387 #define Assert4(C, M, V1, V2, V3, V4) \
388 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
390 void Verifier::visit(Instruction &I) {
391 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
392 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
393 InstVisitor<Verifier>::visit(I);
397 void Verifier::visitGlobalValue(GlobalValue &GV) {
398 Assert1(!GV.isDeclaration() ||
399 GV.isMaterializable() ||
400 GV.hasExternalLinkage() ||
401 GV.hasDLLImportLinkage() ||
402 GV.hasExternalWeakLinkage() ||
403 (isa<GlobalAlias>(GV) &&
404 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
405 "Global is external, but doesn't have external or dllimport or weak linkage!",
408 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
409 "Global is marked as dllimport, but not external", &GV);
411 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
412 "Only global variables can have appending linkage!", &GV);
414 if (GV.hasAppendingLinkage()) {
415 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
416 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
417 "Only global arrays can have appending linkage!", GVar);
420 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
421 "linkonce_odr_auto_hide can only have default visibility!",
425 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
426 if (GV.hasInitializer()) {
427 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
428 "Global variable initializer type does not match global "
429 "variable type!", &GV);
431 // If the global has common linkage, it must have a zero initializer and
432 // cannot be constant.
433 if (GV.hasCommonLinkage()) {
434 Assert1(GV.getInitializer()->isNullValue(),
435 "'common' global must have a zero initializer!", &GV);
436 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
440 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
441 GV.hasExternalWeakLinkage(),
442 "invalid linkage type for global declaration", &GV);
445 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
446 GV.getName() == "llvm.global_dtors")) {
447 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
448 "invalid linkage for intrinsic global variable", &GV);
449 // Don't worry about emitting an error for it not being an array,
450 // visitGlobalValue will complain on appending non-array.
451 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
452 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
453 PointerType *FuncPtrTy =
454 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
455 Assert1(STy && STy->getNumElements() == 2 &&
456 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
457 STy->getTypeAtIndex(1) == FuncPtrTy,
458 "wrong type for intrinsic global variable", &GV);
462 if (GV.hasName() && (GV.getName() == "llvm.used" ||
463 GV.getName() == "llvm.compiler.used")) {
464 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
465 "invalid linkage for intrinsic global variable", &GV);
466 Type *GVType = GV.getType()->getElementType();
467 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
468 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
469 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
470 if (GV.hasInitializer()) {
471 Constant *Init = GV.getInitializer();
472 ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
473 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
475 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
476 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
478 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
479 "invalid llvm.used member", V);
480 Assert1(V->hasName(), "members of llvm.used must be named", V);
486 visitGlobalValue(GV);
489 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
490 Assert1(!GA.getName().empty(),
491 "Alias name cannot be empty!", &GA);
492 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
494 "Alias should have external or external weak linkage!", &GA);
495 Assert1(GA.getAliasee(),
496 "Aliasee cannot be NULL!", &GA);
497 Assert1(GA.getType() == GA.getAliasee()->getType(),
498 "Alias and aliasee types should match!", &GA);
499 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
501 if (!isa<GlobalValue>(GA.getAliasee())) {
502 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
504 (CE->getOpcode() == Instruction::BitCast ||
505 CE->getOpcode() == Instruction::GetElementPtr) &&
506 isa<GlobalValue>(CE->getOperand(0)),
507 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
511 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
513 "Aliasing chain should end with function or global variable", &GA);
515 visitGlobalValue(GA);
518 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
519 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
520 MDNode *MD = NMD.getOperand(i);
524 Assert1(!MD->isFunctionLocal(),
525 "Named metadata operand cannot be function local!", MD);
530 void Verifier::visitMDNode(MDNode &MD, Function *F) {
531 // Only visit each node once. Metadata can be mutually recursive, so this
532 // avoids infinite recursion here, as well as being an optimization.
533 if (!MDNodes.insert(&MD))
536 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
537 Value *Op = MD.getOperand(i);
540 if (isa<Constant>(Op) || isa<MDString>(Op))
542 if (MDNode *N = dyn_cast<MDNode>(Op)) {
543 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
544 "Global metadata operand cannot be function local!", &MD, N);
548 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
550 // If this was an instruction, bb, or argument, verify that it is in the
551 // function that we expect.
552 Function *ActualF = 0;
553 if (Instruction *I = dyn_cast<Instruction>(Op))
554 ActualF = I->getParent()->getParent();
555 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
556 ActualF = BB->getParent();
557 else if (Argument *A = dyn_cast<Argument>(Op))
558 ActualF = A->getParent();
559 assert(ActualF && "Unimplemented function local metadata case!");
561 Assert2(ActualF == F, "function-local metadata used in wrong function",
566 void Verifier::visitModuleFlags(Module &M) {
567 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
570 // Scan each flag, and track the flags and requirements.
571 DenseMap<MDString*, MDNode*> SeenIDs;
572 SmallVector<MDNode*, 16> Requirements;
573 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
574 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
577 // Validate that the requirements in the module are valid.
578 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
579 MDNode *Requirement = Requirements[I];
580 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
581 Value *ReqValue = Requirement->getOperand(1);
583 MDNode *Op = SeenIDs.lookup(Flag);
585 CheckFailed("invalid requirement on flag, flag is not present in module",
590 if (Op->getOperand(2) != ReqValue) {
591 CheckFailed(("invalid requirement on flag, "
592 "flag does not have the required value"),
599 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
600 SmallVectorImpl<MDNode*> &Requirements) {
601 // Each module flag should have three arguments, the merge behavior (a
602 // constant int), the flag ID (an MDString), and the value.
603 Assert1(Op->getNumOperands() == 3,
604 "incorrect number of operands in module flag", Op);
605 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
606 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
608 "invalid behavior operand in module flag (expected constant integer)",
610 unsigned BehaviorValue = Behavior->getZExtValue();
612 "invalid ID operand in module flag (expected metadata string)",
615 // Sanity check the values for behaviors with additional requirements.
616 switch (BehaviorValue) {
619 "invalid behavior operand in module flag (unexpected constant)",
624 case Module::Warning:
625 case Module::Override:
626 // These behavior types accept any value.
629 case Module::Require: {
630 // The value should itself be an MDNode with two operands, a flag ID (an
631 // MDString), and a value.
632 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
633 Assert1(Value && Value->getNumOperands() == 2,
634 "invalid value for 'require' module flag (expected metadata pair)",
636 Assert1(isa<MDString>(Value->getOperand(0)),
637 ("invalid value for 'require' module flag "
638 "(first value operand should be a string)"),
639 Value->getOperand(0));
641 // Append it to the list of requirements, to check once all module flags are
643 Requirements.push_back(Value);
648 case Module::AppendUnique: {
649 // These behavior types require the operand be an MDNode.
650 Assert1(isa<MDNode>(Op->getOperand(2)),
651 "invalid value for 'append'-type module flag "
652 "(expected a metadata node)", Op->getOperand(2));
657 // Unless this is a "requires" flag, check the ID is unique.
658 if (BehaviorValue != Module::Require) {
659 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
661 "module flag identifiers must be unique (or of 'require' type)",
666 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
667 bool isFunction, const Value *V) {
669 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
670 if (Attrs.getSlotIndex(I) == Idx) {
675 assert(Slot != ~0U && "Attribute set inconsistency!");
677 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
679 if (I->isStringAttribute())
682 if (I->getKindAsEnum() == Attribute::NoReturn ||
683 I->getKindAsEnum() == Attribute::NoUnwind ||
684 I->getKindAsEnum() == Attribute::NoInline ||
685 I->getKindAsEnum() == Attribute::AlwaysInline ||
686 I->getKindAsEnum() == Attribute::OptimizeForSize ||
687 I->getKindAsEnum() == Attribute::StackProtect ||
688 I->getKindAsEnum() == Attribute::StackProtectReq ||
689 I->getKindAsEnum() == Attribute::StackProtectStrong ||
690 I->getKindAsEnum() == Attribute::NoRedZone ||
691 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
692 I->getKindAsEnum() == Attribute::Naked ||
693 I->getKindAsEnum() == Attribute::InlineHint ||
694 I->getKindAsEnum() == Attribute::StackAlignment ||
695 I->getKindAsEnum() == Attribute::UWTable ||
696 I->getKindAsEnum() == Attribute::NonLazyBind ||
697 I->getKindAsEnum() == Attribute::ReturnsTwice ||
698 I->getKindAsEnum() == Attribute::SanitizeAddress ||
699 I->getKindAsEnum() == Attribute::SanitizeThread ||
700 I->getKindAsEnum() == Attribute::SanitizeMemory ||
701 I->getKindAsEnum() == Attribute::MinSize ||
702 I->getKindAsEnum() == Attribute::NoDuplicate ||
703 I->getKindAsEnum() == Attribute::Builtin ||
704 I->getKindAsEnum() == Attribute::NoBuiltin ||
705 I->getKindAsEnum() == Attribute::Cold) {
707 CheckFailed("Attribute '" + I->getAsString() +
708 "' only applies to functions!", V);
711 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
712 I->getKindAsEnum() == Attribute::ReadNone) {
714 CheckFailed("Attribute '" + I->getAsString() +
715 "' does not apply to function returns");
718 } else if (isFunction) {
719 CheckFailed("Attribute '" + I->getAsString() +
720 "' does not apply to functions!", V);
726 // VerifyParameterAttrs - Check the given attributes for an argument or return
727 // value of the specified type. The value V is printed in error messages.
728 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
729 bool isReturnValue, const Value *V) {
730 if (!Attrs.hasAttributes(Idx))
733 VerifyAttributeTypes(Attrs, Idx, false, V);
736 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
737 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
738 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
739 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
740 !Attrs.hasAttribute(Idx, Attribute::Returned),
741 "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
742 "do not apply to return values!", V);
744 // Check for mutually incompatible attributes.
745 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
746 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
747 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
748 Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
749 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
750 Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
751 "'byval, nest, and sret' are incompatible!", V);
753 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
754 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
755 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
756 Attrs.hasAttribute(Idx, Attribute::InReg)) ||
757 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
758 Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
759 "'byval, nest, and inreg' are incompatible!", V);
761 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
762 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
763 "'sret and returned' are incompatible!", V);
765 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
766 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
767 "'zeroext and signext' are incompatible!", V);
769 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
770 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
771 "'readnone and readonly' are incompatible!", V);
773 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
774 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
775 "'noinline and alwaysinline' are incompatible!", V);
777 Assert1(!AttrBuilder(Attrs, Idx).
778 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
779 "Wrong types for attribute: " +
780 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
782 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
783 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
784 PTy->getElementType()->isSized(),
785 "Attribute 'byval' does not support unsized types!", V);
787 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
788 "Attribute 'byval' only applies to parameters with pointer type!",
792 // VerifyFunctionAttrs - Check parameter attributes against a function type.
793 // The value V is printed in error messages.
794 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
799 bool SawNest = false;
800 bool SawReturned = false;
802 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
803 unsigned Idx = Attrs.getSlotIndex(i);
807 Ty = FT->getReturnType();
808 else if (Idx-1 < FT->getNumParams())
809 Ty = FT->getParamType(Idx-1);
811 break; // VarArgs attributes, verified elsewhere.
813 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
818 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
819 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
823 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
824 Assert1(!SawReturned, "More than one parameter has attribute returned!",
826 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
827 "argument and return types for 'returned' attribute", V);
831 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
832 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
835 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
838 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
840 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
841 Attribute::ReadNone) &&
842 Attrs.hasAttribute(AttributeSet::FunctionIndex,
843 Attribute::ReadOnly)),
844 "Attributes 'readnone and readonly' are incompatible!", V);
846 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
847 Attribute::NoInline) &&
848 Attrs.hasAttribute(AttributeSet::FunctionIndex,
849 Attribute::AlwaysInline)),
850 "Attributes 'noinline and alwaysinline' are incompatible!", V);
853 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
854 if (Attrs.getNumSlots() == 0)
857 unsigned LastSlot = Attrs.getNumSlots() - 1;
858 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
859 if (LastIndex <= Params
860 || (LastIndex == AttributeSet::FunctionIndex
861 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
867 // visitFunction - Verify that a function is ok.
869 void Verifier::visitFunction(Function &F) {
870 // Check function arguments.
871 FunctionType *FT = F.getFunctionType();
872 unsigned NumArgs = F.arg_size();
874 Assert1(Context == &F.getContext(),
875 "Function context does not match Module context!", &F);
877 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
878 Assert2(FT->getNumParams() == NumArgs,
879 "# formal arguments must match # of arguments for function type!",
881 Assert1(F.getReturnType()->isFirstClassType() ||
882 F.getReturnType()->isVoidTy() ||
883 F.getReturnType()->isStructTy(),
884 "Functions cannot return aggregate values!", &F);
886 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
887 "Invalid struct return type!", &F);
889 AttributeSet Attrs = F.getAttributes();
891 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
892 "Attribute after last parameter!", &F);
894 // Check function attributes.
895 VerifyFunctionAttrs(FT, Attrs, &F);
897 // On function declarations/definitions, we do not support the builtin
898 // attribute. We do not check this in VerifyFunctionAttrs since that is
899 // checking for Attributes that can/can not ever be on functions.
900 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
902 "Attribute 'builtin' can only be applied to a callsite.", &F);
904 // Check that this function meets the restrictions on this calling convention.
905 switch (F.getCallingConv()) {
910 case CallingConv::Fast:
911 case CallingConv::Cold:
912 case CallingConv::X86_FastCall:
913 case CallingConv::X86_ThisCall:
914 case CallingConv::Intel_OCL_BI:
915 case CallingConv::PTX_Kernel:
916 case CallingConv::PTX_Device:
917 Assert1(!F.isVarArg(),
918 "Varargs functions must have C calling conventions!", &F);
922 bool isLLVMdotName = F.getName().size() >= 5 &&
923 F.getName().substr(0, 5) == "llvm.";
925 // Check that the argument values match the function type for this function...
927 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
929 Assert2(I->getType() == FT->getParamType(i),
930 "Argument value does not match function argument type!",
931 I, FT->getParamType(i));
932 Assert1(I->getType()->isFirstClassType(),
933 "Function arguments must have first-class types!", I);
935 Assert2(!I->getType()->isMetadataTy(),
936 "Function takes metadata but isn't an intrinsic", I, &F);
939 if (F.isMaterializable()) {
940 // Function has a body somewhere we can't see.
941 } else if (F.isDeclaration()) {
942 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
943 F.hasExternalWeakLinkage(),
944 "invalid linkage type for function declaration", &F);
946 // Verify that this function (which has a body) is not named "llvm.*". It
947 // is not legal to define intrinsics.
948 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
950 // Check the entry node
951 BasicBlock *Entry = &F.getEntryBlock();
952 Assert1(pred_begin(Entry) == pred_end(Entry),
953 "Entry block to function must not have predecessors!", Entry);
955 // The address of the entry block cannot be taken, unless it is dead.
956 if (Entry->hasAddressTaken()) {
957 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
958 "blockaddress may not be used with the entry block!", Entry);
962 // If this function is actually an intrinsic, verify that it is only used in
963 // direct call/invokes, never having its "address taken".
964 if (F.getIntrinsicID()) {
966 if (F.hasAddressTaken(&U))
967 Assert1(0, "Invalid user of intrinsic instruction!", U);
971 // verifyBasicBlock - Verify that a basic block is well formed...
973 void Verifier::visitBasicBlock(BasicBlock &BB) {
974 InstsInThisBlock.clear();
976 // Ensure that basic blocks have terminators!
977 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
979 // Check constraints that this basic block imposes on all of the PHI nodes in
981 if (isa<PHINode>(BB.front())) {
982 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
983 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
984 std::sort(Preds.begin(), Preds.end());
986 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
987 // Ensure that PHI nodes have at least one entry!
988 Assert1(PN->getNumIncomingValues() != 0,
989 "PHI nodes must have at least one entry. If the block is dead, "
990 "the PHI should be removed!", PN);
991 Assert1(PN->getNumIncomingValues() == Preds.size(),
992 "PHINode should have one entry for each predecessor of its "
993 "parent basic block!", PN);
995 // Get and sort all incoming values in the PHI node...
997 Values.reserve(PN->getNumIncomingValues());
998 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
999 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1000 PN->getIncomingValue(i)));
1001 std::sort(Values.begin(), Values.end());
1003 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1004 // Check to make sure that if there is more than one entry for a
1005 // particular basic block in this PHI node, that the incoming values are
1008 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1009 Values[i].second == Values[i-1].second,
1010 "PHI node has multiple entries for the same basic block with "
1011 "different incoming values!", PN, Values[i].first,
1012 Values[i].second, Values[i-1].second);
1014 // Check to make sure that the predecessors and PHI node entries are
1016 Assert3(Values[i].first == Preds[i],
1017 "PHI node entries do not match predecessors!", PN,
1018 Values[i].first, Preds[i]);
1024 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1025 // Ensure that terminators only exist at the end of the basic block.
1026 Assert1(&I == I.getParent()->getTerminator(),
1027 "Terminator found in the middle of a basic block!", I.getParent());
1028 visitInstruction(I);
1031 void Verifier::visitBranchInst(BranchInst &BI) {
1032 if (BI.isConditional()) {
1033 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1034 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1036 visitTerminatorInst(BI);
1039 void Verifier::visitReturnInst(ReturnInst &RI) {
1040 Function *F = RI.getParent()->getParent();
1041 unsigned N = RI.getNumOperands();
1042 if (F->getReturnType()->isVoidTy())
1044 "Found return instr that returns non-void in Function of void "
1045 "return type!", &RI, F->getReturnType());
1047 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1048 "Function return type does not match operand "
1049 "type of return inst!", &RI, F->getReturnType());
1051 // Check to make sure that the return value has necessary properties for
1053 visitTerminatorInst(RI);
1056 void Verifier::visitSwitchInst(SwitchInst &SI) {
1057 // Check to make sure that all of the constants in the switch instruction
1058 // have the same type as the switched-on value.
1059 Type *SwitchTy = SI.getCondition()->getType();
1060 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
1061 IntegersSubsetToBB Mapping;
1062 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
1063 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1064 IntegersSubset CaseRanges = i.getCaseValueEx();
1065 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
1066 IntegersSubset::Range r = CaseRanges.getItem(ri);
1067 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
1068 "Switch constants must all be same type as switch value!", &SI);
1069 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
1070 "Switch constants must all be same type as switch value!", &SI);
1072 RangeSetMap[r] = i.getCaseIndex();
1076 IntegersSubsetToBB::RangeIterator errItem;
1077 if (!Mapping.verify(errItem)) {
1078 unsigned CaseIndex = RangeSetMap[errItem->first];
1079 SwitchInst::CaseIt i(&SI, CaseIndex);
1080 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
1083 visitTerminatorInst(SI);
1086 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1087 Assert1(BI.getAddress()->getType()->isPointerTy(),
1088 "Indirectbr operand must have pointer type!", &BI);
1089 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1090 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1091 "Indirectbr destinations must all have pointer type!", &BI);
1093 visitTerminatorInst(BI);
1096 void Verifier::visitSelectInst(SelectInst &SI) {
1097 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1099 "Invalid operands for select instruction!", &SI);
1101 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1102 "Select values must have same type as select instruction!", &SI);
1103 visitInstruction(SI);
1106 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1107 /// a pass, if any exist, it's an error.
1109 void Verifier::visitUserOp1(Instruction &I) {
1110 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1113 void Verifier::visitTruncInst(TruncInst &I) {
1114 // Get the source and destination types
1115 Type *SrcTy = I.getOperand(0)->getType();
1116 Type *DestTy = I.getType();
1118 // Get the size of the types in bits, we'll need this later
1119 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1120 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1122 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1123 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1124 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1125 "trunc source and destination must both be a vector or neither", &I);
1126 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1128 visitInstruction(I);
1131 void Verifier::visitZExtInst(ZExtInst &I) {
1132 // Get the source and destination types
1133 Type *SrcTy = I.getOperand(0)->getType();
1134 Type *DestTy = I.getType();
1136 // Get the size of the types in bits, we'll need this later
1137 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1138 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1139 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1140 "zext source and destination must both be a vector or neither", &I);
1141 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1142 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1144 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1146 visitInstruction(I);
1149 void Verifier::visitSExtInst(SExtInst &I) {
1150 // Get the source and destination types
1151 Type *SrcTy = I.getOperand(0)->getType();
1152 Type *DestTy = I.getType();
1154 // Get the size of the types in bits, we'll need this later
1155 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1156 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1158 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1159 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1160 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1161 "sext source and destination must both be a vector or neither", &I);
1162 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1164 visitInstruction(I);
1167 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1168 // Get the source and destination types
1169 Type *SrcTy = I.getOperand(0)->getType();
1170 Type *DestTy = I.getType();
1171 // Get the size of the types in bits, we'll need this later
1172 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1173 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1175 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1176 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1177 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1178 "fptrunc source and destination must both be a vector or neither",&I);
1179 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1181 visitInstruction(I);
1184 void Verifier::visitFPExtInst(FPExtInst &I) {
1185 // Get the source and destination types
1186 Type *SrcTy = I.getOperand(0)->getType();
1187 Type *DestTy = I.getType();
1189 // Get the size of the types in bits, we'll need this later
1190 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1191 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1193 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1194 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1195 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1196 "fpext source and destination must both be a vector or neither", &I);
1197 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1199 visitInstruction(I);
1202 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1203 // Get the source and destination types
1204 Type *SrcTy = I.getOperand(0)->getType();
1205 Type *DestTy = I.getType();
1207 bool SrcVec = SrcTy->isVectorTy();
1208 bool DstVec = DestTy->isVectorTy();
1210 Assert1(SrcVec == DstVec,
1211 "UIToFP source and dest must both be vector or scalar", &I);
1212 Assert1(SrcTy->isIntOrIntVectorTy(),
1213 "UIToFP source must be integer or integer vector", &I);
1214 Assert1(DestTy->isFPOrFPVectorTy(),
1215 "UIToFP result must be FP or FP vector", &I);
1217 if (SrcVec && DstVec)
1218 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1219 cast<VectorType>(DestTy)->getNumElements(),
1220 "UIToFP source and dest vector length mismatch", &I);
1222 visitInstruction(I);
1225 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1226 // Get the source and destination types
1227 Type *SrcTy = I.getOperand(0)->getType();
1228 Type *DestTy = I.getType();
1230 bool SrcVec = SrcTy->isVectorTy();
1231 bool DstVec = DestTy->isVectorTy();
1233 Assert1(SrcVec == DstVec,
1234 "SIToFP source and dest must both be vector or scalar", &I);
1235 Assert1(SrcTy->isIntOrIntVectorTy(),
1236 "SIToFP source must be integer or integer vector", &I);
1237 Assert1(DestTy->isFPOrFPVectorTy(),
1238 "SIToFP result must be FP or FP vector", &I);
1240 if (SrcVec && DstVec)
1241 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1242 cast<VectorType>(DestTy)->getNumElements(),
1243 "SIToFP source and dest vector length mismatch", &I);
1245 visitInstruction(I);
1248 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1249 // Get the source and destination types
1250 Type *SrcTy = I.getOperand(0)->getType();
1251 Type *DestTy = I.getType();
1253 bool SrcVec = SrcTy->isVectorTy();
1254 bool DstVec = DestTy->isVectorTy();
1256 Assert1(SrcVec == DstVec,
1257 "FPToUI source and dest must both be vector or scalar", &I);
1258 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1260 Assert1(DestTy->isIntOrIntVectorTy(),
1261 "FPToUI result must be integer or integer vector", &I);
1263 if (SrcVec && DstVec)
1264 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1265 cast<VectorType>(DestTy)->getNumElements(),
1266 "FPToUI source and dest vector length mismatch", &I);
1268 visitInstruction(I);
1271 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1272 // Get the source and destination types
1273 Type *SrcTy = I.getOperand(0)->getType();
1274 Type *DestTy = I.getType();
1276 bool SrcVec = SrcTy->isVectorTy();
1277 bool DstVec = DestTy->isVectorTy();
1279 Assert1(SrcVec == DstVec,
1280 "FPToSI source and dest must both be vector or scalar", &I);
1281 Assert1(SrcTy->isFPOrFPVectorTy(),
1282 "FPToSI source must be FP or FP vector", &I);
1283 Assert1(DestTy->isIntOrIntVectorTy(),
1284 "FPToSI result must be integer or integer vector", &I);
1286 if (SrcVec && DstVec)
1287 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1288 cast<VectorType>(DestTy)->getNumElements(),
1289 "FPToSI source and dest vector length mismatch", &I);
1291 visitInstruction(I);
1294 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1295 // Get the source and destination types
1296 Type *SrcTy = I.getOperand(0)->getType();
1297 Type *DestTy = I.getType();
1299 Assert1(SrcTy->getScalarType()->isPointerTy(),
1300 "PtrToInt source must be pointer", &I);
1301 Assert1(DestTy->getScalarType()->isIntegerTy(),
1302 "PtrToInt result must be integral", &I);
1303 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1304 "PtrToInt type mismatch", &I);
1306 if (SrcTy->isVectorTy()) {
1307 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1308 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1309 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1310 "PtrToInt Vector width mismatch", &I);
1313 visitInstruction(I);
1316 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1317 // Get the source and destination types
1318 Type *SrcTy = I.getOperand(0)->getType();
1319 Type *DestTy = I.getType();
1321 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1322 "IntToPtr source must be an integral", &I);
1323 Assert1(DestTy->getScalarType()->isPointerTy(),
1324 "IntToPtr result must be a pointer",&I);
1325 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1326 "IntToPtr type mismatch", &I);
1327 if (SrcTy->isVectorTy()) {
1328 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1329 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1330 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1331 "IntToPtr Vector width mismatch", &I);
1333 visitInstruction(I);
1336 void Verifier::visitBitCastInst(BitCastInst &I) {
1337 // Get the source and destination types
1338 Type *SrcTy = I.getOperand(0)->getType();
1339 Type *DestTy = I.getType();
1341 // Get the size of the types in bits, we'll need this later
1342 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1343 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1345 // BitCast implies a no-op cast of type only. No bits change.
1346 // However, you can't cast pointers to anything but pointers.
1347 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1348 "Bitcast requires both operands to be pointer or neither", &I);
1349 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1351 // Disallow aggregates.
1352 Assert1(!SrcTy->isAggregateType(),
1353 "Bitcast operand must not be aggregate", &I);
1354 Assert1(!DestTy->isAggregateType(),
1355 "Bitcast type must not be aggregate", &I);
1357 visitInstruction(I);
1360 /// visitPHINode - Ensure that a PHI node is well formed.
1362 void Verifier::visitPHINode(PHINode &PN) {
1363 // Ensure that the PHI nodes are all grouped together at the top of the block.
1364 // This can be tested by checking whether the instruction before this is
1365 // either nonexistent (because this is begin()) or is a PHI node. If not,
1366 // then there is some other instruction before a PHI.
1367 Assert2(&PN == &PN.getParent()->front() ||
1368 isa<PHINode>(--BasicBlock::iterator(&PN)),
1369 "PHI nodes not grouped at top of basic block!",
1370 &PN, PN.getParent());
1372 // Check that all of the values of the PHI node have the same type as the
1373 // result, and that the incoming blocks are really basic blocks.
1374 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1375 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1376 "PHI node operands are not the same type as the result!", &PN);
1379 // All other PHI node constraints are checked in the visitBasicBlock method.
1381 visitInstruction(PN);
1384 void Verifier::VerifyCallSite(CallSite CS) {
1385 Instruction *I = CS.getInstruction();
1387 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1388 "Called function must be a pointer!", I);
1389 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1391 Assert1(FPTy->getElementType()->isFunctionTy(),
1392 "Called function is not pointer to function type!", I);
1393 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1395 // Verify that the correct number of arguments are being passed
1396 if (FTy->isVarArg())
1397 Assert1(CS.arg_size() >= FTy->getNumParams(),
1398 "Called function requires more parameters than were provided!",I);
1400 Assert1(CS.arg_size() == FTy->getNumParams(),
1401 "Incorrect number of arguments passed to called function!", I);
1403 // Verify that all arguments to the call match the function type.
1404 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1405 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1406 "Call parameter type does not match function signature!",
1407 CS.getArgument(i), FTy->getParamType(i), I);
1409 AttributeSet Attrs = CS.getAttributes();
1411 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1412 "Attribute after last parameter!", I);
1414 // Verify call attributes.
1415 VerifyFunctionAttrs(FTy, Attrs, I);
1417 if (FTy->isVarArg()) {
1418 // FIXME? is 'nest' even legal here?
1419 bool SawNest = false;
1420 bool SawReturned = false;
1422 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1423 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1425 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1429 // Check attributes on the varargs part.
1430 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1431 Type *Ty = CS.getArgument(Idx-1)->getType();
1432 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1434 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1435 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1439 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1440 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1442 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1443 "Incompatible argument and return types for 'returned' "
1448 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1449 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1453 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1454 if (CS.getCalledFunction() == 0 ||
1455 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1456 for (FunctionType::param_iterator PI = FTy->param_begin(),
1457 PE = FTy->param_end(); PI != PE; ++PI)
1458 Assert1(!(*PI)->isMetadataTy(),
1459 "Function has metadata parameter but isn't an intrinsic", I);
1462 // If the call site has the 'builtin' attribute, verify that it's applied to a
1463 // direct call to a function with the 'nobuiltin' attribute.
1464 if (CS.hasFnAttr(Attribute::Builtin))
1465 Assert1(CS.getCalledFunction() &&
1466 CS.getCalledFunction()->hasFnAttribute(Attribute::NoBuiltin),
1467 "Attribute 'builtin' can only be used in a call to a function with "
1468 "the 'nobuiltin' attribute.", I);
1470 visitInstruction(*I);
1473 void Verifier::visitCallInst(CallInst &CI) {
1474 VerifyCallSite(&CI);
1476 if (Function *F = CI.getCalledFunction())
1477 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1478 visitIntrinsicFunctionCall(ID, CI);
1481 void Verifier::visitInvokeInst(InvokeInst &II) {
1482 VerifyCallSite(&II);
1484 // Verify that there is a landingpad instruction as the first non-PHI
1485 // instruction of the 'unwind' destination.
1486 Assert1(II.getUnwindDest()->isLandingPad(),
1487 "The unwind destination does not have a landingpad instruction!",&II);
1489 visitTerminatorInst(II);
1492 /// visitBinaryOperator - Check that both arguments to the binary operator are
1493 /// of the same type!
1495 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1496 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1497 "Both operands to a binary operator are not of the same type!", &B);
1499 switch (B.getOpcode()) {
1500 // Check that integer arithmetic operators are only used with
1501 // integral operands.
1502 case Instruction::Add:
1503 case Instruction::Sub:
1504 case Instruction::Mul:
1505 case Instruction::SDiv:
1506 case Instruction::UDiv:
1507 case Instruction::SRem:
1508 case Instruction::URem:
1509 Assert1(B.getType()->isIntOrIntVectorTy(),
1510 "Integer arithmetic operators only work with integral types!", &B);
1511 Assert1(B.getType() == B.getOperand(0)->getType(),
1512 "Integer arithmetic operators must have same type "
1513 "for operands and result!", &B);
1515 // Check that floating-point arithmetic operators are only used with
1516 // floating-point operands.
1517 case Instruction::FAdd:
1518 case Instruction::FSub:
1519 case Instruction::FMul:
1520 case Instruction::FDiv:
1521 case Instruction::FRem:
1522 Assert1(B.getType()->isFPOrFPVectorTy(),
1523 "Floating-point arithmetic operators only work with "
1524 "floating-point types!", &B);
1525 Assert1(B.getType() == B.getOperand(0)->getType(),
1526 "Floating-point arithmetic operators must have same type "
1527 "for operands and result!", &B);
1529 // Check that logical operators are only used with integral operands.
1530 case Instruction::And:
1531 case Instruction::Or:
1532 case Instruction::Xor:
1533 Assert1(B.getType()->isIntOrIntVectorTy(),
1534 "Logical operators only work with integral types!", &B);
1535 Assert1(B.getType() == B.getOperand(0)->getType(),
1536 "Logical operators must have same type for operands and result!",
1539 case Instruction::Shl:
1540 case Instruction::LShr:
1541 case Instruction::AShr:
1542 Assert1(B.getType()->isIntOrIntVectorTy(),
1543 "Shifts only work with integral types!", &B);
1544 Assert1(B.getType() == B.getOperand(0)->getType(),
1545 "Shift return type must be same as operands!", &B);
1548 llvm_unreachable("Unknown BinaryOperator opcode!");
1551 visitInstruction(B);
1554 void Verifier::visitICmpInst(ICmpInst &IC) {
1555 // Check that the operands are the same type
1556 Type *Op0Ty = IC.getOperand(0)->getType();
1557 Type *Op1Ty = IC.getOperand(1)->getType();
1558 Assert1(Op0Ty == Op1Ty,
1559 "Both operands to ICmp instruction are not of the same type!", &IC);
1560 // Check that the operands are the right type
1561 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1562 "Invalid operand types for ICmp instruction", &IC);
1563 // Check that the predicate is valid.
1564 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1565 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1566 "Invalid predicate in ICmp instruction!", &IC);
1568 visitInstruction(IC);
1571 void Verifier::visitFCmpInst(FCmpInst &FC) {
1572 // Check that the operands are the same type
1573 Type *Op0Ty = FC.getOperand(0)->getType();
1574 Type *Op1Ty = FC.getOperand(1)->getType();
1575 Assert1(Op0Ty == Op1Ty,
1576 "Both operands to FCmp instruction are not of the same type!", &FC);
1577 // Check that the operands are the right type
1578 Assert1(Op0Ty->isFPOrFPVectorTy(),
1579 "Invalid operand types for FCmp instruction", &FC);
1580 // Check that the predicate is valid.
1581 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1582 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1583 "Invalid predicate in FCmp instruction!", &FC);
1585 visitInstruction(FC);
1588 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1589 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1591 "Invalid extractelement operands!", &EI);
1592 visitInstruction(EI);
1595 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1596 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1599 "Invalid insertelement operands!", &IE);
1600 visitInstruction(IE);
1603 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1604 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1606 "Invalid shufflevector operands!", &SV);
1607 visitInstruction(SV);
1610 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1611 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1613 Assert1(isa<PointerType>(TargetTy),
1614 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1615 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1616 "GEP into unsized type!", &GEP);
1617 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1618 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1621 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1623 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1624 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1626 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1627 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1628 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1630 if (GEP.getPointerOperandType()->isVectorTy()) {
1631 // Additional checks for vector GEPs.
1632 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1633 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1634 "Vector GEP result width doesn't match operand's", &GEP);
1635 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1636 Type *IndexTy = Idxs[i]->getType();
1637 Assert1(IndexTy->isVectorTy(),
1638 "Vector GEP must have vector indices!", &GEP);
1639 unsigned IndexWidth = IndexTy->getVectorNumElements();
1640 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1643 visitInstruction(GEP);
1646 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1647 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1650 void Verifier::visitLoadInst(LoadInst &LI) {
1651 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1652 Assert1(PTy, "Load operand must be a pointer.", &LI);
1653 Type *ElTy = PTy->getElementType();
1654 Assert2(ElTy == LI.getType(),
1655 "Load result type does not match pointer operand type!", &LI, ElTy);
1656 if (LI.isAtomic()) {
1657 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1658 "Load cannot have Release ordering", &LI);
1659 Assert1(LI.getAlignment() != 0,
1660 "Atomic load must specify explicit alignment", &LI);
1661 if (!ElTy->isPointerTy()) {
1662 Assert2(ElTy->isIntegerTy(),
1663 "atomic store operand must have integer type!",
1665 unsigned Size = ElTy->getPrimitiveSizeInBits();
1666 Assert2(Size >= 8 && !(Size & (Size - 1)),
1667 "atomic store operand must be power-of-two byte-sized integer",
1671 Assert1(LI.getSynchScope() == CrossThread,
1672 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1675 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1676 unsigned NumOperands = Range->getNumOperands();
1677 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1678 unsigned NumRanges = NumOperands / 2;
1679 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1681 ConstantRange LastRange(1); // Dummy initial value
1682 for (unsigned i = 0; i < NumRanges; ++i) {
1683 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1684 Assert1(Low, "The lower limit must be an integer!", Low);
1685 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1686 Assert1(High, "The upper limit must be an integer!", High);
1687 Assert1(High->getType() == Low->getType() &&
1688 High->getType() == ElTy, "Range types must match load type!",
1691 APInt HighV = High->getValue();
1692 APInt LowV = Low->getValue();
1693 ConstantRange CurRange(LowV, HighV);
1694 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1695 "Range must not be empty!", Range);
1697 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1698 "Intervals are overlapping", Range);
1699 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1701 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1704 LastRange = ConstantRange(LowV, HighV);
1706 if (NumRanges > 2) {
1708 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1710 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1711 ConstantRange FirstRange(FirstLow, FirstHigh);
1712 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1713 "Intervals are overlapping", Range);
1714 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1721 visitInstruction(LI);
1724 void Verifier::visitStoreInst(StoreInst &SI) {
1725 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1726 Assert1(PTy, "Store operand must be a pointer.", &SI);
1727 Type *ElTy = PTy->getElementType();
1728 Assert2(ElTy == SI.getOperand(0)->getType(),
1729 "Stored value type does not match pointer operand type!",
1731 if (SI.isAtomic()) {
1732 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1733 "Store cannot have Acquire ordering", &SI);
1734 Assert1(SI.getAlignment() != 0,
1735 "Atomic store must specify explicit alignment", &SI);
1736 if (!ElTy->isPointerTy()) {
1737 Assert2(ElTy->isIntegerTy(),
1738 "atomic store operand must have integer type!",
1740 unsigned Size = ElTy->getPrimitiveSizeInBits();
1741 Assert2(Size >= 8 && !(Size & (Size - 1)),
1742 "atomic store operand must be power-of-two byte-sized integer",
1746 Assert1(SI.getSynchScope() == CrossThread,
1747 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1749 visitInstruction(SI);
1752 void Verifier::visitAllocaInst(AllocaInst &AI) {
1753 PointerType *PTy = AI.getType();
1754 Assert1(PTy->getAddressSpace() == 0,
1755 "Allocation instruction pointer not in the generic address space!",
1757 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1759 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1760 "Alloca array size must have integer type", &AI);
1761 visitInstruction(AI);
1764 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1765 Assert1(CXI.getOrdering() != NotAtomic,
1766 "cmpxchg instructions must be atomic.", &CXI);
1767 Assert1(CXI.getOrdering() != Unordered,
1768 "cmpxchg instructions cannot be unordered.", &CXI);
1769 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1770 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1771 Type *ElTy = PTy->getElementType();
1772 Assert2(ElTy->isIntegerTy(),
1773 "cmpxchg operand must have integer type!",
1775 unsigned Size = ElTy->getPrimitiveSizeInBits();
1776 Assert2(Size >= 8 && !(Size & (Size - 1)),
1777 "cmpxchg operand must be power-of-two byte-sized integer",
1779 Assert2(ElTy == CXI.getOperand(1)->getType(),
1780 "Expected value type does not match pointer operand type!",
1782 Assert2(ElTy == CXI.getOperand(2)->getType(),
1783 "Stored value type does not match pointer operand type!",
1785 visitInstruction(CXI);
1788 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1789 Assert1(RMWI.getOrdering() != NotAtomic,
1790 "atomicrmw instructions must be atomic.", &RMWI);
1791 Assert1(RMWI.getOrdering() != Unordered,
1792 "atomicrmw instructions cannot be unordered.", &RMWI);
1793 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1794 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1795 Type *ElTy = PTy->getElementType();
1796 Assert2(ElTy->isIntegerTy(),
1797 "atomicrmw operand must have integer type!",
1799 unsigned Size = ElTy->getPrimitiveSizeInBits();
1800 Assert2(Size >= 8 && !(Size & (Size - 1)),
1801 "atomicrmw operand must be power-of-two byte-sized integer",
1803 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1804 "Argument value type does not match pointer operand type!",
1806 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1807 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1808 "Invalid binary operation!", &RMWI);
1809 visitInstruction(RMWI);
1812 void Verifier::visitFenceInst(FenceInst &FI) {
1813 const AtomicOrdering Ordering = FI.getOrdering();
1814 Assert1(Ordering == Acquire || Ordering == Release ||
1815 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1816 "fence instructions may only have "
1817 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1818 visitInstruction(FI);
1821 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1822 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1823 EVI.getIndices()) ==
1825 "Invalid ExtractValueInst operands!", &EVI);
1827 visitInstruction(EVI);
1830 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1831 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1832 IVI.getIndices()) ==
1833 IVI.getOperand(1)->getType(),
1834 "Invalid InsertValueInst operands!", &IVI);
1836 visitInstruction(IVI);
1839 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1840 BasicBlock *BB = LPI.getParent();
1842 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1844 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1845 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1847 // The landingpad instruction defines its parent as a landing pad block. The
1848 // landing pad block may be branched to only by the unwind edge of an invoke.
1849 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1850 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1851 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1852 "Block containing LandingPadInst must be jumped to "
1853 "only by the unwind edge of an invoke.", &LPI);
1856 // The landingpad instruction must be the first non-PHI instruction in the
1858 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1859 "LandingPadInst not the first non-PHI instruction in the block.",
1862 // The personality functions for all landingpad instructions within the same
1863 // function should match.
1865 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1866 "Personality function doesn't match others in function", &LPI);
1867 PersonalityFn = LPI.getPersonalityFn();
1869 // All operands must be constants.
1870 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1872 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1873 Value *Clause = LPI.getClause(i);
1874 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1875 if (LPI.isCatch(i)) {
1876 Assert1(isa<PointerType>(Clause->getType()),
1877 "Catch operand does not have pointer type!", &LPI);
1879 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1880 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1881 "Filter operand is not an array of constants!", &LPI);
1885 visitInstruction(LPI);
1888 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1889 Instruction *Op = cast<Instruction>(I.getOperand(i));
1890 // If the we have an invalid invoke, don't try to compute the dominance.
1891 // We already reject it in the invoke specific checks and the dominance
1892 // computation doesn't handle multiple edges.
1893 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1894 if (II->getNormalDest() == II->getUnwindDest())
1898 const Use &U = I.getOperandUse(i);
1899 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1900 "Instruction does not dominate all uses!", Op, &I);
1903 /// verifyInstruction - Verify that an instruction is well formed.
1905 void Verifier::visitInstruction(Instruction &I) {
1906 BasicBlock *BB = I.getParent();
1907 Assert1(BB, "Instruction not embedded in basic block!", &I);
1909 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1910 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1912 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1913 "Only PHI nodes may reference their own value!", &I);
1916 // Check that void typed values don't have names
1917 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1918 "Instruction has a name, but provides a void value!", &I);
1920 // Check that the return value of the instruction is either void or a legal
1922 Assert1(I.getType()->isVoidTy() ||
1923 I.getType()->isFirstClassType(),
1924 "Instruction returns a non-scalar type!", &I);
1926 // Check that the instruction doesn't produce metadata. Calls are already
1927 // checked against the callee type.
1928 Assert1(!I.getType()->isMetadataTy() ||
1929 isa<CallInst>(I) || isa<InvokeInst>(I),
1930 "Invalid use of metadata!", &I);
1932 // Check that all uses of the instruction, if they are instructions
1933 // themselves, actually have parent basic blocks. If the use is not an
1934 // instruction, it is an error!
1935 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1937 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1938 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1939 " embedded in a basic block!", &I, Used);
1941 CheckFailed("Use of instruction is not an instruction!", *UI);
1946 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1947 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1949 // Check to make sure that only first-class-values are operands to
1951 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1952 Assert1(0, "Instruction operands must be first-class values!", &I);
1955 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1956 // Check to make sure that the "address of" an intrinsic function is never
1958 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1959 "Cannot take the address of an intrinsic!", &I);
1960 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1961 F->getIntrinsicID() == Intrinsic::donothing,
1962 "Cannot invoke an intrinsinc other than donothing", &I);
1963 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1965 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1966 Assert1(OpBB->getParent() == BB->getParent(),
1967 "Referring to a basic block in another function!", &I);
1968 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1969 Assert1(OpArg->getParent() == BB->getParent(),
1970 "Referring to an argument in another function!", &I);
1971 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1972 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1974 } else if (isa<Instruction>(I.getOperand(i))) {
1975 verifyDominatesUse(I, i);
1976 } else if (isa<InlineAsm>(I.getOperand(i))) {
1977 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1978 (i + 3 == e && isa<InvokeInst>(I)),
1979 "Cannot take the address of an inline asm!", &I);
1983 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1984 Assert1(I.getType()->isFPOrFPVectorTy(),
1985 "fpmath requires a floating point result!", &I);
1986 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1987 Value *Op0 = MD->getOperand(0);
1988 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1989 APFloat Accuracy = CFP0->getValueAPF();
1990 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
1991 "fpmath accuracy not a positive number!", &I);
1993 Assert1(false, "invalid fpmath accuracy!", &I);
1997 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1998 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2000 InstsInThisBlock.insert(&I);
2003 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2004 /// intrinsic argument or return value) matches the type constraints specified
2005 /// by the .td file (e.g. an "any integer" argument really is an integer).
2007 /// This return true on error but does not print a message.
2008 bool Verifier::VerifyIntrinsicType(Type *Ty,
2009 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2010 SmallVectorImpl<Type*> &ArgTys) {
2011 using namespace Intrinsic;
2013 // If we ran out of descriptors, there are too many arguments.
2014 if (Infos.empty()) return true;
2015 IITDescriptor D = Infos.front();
2016 Infos = Infos.slice(1);
2019 case IITDescriptor::Void: return !Ty->isVoidTy();
2020 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2021 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2022 case IITDescriptor::Half: return !Ty->isHalfTy();
2023 case IITDescriptor::Float: return !Ty->isFloatTy();
2024 case IITDescriptor::Double: return !Ty->isDoubleTy();
2025 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2026 case IITDescriptor::Vector: {
2027 VectorType *VT = dyn_cast<VectorType>(Ty);
2028 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2029 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2031 case IITDescriptor::Pointer: {
2032 PointerType *PT = dyn_cast<PointerType>(Ty);
2033 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2034 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2037 case IITDescriptor::Struct: {
2038 StructType *ST = dyn_cast<StructType>(Ty);
2039 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2042 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2043 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2048 case IITDescriptor::Argument:
2049 // Two cases here - If this is the second occurrence of an argument, verify
2050 // that the later instance matches the previous instance.
2051 if (D.getArgumentNumber() < ArgTys.size())
2052 return Ty != ArgTys[D.getArgumentNumber()];
2054 // Otherwise, if this is the first instance of an argument, record it and
2055 // verify the "Any" kind.
2056 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2057 ArgTys.push_back(Ty);
2059 switch (D.getArgumentKind()) {
2060 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2061 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2062 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2063 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2065 llvm_unreachable("all argument kinds not covered");
2067 case IITDescriptor::ExtendVecArgument:
2068 // This may only be used when referring to a previous vector argument.
2069 return D.getArgumentNumber() >= ArgTys.size() ||
2070 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2071 VectorType::getExtendedElementVectorType(
2072 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2074 case IITDescriptor::TruncVecArgument:
2075 // This may only be used when referring to a previous vector argument.
2076 return D.getArgumentNumber() >= ArgTys.size() ||
2077 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2078 VectorType::getTruncatedElementVectorType(
2079 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2081 llvm_unreachable("unhandled");
2084 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2086 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2087 Function *IF = CI.getCalledFunction();
2088 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2091 // Verify that the intrinsic prototype lines up with what the .td files
2093 FunctionType *IFTy = IF->getFunctionType();
2094 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
2096 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2097 getIntrinsicInfoTableEntries(ID, Table);
2098 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2100 SmallVector<Type *, 4> ArgTys;
2101 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2102 "Intrinsic has incorrect return type!", IF);
2103 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2104 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2105 "Intrinsic has incorrect argument type!", IF);
2106 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2108 // Now that we have the intrinsic ID and the actual argument types (and we
2109 // know they are legal for the intrinsic!) get the intrinsic name through the
2110 // usual means. This allows us to verify the mangling of argument types into
2112 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2113 "Intrinsic name not mangled correctly for type arguments!", IF);
2115 // If the intrinsic takes MDNode arguments, verify that they are either global
2116 // or are local to *this* function.
2117 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2118 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2119 visitMDNode(*MD, CI.getParent()->getParent());
2124 case Intrinsic::ctlz: // llvm.ctlz
2125 case Intrinsic::cttz: // llvm.cttz
2126 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2127 "is_zero_undef argument of bit counting intrinsics must be a "
2128 "constant int", &CI);
2130 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2131 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2132 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2133 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2134 Assert1(MD->getNumOperands() == 1,
2135 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2137 case Intrinsic::memcpy:
2138 case Intrinsic::memmove:
2139 case Intrinsic::memset:
2140 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2141 "alignment argument of memory intrinsics must be a constant int",
2143 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2144 "isvolatile argument of memory intrinsics must be a constant int",
2147 case Intrinsic::gcroot:
2148 case Intrinsic::gcwrite:
2149 case Intrinsic::gcread:
2150 if (ID == Intrinsic::gcroot) {
2152 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2153 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2154 Assert1(isa<Constant>(CI.getArgOperand(1)),
2155 "llvm.gcroot parameter #2 must be a constant.", &CI);
2156 if (!AI->getType()->getElementType()->isPointerTy()) {
2157 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2158 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2159 "or argument #2 must be a non-null constant.", &CI);
2163 Assert1(CI.getParent()->getParent()->hasGC(),
2164 "Enclosing function does not use GC.", &CI);
2166 case Intrinsic::init_trampoline:
2167 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2168 "llvm.init_trampoline parameter #2 must resolve to a function.",
2171 case Intrinsic::prefetch:
2172 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2173 isa<ConstantInt>(CI.getArgOperand(2)) &&
2174 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2175 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2176 "invalid arguments to llvm.prefetch",
2179 case Intrinsic::stackprotector:
2180 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2181 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2184 case Intrinsic::lifetime_start:
2185 case Intrinsic::lifetime_end:
2186 case Intrinsic::invariant_start:
2187 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2188 "size argument of memory use markers must be a constant integer",
2191 case Intrinsic::invariant_end:
2192 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2193 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2198 void Verifier::verifyDebugInfo(Module &M) {
2199 // Verify Debug Info.
2200 if (!DisableDebugInfoVerifier) {
2201 DebugInfoFinder Finder;
2202 Finder.processModule(M);
2204 for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2205 E = Finder.compile_unit_end(); I != E; ++I)
2206 Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2207 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2208 E = Finder.subprogram_end(); I != E; ++I)
2209 Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2210 for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2211 E = Finder.global_variable_end(); I != E; ++I)
2212 Assert1(DIGlobalVariable(*I).Verify(),
2213 "DIGlobalVariable does not Verify!", *I);
2214 for (DebugInfoFinder::iterator I = Finder.type_begin(),
2215 E = Finder.type_end(); I != E; ++I)
2216 Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2217 for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2218 E = Finder.scope_end(); I != E; ++I)
2219 Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2223 //===----------------------------------------------------------------------===//
2224 // Implement the public interfaces to this file...
2225 //===----------------------------------------------------------------------===//
2227 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2228 return new Verifier(action);
2232 /// verifyFunction - Check a function for errors, printing messages on stderr.
2233 /// Return true if the function is corrupt.
2235 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2236 Function &F = const_cast<Function&>(f);
2237 assert(!F.isDeclaration() && "Cannot verify external functions");
2239 FunctionPassManager FPM(F.getParent());
2240 Verifier *V = new Verifier(action);
2246 /// verifyModule - Check a module for errors, printing messages on stderr.
2247 /// Return true if the module is corrupt.
2249 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2250 std::string *ErrorInfo) {
2252 Verifier *V = new Verifier(action);
2254 PM.run(const_cast<Module&>(M));
2256 if (ErrorInfo && V->Broken)
2257 *ErrorInfo = V->MessagesStr.str();