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/CallingConv.h"
50 #include "llvm/Constants.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/InlineAsm.h"
53 #include "llvm/IntrinsicInst.h"
54 #include "llvm/LLVMContext.h"
55 #include "llvm/Metadata.h"
56 #include "llvm/Module.h"
57 #include "llvm/Pass.h"
58 #include "llvm/PassManager.h"
59 #include "llvm/Analysis/Dominators.h"
60 #include "llvm/Assembly/Writer.h"
61 #include "llvm/CodeGen/ValueTypes.h"
62 #include "llvm/Support/CallSite.h"
63 #include "llvm/Support/CFG.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/InstVisitor.h"
66 #include "llvm/ADT/SetVector.h"
67 #include "llvm/ADT/SmallPtrSet.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/StringExtras.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/Support/ConstantRange.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/raw_ostream.h"
78 namespace { // Anonymous namespace for class
79 struct PreVerifier : public FunctionPass {
80 static char ID; // Pass ID, replacement for typeid
82 PreVerifier() : FunctionPass(ID) {
83 initializePreVerifierPass(*PassRegistry::getPassRegistry());
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90 // Check that the prerequisites for successful DominatorTree construction
92 bool runOnFunction(Function &F) {
95 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
96 if (I->empty() || !I->back().isTerminator()) {
97 dbgs() << "Basic Block in function '" << F.getName()
98 << "' does not have terminator!\n";
99 WriteAsOperand(dbgs(), I, true);
106 report_fatal_error("Broken module, no Basic Block terminator!");
113 char PreVerifier::ID = 0;
114 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
116 static char &PreVerifyID = PreVerifier::ID;
119 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
120 static char ID; // Pass ID, replacement for typeid
121 bool Broken; // Is this module found to be broken?
122 VerifierFailureAction action;
123 // What to do if verification fails.
124 Module *Mod; // Module we are verifying right now
125 LLVMContext *Context; // Context within which we are verifying
126 DominatorTree *DT; // Dominator Tree, caution can be null!
128 std::string Messages;
129 raw_string_ostream MessagesStr;
131 /// InstInThisBlock - when verifying a basic block, keep track of all of the
132 /// instructions we have seen so far. This allows us to do efficient
133 /// dominance checks for the case when an instruction has an operand that is
134 /// an instruction in the same block.
135 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
137 /// MDNodes - keep track of the metadata nodes that have been checked
139 SmallPtrSet<MDNode *, 32> MDNodes;
141 /// PersonalityFn - The personality function referenced by the
142 /// LandingPadInsts. All LandingPadInsts within the same function must use
143 /// the same personality function.
144 const Value *PersonalityFn;
147 : FunctionPass(ID), Broken(false),
148 action(AbortProcessAction), Mod(0), Context(0), DT(0),
149 MessagesStr(Messages), PersonalityFn(0) {
150 initializeVerifierPass(*PassRegistry::getPassRegistry());
152 explicit Verifier(VerifierFailureAction ctn)
153 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
154 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
155 initializeVerifierPass(*PassRegistry::getPassRegistry());
158 bool doInitialization(Module &M) {
160 Context = &M.getContext();
162 // We must abort before returning back to the pass manager, or else the
163 // pass manager may try to run other passes on the broken module.
164 return abortIfBroken();
167 bool runOnFunction(Function &F) {
168 // Get dominator information if we are being run by PassManager
169 DT = &getAnalysis<DominatorTree>();
172 if (!Context) Context = &F.getContext();
175 InstsInThisBlock.clear();
178 // We must abort before returning back to the pass manager, or else the
179 // pass manager may try to run other passes on the broken module.
180 return abortIfBroken();
183 bool doFinalization(Module &M) {
184 // Scan through, checking all of the external function's linkage now...
185 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
186 visitGlobalValue(*I);
188 // Check to make sure function prototypes are okay.
189 if (I->isDeclaration()) visitFunction(*I);
192 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
194 visitGlobalVariable(*I);
196 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
198 visitGlobalAlias(*I);
200 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
201 E = M.named_metadata_end(); I != E; ++I)
202 visitNamedMDNode(*I);
204 // If the module is broken, abort at this time.
205 return abortIfBroken();
208 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
209 AU.setPreservesAll();
210 AU.addRequiredID(PreVerifyID);
211 AU.addRequired<DominatorTree>();
214 /// abortIfBroken - If the module is broken and we are supposed to abort on
215 /// this condition, do so.
217 bool abortIfBroken() {
218 if (!Broken) return false;
219 MessagesStr << "Broken module found, ";
221 case AbortProcessAction:
222 MessagesStr << "compilation aborted!\n";
223 dbgs() << MessagesStr.str();
224 // Client should choose different reaction if abort is not desired
226 case PrintMessageAction:
227 MessagesStr << "verification continues.\n";
228 dbgs() << MessagesStr.str();
230 case ReturnStatusAction:
231 MessagesStr << "compilation terminated.\n";
234 llvm_unreachable("Invalid action");
238 // Verification methods...
239 void visitGlobalValue(GlobalValue &GV);
240 void visitGlobalVariable(GlobalVariable &GV);
241 void visitGlobalAlias(GlobalAlias &GA);
242 void visitNamedMDNode(NamedMDNode &NMD);
243 void visitMDNode(MDNode &MD, Function *F);
244 void visitFunction(Function &F);
245 void visitBasicBlock(BasicBlock &BB);
246 using InstVisitor<Verifier>::visit;
248 void visit(Instruction &I);
250 void visitTruncInst(TruncInst &I);
251 void visitZExtInst(ZExtInst &I);
252 void visitSExtInst(SExtInst &I);
253 void visitFPTruncInst(FPTruncInst &I);
254 void visitFPExtInst(FPExtInst &I);
255 void visitFPToUIInst(FPToUIInst &I);
256 void visitFPToSIInst(FPToSIInst &I);
257 void visitUIToFPInst(UIToFPInst &I);
258 void visitSIToFPInst(SIToFPInst &I);
259 void visitIntToPtrInst(IntToPtrInst &I);
260 void visitPtrToIntInst(PtrToIntInst &I);
261 void visitBitCastInst(BitCastInst &I);
262 void visitPHINode(PHINode &PN);
263 void visitBinaryOperator(BinaryOperator &B);
264 void visitICmpInst(ICmpInst &IC);
265 void visitFCmpInst(FCmpInst &FC);
266 void visitExtractElementInst(ExtractElementInst &EI);
267 void visitInsertElementInst(InsertElementInst &EI);
268 void visitShuffleVectorInst(ShuffleVectorInst &EI);
269 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
270 void visitCallInst(CallInst &CI);
271 void visitInvokeInst(InvokeInst &II);
272 void visitGetElementPtrInst(GetElementPtrInst &GEP);
273 void visitLoadInst(LoadInst &LI);
274 void visitStoreInst(StoreInst &SI);
275 void verifyDominatesUse(Instruction &I, unsigned i);
276 void visitInstruction(Instruction &I);
277 void visitTerminatorInst(TerminatorInst &I);
278 void visitBranchInst(BranchInst &BI);
279 void visitReturnInst(ReturnInst &RI);
280 void visitSwitchInst(SwitchInst &SI);
281 void visitIndirectBrInst(IndirectBrInst &BI);
282 void visitSelectInst(SelectInst &SI);
283 void visitUserOp1(Instruction &I);
284 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
285 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
286 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
287 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
288 void visitFenceInst(FenceInst &FI);
289 void visitAllocaInst(AllocaInst &AI);
290 void visitExtractValueInst(ExtractValueInst &EVI);
291 void visitInsertValueInst(InsertValueInst &IVI);
292 void visitLandingPadInst(LandingPadInst &LPI);
294 void VerifyCallSite(CallSite CS);
295 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
296 int VT, unsigned ArgNo, std::string &Suffix);
297 bool VerifyIntrinsicType(Type *Ty,
298 ArrayRef<Intrinsic::IITDescriptor> &Infos,
299 SmallVectorImpl<Type*> &ArgTys);
300 void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
301 bool isReturnValue, const Value *V);
302 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
305 void WriteValue(const Value *V) {
307 if (isa<Instruction>(V)) {
308 MessagesStr << *V << '\n';
310 WriteAsOperand(MessagesStr, V, true, Mod);
315 void WriteType(Type *T) {
317 MessagesStr << ' ' << *T;
321 // CheckFailed - A check failed, so print out the condition and the message
322 // that failed. This provides a nice place to put a breakpoint if you want
323 // to see why something is not correct.
324 void CheckFailed(const Twine &Message,
325 const Value *V1 = 0, const Value *V2 = 0,
326 const Value *V3 = 0, const Value *V4 = 0) {
327 MessagesStr << Message.str() << "\n";
335 void CheckFailed(const Twine &Message, const Value *V1,
336 Type *T2, const Value *V3 = 0) {
337 MessagesStr << Message.str() << "\n";
344 void CheckFailed(const Twine &Message, Type *T1,
345 Type *T2 = 0, Type *T3 = 0) {
346 MessagesStr << Message.str() << "\n";
353 } // End anonymous namespace
355 char Verifier::ID = 0;
356 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
357 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
358 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
359 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
361 // Assert - We know that cond should be true, if not print an error message.
362 #define Assert(C, M) \
363 do { if (!(C)) { CheckFailed(M); return; } } while (0)
364 #define Assert1(C, M, V1) \
365 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
366 #define Assert2(C, M, V1, V2) \
367 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
368 #define Assert3(C, M, V1, V2, V3) \
369 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
370 #define Assert4(C, M, V1, V2, V3, V4) \
371 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
373 void Verifier::visit(Instruction &I) {
374 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
375 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
376 InstVisitor<Verifier>::visit(I);
380 void Verifier::visitGlobalValue(GlobalValue &GV) {
381 Assert1(!GV.isDeclaration() ||
382 GV.isMaterializable() ||
383 GV.hasExternalLinkage() ||
384 GV.hasDLLImportLinkage() ||
385 GV.hasExternalWeakLinkage() ||
386 (isa<GlobalAlias>(GV) &&
387 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
388 "Global is external, but doesn't have external or dllimport or weak linkage!",
391 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
392 "Global is marked as dllimport, but not external", &GV);
394 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
395 "Only global variables can have appending linkage!", &GV);
397 if (GV.hasAppendingLinkage()) {
398 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
399 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
400 "Only global arrays can have appending linkage!", GVar);
403 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
404 "linkonce_odr_auto_hide can only have default visibility!",
408 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
409 if (GV.hasInitializer()) {
410 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
411 "Global variable initializer type does not match global "
412 "variable type!", &GV);
414 // If the global has common linkage, it must have a zero initializer and
415 // cannot be constant.
416 if (GV.hasCommonLinkage()) {
417 Assert1(GV.getInitializer()->isNullValue(),
418 "'common' global must have a zero initializer!", &GV);
419 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
423 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
424 GV.hasExternalWeakLinkage(),
425 "invalid linkage type for global declaration", &GV);
428 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
429 GV.getName() == "llvm.global_dtors")) {
430 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
431 "invalid linkage for intrinsic global variable", &GV);
432 // Don't worry about emitting an error for it not being an array,
433 // visitGlobalValue will complain on appending non-array.
434 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
435 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
436 PointerType *FuncPtrTy =
437 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
438 Assert1(STy && STy->getNumElements() == 2 &&
439 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
440 STy->getTypeAtIndex(1) == FuncPtrTy,
441 "wrong type for intrinsic global variable", &GV);
445 visitGlobalValue(GV);
448 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
449 Assert1(!GA.getName().empty(),
450 "Alias name cannot be empty!", &GA);
451 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
453 "Alias should have external or external weak linkage!", &GA);
454 Assert1(GA.getAliasee(),
455 "Aliasee cannot be NULL!", &GA);
456 Assert1(GA.getType() == GA.getAliasee()->getType(),
457 "Alias and aliasee types should match!", &GA);
458 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
460 if (!isa<GlobalValue>(GA.getAliasee())) {
461 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
463 (CE->getOpcode() == Instruction::BitCast ||
464 CE->getOpcode() == Instruction::GetElementPtr) &&
465 isa<GlobalValue>(CE->getOperand(0)),
466 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
470 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
472 "Aliasing chain should end with function or global variable", &GA);
474 visitGlobalValue(GA);
477 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
478 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
479 MDNode *MD = NMD.getOperand(i);
483 Assert1(!MD->isFunctionLocal(),
484 "Named metadata operand cannot be function local!", MD);
489 void Verifier::visitMDNode(MDNode &MD, Function *F) {
490 // Only visit each node once. Metadata can be mutually recursive, so this
491 // avoids infinite recursion here, as well as being an optimization.
492 if (!MDNodes.insert(&MD))
495 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
496 Value *Op = MD.getOperand(i);
499 if (isa<Constant>(Op) || isa<MDString>(Op))
501 if (MDNode *N = dyn_cast<MDNode>(Op)) {
502 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
503 "Global metadata operand cannot be function local!", &MD, N);
507 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
509 // If this was an instruction, bb, or argument, verify that it is in the
510 // function that we expect.
511 Function *ActualF = 0;
512 if (Instruction *I = dyn_cast<Instruction>(Op))
513 ActualF = I->getParent()->getParent();
514 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
515 ActualF = BB->getParent();
516 else if (Argument *A = dyn_cast<Argument>(Op))
517 ActualF = A->getParent();
518 assert(ActualF && "Unimplemented function local metadata case!");
520 Assert2(ActualF == F, "function-local metadata used in wrong function",
525 // VerifyParameterAttrs - Check the given attributes for an argument or return
526 // value of the specified type. The value V is printed in error messages.
527 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
528 bool isReturnValue, const Value *V) {
529 if (!Attrs.hasAttributes())
532 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
533 Assert1(!FnCheckAttr, "Attribute " + FnCheckAttr.getAsString() +
534 " only applies to the function!", V);
537 Assert1(!Attrs.hasParameterOnlyAttrs(),
538 "Attributes 'byval', 'nest', 'sret', and 'nocapture' "
539 "do not apply to return values!", V);
542 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
543 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
544 Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
545 MutI.getAsString() + " are incompatible!", V);
548 Attributes TypeI = Attrs & Attributes::typeIncompatible(Ty);
549 Assert1(!TypeI, "Wrong type for attribute " +
550 TypeI.getAsString(), V);
552 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
553 Assert1(!Attrs.hasAttribute(Attributes::ByVal) ||
554 PTy->getElementType()->isSized(),
555 "Attribute 'byval' does not support unsized types!", V);
557 Assert1(!Attrs.hasAttribute(Attributes::ByVal),
558 "Attribute 'byval' only applies to parameters with pointer type!",
562 // VerifyFunctionAttrs - Check parameter attributes against a function type.
563 // The value V is printed in error messages.
564 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
565 const AttrListPtr &Attrs,
570 bool SawNest = false;
572 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
573 const AttributeWithIndex &Attr = Attrs.getSlot(i);
577 Ty = FT->getReturnType();
578 else if (Attr.Index-1 < FT->getNumParams())
579 Ty = FT->getParamType(Attr.Index-1);
581 break; // VarArgs attributes, verified elsewhere.
583 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
585 if (Attr.Attrs.hasAttribute(Attributes::Nest)) {
586 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
590 if (Attr.Attrs.hasAttribute(Attributes::StructRet))
591 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
594 Attributes FAttrs = Attrs.getFnAttributes();
595 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
596 Assert1(!NotFn, "Attribute " + NotFn.getAsString() +
597 " does not apply to the function!", V);
600 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
601 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
602 Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
603 MutI.getAsString() + " are incompatible!", V);
607 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
611 unsigned LastSlot = Attrs.getNumSlots() - 1;
612 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
613 if (LastIndex <= Params
614 || (LastIndex == (unsigned)~0
615 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
621 // visitFunction - Verify that a function is ok.
623 void Verifier::visitFunction(Function &F) {
624 // Check function arguments.
625 FunctionType *FT = F.getFunctionType();
626 unsigned NumArgs = F.arg_size();
628 Assert1(Context == &F.getContext(),
629 "Function context does not match Module context!", &F);
631 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
632 Assert2(FT->getNumParams() == NumArgs,
633 "# formal arguments must match # of arguments for function type!",
635 Assert1(F.getReturnType()->isFirstClassType() ||
636 F.getReturnType()->isVoidTy() ||
637 F.getReturnType()->isStructTy(),
638 "Functions cannot return aggregate values!", &F);
640 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
641 "Invalid struct return type!", &F);
643 const AttrListPtr &Attrs = F.getAttributes();
645 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
646 "Attributes after last parameter!", &F);
648 // Check function attributes.
649 VerifyFunctionAttrs(FT, Attrs, &F);
651 // Check that this function meets the restrictions on this calling convention.
652 switch (F.getCallingConv()) {
657 case CallingConv::Fast:
658 case CallingConv::Cold:
659 case CallingConv::X86_FastCall:
660 case CallingConv::X86_ThisCall:
661 case CallingConv::PTX_Kernel:
662 case CallingConv::PTX_Device:
663 Assert1(!F.isVarArg(),
664 "Varargs functions must have C calling conventions!", &F);
668 bool isLLVMdotName = F.getName().size() >= 5 &&
669 F.getName().substr(0, 5) == "llvm.";
671 // Check that the argument values match the function type for this function...
673 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
675 Assert2(I->getType() == FT->getParamType(i),
676 "Argument value does not match function argument type!",
677 I, FT->getParamType(i));
678 Assert1(I->getType()->isFirstClassType(),
679 "Function arguments must have first-class types!", I);
681 Assert2(!I->getType()->isMetadataTy(),
682 "Function takes metadata but isn't an intrinsic", I, &F);
685 if (F.isMaterializable()) {
686 // Function has a body somewhere we can't see.
687 } else if (F.isDeclaration()) {
688 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
689 F.hasExternalWeakLinkage(),
690 "invalid linkage type for function declaration", &F);
692 // Verify that this function (which has a body) is not named "llvm.*". It
693 // is not legal to define intrinsics.
694 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
696 // Check the entry node
697 BasicBlock *Entry = &F.getEntryBlock();
698 Assert1(pred_begin(Entry) == pred_end(Entry),
699 "Entry block to function must not have predecessors!", Entry);
701 // The address of the entry block cannot be taken, unless it is dead.
702 if (Entry->hasAddressTaken()) {
703 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
704 "blockaddress may not be used with the entry block!", Entry);
708 // If this function is actually an intrinsic, verify that it is only used in
709 // direct call/invokes, never having its "address taken".
710 if (F.getIntrinsicID()) {
712 if (F.hasAddressTaken(&U))
713 Assert1(0, "Invalid user of intrinsic instruction!", U);
717 // verifyBasicBlock - Verify that a basic block is well formed...
719 void Verifier::visitBasicBlock(BasicBlock &BB) {
720 InstsInThisBlock.clear();
722 // Ensure that basic blocks have terminators!
723 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
725 // Check constraints that this basic block imposes on all of the PHI nodes in
727 if (isa<PHINode>(BB.front())) {
728 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
729 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
730 std::sort(Preds.begin(), Preds.end());
732 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
733 // Ensure that PHI nodes have at least one entry!
734 Assert1(PN->getNumIncomingValues() != 0,
735 "PHI nodes must have at least one entry. If the block is dead, "
736 "the PHI should be removed!", PN);
737 Assert1(PN->getNumIncomingValues() == Preds.size(),
738 "PHINode should have one entry for each predecessor of its "
739 "parent basic block!", PN);
741 // Get and sort all incoming values in the PHI node...
743 Values.reserve(PN->getNumIncomingValues());
744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
745 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
746 PN->getIncomingValue(i)));
747 std::sort(Values.begin(), Values.end());
749 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
750 // Check to make sure that if there is more than one entry for a
751 // particular basic block in this PHI node, that the incoming values are
754 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
755 Values[i].second == Values[i-1].second,
756 "PHI node has multiple entries for the same basic block with "
757 "different incoming values!", PN, Values[i].first,
758 Values[i].second, Values[i-1].second);
760 // Check to make sure that the predecessors and PHI node entries are
762 Assert3(Values[i].first == Preds[i],
763 "PHI node entries do not match predecessors!", PN,
764 Values[i].first, Preds[i]);
770 void Verifier::visitTerminatorInst(TerminatorInst &I) {
771 // Ensure that terminators only exist at the end of the basic block.
772 Assert1(&I == I.getParent()->getTerminator(),
773 "Terminator found in the middle of a basic block!", I.getParent());
777 void Verifier::visitBranchInst(BranchInst &BI) {
778 if (BI.isConditional()) {
779 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
780 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
782 visitTerminatorInst(BI);
785 void Verifier::visitReturnInst(ReturnInst &RI) {
786 Function *F = RI.getParent()->getParent();
787 unsigned N = RI.getNumOperands();
788 if (F->getReturnType()->isVoidTy())
790 "Found return instr that returns non-void in Function of void "
791 "return type!", &RI, F->getReturnType());
793 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
794 "Function return type does not match operand "
795 "type of return inst!", &RI, F->getReturnType());
797 // Check to make sure that the return value has necessary properties for
799 visitTerminatorInst(RI);
802 void Verifier::visitSwitchInst(SwitchInst &SI) {
803 // Check to make sure that all of the constants in the switch instruction
804 // have the same type as the switched-on value.
805 Type *SwitchTy = SI.getCondition()->getType();
806 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
807 IntegersSubsetToBB Mapping;
808 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
809 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
810 IntegersSubset CaseRanges = i.getCaseValueEx();
811 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
812 IntegersSubset::Range r = CaseRanges.getItem(ri);
813 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
814 "Switch constants must all be same type as switch value!", &SI);
815 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
816 "Switch constants must all be same type as switch value!", &SI);
818 RangeSetMap[r] = i.getCaseIndex();
822 IntegersSubsetToBB::RangeIterator errItem;
823 if (!Mapping.verify(errItem)) {
824 unsigned CaseIndex = RangeSetMap[errItem->first];
825 SwitchInst::CaseIt i(&SI, CaseIndex);
826 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
829 visitTerminatorInst(SI);
832 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
833 Assert1(BI.getAddress()->getType()->isPointerTy(),
834 "Indirectbr operand must have pointer type!", &BI);
835 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
836 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
837 "Indirectbr destinations must all have pointer type!", &BI);
839 visitTerminatorInst(BI);
842 void Verifier::visitSelectInst(SelectInst &SI) {
843 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
845 "Invalid operands for select instruction!", &SI);
847 Assert1(SI.getTrueValue()->getType() == SI.getType(),
848 "Select values must have same type as select instruction!", &SI);
849 visitInstruction(SI);
852 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
853 /// a pass, if any exist, it's an error.
855 void Verifier::visitUserOp1(Instruction &I) {
856 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
859 void Verifier::visitTruncInst(TruncInst &I) {
860 // Get the source and destination types
861 Type *SrcTy = I.getOperand(0)->getType();
862 Type *DestTy = I.getType();
864 // Get the size of the types in bits, we'll need this later
865 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
866 unsigned DestBitSize = DestTy->getScalarSizeInBits();
868 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
869 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
870 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
871 "trunc source and destination must both be a vector or neither", &I);
872 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
877 void Verifier::visitZExtInst(ZExtInst &I) {
878 // Get the source and destination types
879 Type *SrcTy = I.getOperand(0)->getType();
880 Type *DestTy = I.getType();
882 // Get the size of the types in bits, we'll need this later
883 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
884 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
885 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
886 "zext source and destination must both be a vector or neither", &I);
887 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
888 unsigned DestBitSize = DestTy->getScalarSizeInBits();
890 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
895 void Verifier::visitSExtInst(SExtInst &I) {
896 // Get the source and destination types
897 Type *SrcTy = I.getOperand(0)->getType();
898 Type *DestTy = I.getType();
900 // Get the size of the types in bits, we'll need this later
901 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
902 unsigned DestBitSize = DestTy->getScalarSizeInBits();
904 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
905 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
906 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
907 "sext source and destination must both be a vector or neither", &I);
908 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
913 void Verifier::visitFPTruncInst(FPTruncInst &I) {
914 // Get the source and destination types
915 Type *SrcTy = I.getOperand(0)->getType();
916 Type *DestTy = I.getType();
917 // Get the size of the types in bits, we'll need this later
918 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
919 unsigned DestBitSize = DestTy->getScalarSizeInBits();
921 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
922 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
923 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
924 "fptrunc source and destination must both be a vector or neither",&I);
925 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
930 void Verifier::visitFPExtInst(FPExtInst &I) {
931 // Get the source and destination types
932 Type *SrcTy = I.getOperand(0)->getType();
933 Type *DestTy = I.getType();
935 // Get the size of the types in bits, we'll need this later
936 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
937 unsigned DestBitSize = DestTy->getScalarSizeInBits();
939 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
940 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
941 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
942 "fpext source and destination must both be a vector or neither", &I);
943 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
948 void Verifier::visitUIToFPInst(UIToFPInst &I) {
949 // Get the source and destination types
950 Type *SrcTy = I.getOperand(0)->getType();
951 Type *DestTy = I.getType();
953 bool SrcVec = SrcTy->isVectorTy();
954 bool DstVec = DestTy->isVectorTy();
956 Assert1(SrcVec == DstVec,
957 "UIToFP source and dest must both be vector or scalar", &I);
958 Assert1(SrcTy->isIntOrIntVectorTy(),
959 "UIToFP source must be integer or integer vector", &I);
960 Assert1(DestTy->isFPOrFPVectorTy(),
961 "UIToFP result must be FP or FP vector", &I);
963 if (SrcVec && DstVec)
964 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
965 cast<VectorType>(DestTy)->getNumElements(),
966 "UIToFP source and dest vector length mismatch", &I);
971 void Verifier::visitSIToFPInst(SIToFPInst &I) {
972 // Get the source and destination types
973 Type *SrcTy = I.getOperand(0)->getType();
974 Type *DestTy = I.getType();
976 bool SrcVec = SrcTy->isVectorTy();
977 bool DstVec = DestTy->isVectorTy();
979 Assert1(SrcVec == DstVec,
980 "SIToFP source and dest must both be vector or scalar", &I);
981 Assert1(SrcTy->isIntOrIntVectorTy(),
982 "SIToFP source must be integer or integer vector", &I);
983 Assert1(DestTy->isFPOrFPVectorTy(),
984 "SIToFP result must be FP or FP vector", &I);
986 if (SrcVec && DstVec)
987 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
988 cast<VectorType>(DestTy)->getNumElements(),
989 "SIToFP source and dest vector length mismatch", &I);
994 void Verifier::visitFPToUIInst(FPToUIInst &I) {
995 // Get the source and destination types
996 Type *SrcTy = I.getOperand(0)->getType();
997 Type *DestTy = I.getType();
999 bool SrcVec = SrcTy->isVectorTy();
1000 bool DstVec = DestTy->isVectorTy();
1002 Assert1(SrcVec == DstVec,
1003 "FPToUI source and dest must both be vector or scalar", &I);
1004 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1006 Assert1(DestTy->isIntOrIntVectorTy(),
1007 "FPToUI result must be integer or integer vector", &I);
1009 if (SrcVec && DstVec)
1010 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1011 cast<VectorType>(DestTy)->getNumElements(),
1012 "FPToUI source and dest vector length mismatch", &I);
1014 visitInstruction(I);
1017 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1018 // Get the source and destination types
1019 Type *SrcTy = I.getOperand(0)->getType();
1020 Type *DestTy = I.getType();
1022 bool SrcVec = SrcTy->isVectorTy();
1023 bool DstVec = DestTy->isVectorTy();
1025 Assert1(SrcVec == DstVec,
1026 "FPToSI source and dest must both be vector or scalar", &I);
1027 Assert1(SrcTy->isFPOrFPVectorTy(),
1028 "FPToSI source must be FP or FP vector", &I);
1029 Assert1(DestTy->isIntOrIntVectorTy(),
1030 "FPToSI result must be integer or integer vector", &I);
1032 if (SrcVec && DstVec)
1033 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1034 cast<VectorType>(DestTy)->getNumElements(),
1035 "FPToSI source and dest vector length mismatch", &I);
1037 visitInstruction(I);
1040 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1041 // Get the source and destination types
1042 Type *SrcTy = I.getOperand(0)->getType();
1043 Type *DestTy = I.getType();
1045 Assert1(SrcTy->getScalarType()->isPointerTy(),
1046 "PtrToInt source must be pointer", &I);
1047 Assert1(DestTy->getScalarType()->isIntegerTy(),
1048 "PtrToInt result must be integral", &I);
1049 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1050 "PtrToInt type mismatch", &I);
1052 if (SrcTy->isVectorTy()) {
1053 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1054 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1055 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1056 "PtrToInt Vector width mismatch", &I);
1059 visitInstruction(I);
1062 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1063 // Get the source and destination types
1064 Type *SrcTy = I.getOperand(0)->getType();
1065 Type *DestTy = I.getType();
1067 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1068 "IntToPtr source must be an integral", &I);
1069 Assert1(DestTy->getScalarType()->isPointerTy(),
1070 "IntToPtr result must be a pointer",&I);
1071 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1072 "IntToPtr type mismatch", &I);
1073 if (SrcTy->isVectorTy()) {
1074 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1075 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1076 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1077 "IntToPtr Vector width mismatch", &I);
1079 visitInstruction(I);
1082 void Verifier::visitBitCastInst(BitCastInst &I) {
1083 // Get the source and destination types
1084 Type *SrcTy = I.getOperand(0)->getType();
1085 Type *DestTy = I.getType();
1087 // Get the size of the types in bits, we'll need this later
1088 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1089 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1091 // BitCast implies a no-op cast of type only. No bits change.
1092 // However, you can't cast pointers to anything but pointers.
1093 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1094 "Bitcast requires both operands to be pointer or neither", &I);
1095 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1097 // Disallow aggregates.
1098 Assert1(!SrcTy->isAggregateType(),
1099 "Bitcast operand must not be aggregate", &I);
1100 Assert1(!DestTy->isAggregateType(),
1101 "Bitcast type must not be aggregate", &I);
1103 visitInstruction(I);
1106 /// visitPHINode - Ensure that a PHI node is well formed.
1108 void Verifier::visitPHINode(PHINode &PN) {
1109 // Ensure that the PHI nodes are all grouped together at the top of the block.
1110 // This can be tested by checking whether the instruction before this is
1111 // either nonexistent (because this is begin()) or is a PHI node. If not,
1112 // then there is some other instruction before a PHI.
1113 Assert2(&PN == &PN.getParent()->front() ||
1114 isa<PHINode>(--BasicBlock::iterator(&PN)),
1115 "PHI nodes not grouped at top of basic block!",
1116 &PN, PN.getParent());
1118 // Check that all of the values of the PHI node have the same type as the
1119 // result, and that the incoming blocks are really basic blocks.
1120 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1121 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1122 "PHI node operands are not the same type as the result!", &PN);
1125 // All other PHI node constraints are checked in the visitBasicBlock method.
1127 visitInstruction(PN);
1130 void Verifier::VerifyCallSite(CallSite CS) {
1131 Instruction *I = CS.getInstruction();
1133 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1134 "Called function must be a pointer!", I);
1135 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1137 Assert1(FPTy->getElementType()->isFunctionTy(),
1138 "Called function is not pointer to function type!", I);
1139 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1141 // Verify that the correct number of arguments are being passed
1142 if (FTy->isVarArg())
1143 Assert1(CS.arg_size() >= FTy->getNumParams(),
1144 "Called function requires more parameters than were provided!",I);
1146 Assert1(CS.arg_size() == FTy->getNumParams(),
1147 "Incorrect number of arguments passed to called function!", I);
1149 // Verify that all arguments to the call match the function type.
1150 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1151 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1152 "Call parameter type does not match function signature!",
1153 CS.getArgument(i), FTy->getParamType(i), I);
1155 const AttrListPtr &Attrs = CS.getAttributes();
1157 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1158 "Attributes after last parameter!", I);
1160 // Verify call attributes.
1161 VerifyFunctionAttrs(FTy, Attrs, I);
1163 if (FTy->isVarArg())
1164 // Check attributes on the varargs part.
1165 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1166 Attributes Attr = Attrs.getParamAttributes(Idx);
1168 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1170 Assert1(!Attr.hasIncompatibleWithVarArgsAttrs(),
1171 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1174 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1175 if (CS.getCalledFunction() == 0 ||
1176 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1177 for (FunctionType::param_iterator PI = FTy->param_begin(),
1178 PE = FTy->param_end(); PI != PE; ++PI)
1179 Assert1(!(*PI)->isMetadataTy(),
1180 "Function has metadata parameter but isn't an intrinsic", I);
1183 visitInstruction(*I);
1186 void Verifier::visitCallInst(CallInst &CI) {
1187 VerifyCallSite(&CI);
1189 if (Function *F = CI.getCalledFunction())
1190 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1191 visitIntrinsicFunctionCall(ID, CI);
1194 void Verifier::visitInvokeInst(InvokeInst &II) {
1195 VerifyCallSite(&II);
1197 // Verify that there is a landingpad instruction as the first non-PHI
1198 // instruction of the 'unwind' destination.
1199 Assert1(II.getUnwindDest()->isLandingPad(),
1200 "The unwind destination does not have a landingpad instruction!",&II);
1202 visitTerminatorInst(II);
1205 /// visitBinaryOperator - Check that both arguments to the binary operator are
1206 /// of the same type!
1208 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1209 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1210 "Both operands to a binary operator are not of the same type!", &B);
1212 switch (B.getOpcode()) {
1213 // Check that integer arithmetic operators are only used with
1214 // integral operands.
1215 case Instruction::Add:
1216 case Instruction::Sub:
1217 case Instruction::Mul:
1218 case Instruction::SDiv:
1219 case Instruction::UDiv:
1220 case Instruction::SRem:
1221 case Instruction::URem:
1222 Assert1(B.getType()->isIntOrIntVectorTy(),
1223 "Integer arithmetic operators only work with integral types!", &B);
1224 Assert1(B.getType() == B.getOperand(0)->getType(),
1225 "Integer arithmetic operators must have same type "
1226 "for operands and result!", &B);
1228 // Check that floating-point arithmetic operators are only used with
1229 // floating-point operands.
1230 case Instruction::FAdd:
1231 case Instruction::FSub:
1232 case Instruction::FMul:
1233 case Instruction::FDiv:
1234 case Instruction::FRem:
1235 Assert1(B.getType()->isFPOrFPVectorTy(),
1236 "Floating-point arithmetic operators only work with "
1237 "floating-point types!", &B);
1238 Assert1(B.getType() == B.getOperand(0)->getType(),
1239 "Floating-point arithmetic operators must have same type "
1240 "for operands and result!", &B);
1242 // Check that logical operators are only used with integral operands.
1243 case Instruction::And:
1244 case Instruction::Or:
1245 case Instruction::Xor:
1246 Assert1(B.getType()->isIntOrIntVectorTy(),
1247 "Logical operators only work with integral types!", &B);
1248 Assert1(B.getType() == B.getOperand(0)->getType(),
1249 "Logical operators must have same type for operands and result!",
1252 case Instruction::Shl:
1253 case Instruction::LShr:
1254 case Instruction::AShr:
1255 Assert1(B.getType()->isIntOrIntVectorTy(),
1256 "Shifts only work with integral types!", &B);
1257 Assert1(B.getType() == B.getOperand(0)->getType(),
1258 "Shift return type must be same as operands!", &B);
1261 llvm_unreachable("Unknown BinaryOperator opcode!");
1264 visitInstruction(B);
1267 void Verifier::visitICmpInst(ICmpInst &IC) {
1268 // Check that the operands are the same type
1269 Type *Op0Ty = IC.getOperand(0)->getType();
1270 Type *Op1Ty = IC.getOperand(1)->getType();
1271 Assert1(Op0Ty == Op1Ty,
1272 "Both operands to ICmp instruction are not of the same type!", &IC);
1273 // Check that the operands are the right type
1274 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1275 "Invalid operand types for ICmp instruction", &IC);
1276 // Check that the predicate is valid.
1277 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1278 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1279 "Invalid predicate in ICmp instruction!", &IC);
1281 visitInstruction(IC);
1284 void Verifier::visitFCmpInst(FCmpInst &FC) {
1285 // Check that the operands are the same type
1286 Type *Op0Ty = FC.getOperand(0)->getType();
1287 Type *Op1Ty = FC.getOperand(1)->getType();
1288 Assert1(Op0Ty == Op1Ty,
1289 "Both operands to FCmp instruction are not of the same type!", &FC);
1290 // Check that the operands are the right type
1291 Assert1(Op0Ty->isFPOrFPVectorTy(),
1292 "Invalid operand types for FCmp instruction", &FC);
1293 // Check that the predicate is valid.
1294 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1295 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1296 "Invalid predicate in FCmp instruction!", &FC);
1298 visitInstruction(FC);
1301 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1302 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1304 "Invalid extractelement operands!", &EI);
1305 visitInstruction(EI);
1308 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1309 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1312 "Invalid insertelement operands!", &IE);
1313 visitInstruction(IE);
1316 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1317 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1319 "Invalid shufflevector operands!", &SV);
1320 visitInstruction(SV);
1323 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1324 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1326 Assert1(isa<PointerType>(TargetTy),
1327 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1328 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1329 "GEP into unsized type!", &GEP);
1331 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1333 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1334 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1336 if (GEP.getPointerOperandType()->isPointerTy()) {
1337 // Validate GEPs with scalar indices.
1338 Assert2(GEP.getType()->isPointerTy() &&
1339 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1340 "GEP is not of right type for indices!", &GEP, ElTy);
1342 // Validate GEPs with a vector index.
1343 Assert1(Idxs.size() == 1, "Invalid number of indices!", &GEP);
1344 Value *Index = Idxs[0];
1345 Type *IndexTy = Index->getType();
1346 Assert1(IndexTy->isVectorTy(),
1347 "Vector GEP must have vector indices!", &GEP);
1348 Assert1(GEP.getType()->isVectorTy(),
1349 "Vector GEP must return a vector value", &GEP);
1350 Type *ElemPtr = cast<VectorType>(GEP.getType())->getElementType();
1351 Assert1(ElemPtr->isPointerTy(),
1352 "Vector GEP pointer operand is not a pointer!", &GEP);
1353 unsigned IndexWidth = cast<VectorType>(IndexTy)->getNumElements();
1354 unsigned GepWidth = cast<VectorType>(GEP.getType())->getNumElements();
1355 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1356 Assert1(ElTy == cast<PointerType>(ElemPtr)->getElementType(),
1357 "Vector GEP type does not match pointer type!", &GEP);
1359 visitInstruction(GEP);
1362 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1363 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1366 void Verifier::visitLoadInst(LoadInst &LI) {
1367 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1368 Assert1(PTy, "Load operand must be a pointer.", &LI);
1369 Type *ElTy = PTy->getElementType();
1370 Assert2(ElTy == LI.getType(),
1371 "Load result type does not match pointer operand type!", &LI, ElTy);
1372 if (LI.isAtomic()) {
1373 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1374 "Load cannot have Release ordering", &LI);
1375 Assert1(LI.getAlignment() != 0,
1376 "Atomic load must specify explicit alignment", &LI);
1377 if (!ElTy->isPointerTy()) {
1378 Assert2(ElTy->isIntegerTy(),
1379 "atomic store operand must have integer type!",
1381 unsigned Size = ElTy->getPrimitiveSizeInBits();
1382 Assert2(Size >= 8 && !(Size & (Size - 1)),
1383 "atomic store operand must be power-of-two byte-sized integer",
1387 Assert1(LI.getSynchScope() == CrossThread,
1388 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1391 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1392 unsigned NumOperands = Range->getNumOperands();
1393 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1394 unsigned NumRanges = NumOperands / 2;
1395 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1397 ConstantRange LastRange(1); // Dummy initial value
1398 for (unsigned i = 0; i < NumRanges; ++i) {
1399 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1400 Assert1(Low, "The lower limit must be an integer!", Low);
1401 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1402 Assert1(High, "The upper limit must be an integer!", High);
1403 Assert1(High->getType() == Low->getType() &&
1404 High->getType() == ElTy, "Range types must match load type!",
1407 APInt HighV = High->getValue();
1408 APInt LowV = Low->getValue();
1409 ConstantRange CurRange(LowV, HighV);
1410 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1411 "Range must not be empty!", Range);
1413 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1414 "Intervals are overlapping", Range);
1415 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1417 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1420 LastRange = ConstantRange(LowV, HighV);
1422 if (NumRanges > 2) {
1424 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1426 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1427 ConstantRange FirstRange(FirstLow, FirstHigh);
1428 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1429 "Intervals are overlapping", Range);
1430 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1437 visitInstruction(LI);
1440 void Verifier::visitStoreInst(StoreInst &SI) {
1441 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1442 Assert1(PTy, "Store operand must be a pointer.", &SI);
1443 Type *ElTy = PTy->getElementType();
1444 Assert2(ElTy == SI.getOperand(0)->getType(),
1445 "Stored value type does not match pointer operand type!",
1447 if (SI.isAtomic()) {
1448 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1449 "Store cannot have Acquire ordering", &SI);
1450 Assert1(SI.getAlignment() != 0,
1451 "Atomic store must specify explicit alignment", &SI);
1452 if (!ElTy->isPointerTy()) {
1453 Assert2(ElTy->isIntegerTy(),
1454 "atomic store operand must have integer type!",
1456 unsigned Size = ElTy->getPrimitiveSizeInBits();
1457 Assert2(Size >= 8 && !(Size & (Size - 1)),
1458 "atomic store operand must be power-of-two byte-sized integer",
1462 Assert1(SI.getSynchScope() == CrossThread,
1463 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1465 visitInstruction(SI);
1468 void Verifier::visitAllocaInst(AllocaInst &AI) {
1469 PointerType *PTy = AI.getType();
1470 Assert1(PTy->getAddressSpace() == 0,
1471 "Allocation instruction pointer not in the generic address space!",
1473 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1475 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1476 "Alloca array size must have integer type", &AI);
1477 visitInstruction(AI);
1480 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1481 Assert1(CXI.getOrdering() != NotAtomic,
1482 "cmpxchg instructions must be atomic.", &CXI);
1483 Assert1(CXI.getOrdering() != Unordered,
1484 "cmpxchg instructions cannot be unordered.", &CXI);
1485 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1486 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1487 Type *ElTy = PTy->getElementType();
1488 Assert2(ElTy->isIntegerTy(),
1489 "cmpxchg operand must have integer type!",
1491 unsigned Size = ElTy->getPrimitiveSizeInBits();
1492 Assert2(Size >= 8 && !(Size & (Size - 1)),
1493 "cmpxchg operand must be power-of-two byte-sized integer",
1495 Assert2(ElTy == CXI.getOperand(1)->getType(),
1496 "Expected value type does not match pointer operand type!",
1498 Assert2(ElTy == CXI.getOperand(2)->getType(),
1499 "Stored value type does not match pointer operand type!",
1501 visitInstruction(CXI);
1504 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1505 Assert1(RMWI.getOrdering() != NotAtomic,
1506 "atomicrmw instructions must be atomic.", &RMWI);
1507 Assert1(RMWI.getOrdering() != Unordered,
1508 "atomicrmw instructions cannot be unordered.", &RMWI);
1509 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1510 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1511 Type *ElTy = PTy->getElementType();
1512 Assert2(ElTy->isIntegerTy(),
1513 "atomicrmw operand must have integer type!",
1515 unsigned Size = ElTy->getPrimitiveSizeInBits();
1516 Assert2(Size >= 8 && !(Size & (Size - 1)),
1517 "atomicrmw operand must be power-of-two byte-sized integer",
1519 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1520 "Argument value type does not match pointer operand type!",
1522 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1523 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1524 "Invalid binary operation!", &RMWI);
1525 visitInstruction(RMWI);
1528 void Verifier::visitFenceInst(FenceInst &FI) {
1529 const AtomicOrdering Ordering = FI.getOrdering();
1530 Assert1(Ordering == Acquire || Ordering == Release ||
1531 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1532 "fence instructions may only have "
1533 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1534 visitInstruction(FI);
1537 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1538 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1539 EVI.getIndices()) ==
1541 "Invalid ExtractValueInst operands!", &EVI);
1543 visitInstruction(EVI);
1546 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1547 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1548 IVI.getIndices()) ==
1549 IVI.getOperand(1)->getType(),
1550 "Invalid InsertValueInst operands!", &IVI);
1552 visitInstruction(IVI);
1555 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1556 BasicBlock *BB = LPI.getParent();
1558 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1560 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1561 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1563 // The landingpad instruction defines its parent as a landing pad block. The
1564 // landing pad block may be branched to only by the unwind edge of an invoke.
1565 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1566 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1567 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1568 "Block containing LandingPadInst must be jumped to "
1569 "only by the unwind edge of an invoke.", &LPI);
1572 // The landingpad instruction must be the first non-PHI instruction in the
1574 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1575 "LandingPadInst not the first non-PHI instruction in the block.",
1578 // The personality functions for all landingpad instructions within the same
1579 // function should match.
1581 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1582 "Personality function doesn't match others in function", &LPI);
1583 PersonalityFn = LPI.getPersonalityFn();
1585 // All operands must be constants.
1586 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1588 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1589 Value *Clause = LPI.getClause(i);
1590 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1591 if (LPI.isCatch(i)) {
1592 Assert1(isa<PointerType>(Clause->getType()),
1593 "Catch operand does not have pointer type!", &LPI);
1595 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1596 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1597 "Filter operand is not an array of constants!", &LPI);
1601 visitInstruction(LPI);
1604 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1605 Instruction *Op = cast<Instruction>(I.getOperand(i));
1606 // If the we have an invalid invoke, don't try to compute the dominance.
1607 // We already reject it in the invoke specific checks and the dominance
1608 // computation doesn't handle multiple edges.
1609 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1610 if (II->getNormalDest() == II->getUnwindDest())
1614 const Use &U = I.getOperandUse(i);
1615 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1616 "Instruction does not dominate all uses!", Op, &I);
1619 /// verifyInstruction - Verify that an instruction is well formed.
1621 void Verifier::visitInstruction(Instruction &I) {
1622 BasicBlock *BB = I.getParent();
1623 Assert1(BB, "Instruction not embedded in basic block!", &I);
1625 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1626 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1628 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1629 "Only PHI nodes may reference their own value!", &I);
1632 // Check that void typed values don't have names
1633 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1634 "Instruction has a name, but provides a void value!", &I);
1636 // Check that the return value of the instruction is either void or a legal
1638 Assert1(I.getType()->isVoidTy() ||
1639 I.getType()->isFirstClassType(),
1640 "Instruction returns a non-scalar type!", &I);
1642 // Check that the instruction doesn't produce metadata. Calls are already
1643 // checked against the callee type.
1644 Assert1(!I.getType()->isMetadataTy() ||
1645 isa<CallInst>(I) || isa<InvokeInst>(I),
1646 "Invalid use of metadata!", &I);
1648 // Check that all uses of the instruction, if they are instructions
1649 // themselves, actually have parent basic blocks. If the use is not an
1650 // instruction, it is an error!
1651 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1653 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1654 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1655 " embedded in a basic block!", &I, Used);
1657 CheckFailed("Use of instruction is not an instruction!", *UI);
1662 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1663 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1665 // Check to make sure that only first-class-values are operands to
1667 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1668 Assert1(0, "Instruction operands must be first-class values!", &I);
1671 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1672 // Check to make sure that the "address of" an intrinsic function is never
1674 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1675 "Cannot take the address of an intrinsic!", &I);
1676 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1677 F->getIntrinsicID() == Intrinsic::donothing,
1678 "Cannot invoke an intrinsinc other than donothing", &I);
1679 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1681 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1682 Assert1(OpBB->getParent() == BB->getParent(),
1683 "Referring to a basic block in another function!", &I);
1684 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1685 Assert1(OpArg->getParent() == BB->getParent(),
1686 "Referring to an argument in another function!", &I);
1687 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1688 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1690 } else if (isa<Instruction>(I.getOperand(i))) {
1691 verifyDominatesUse(I, i);
1692 } else if (isa<InlineAsm>(I.getOperand(i))) {
1693 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1694 (i + 3 == e && isa<InvokeInst>(I)),
1695 "Cannot take the address of an inline asm!", &I);
1699 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1700 Assert1(I.getType()->isFPOrFPVectorTy(),
1701 "fpmath requires a floating point result!", &I);
1702 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1703 Value *Op0 = MD->getOperand(0);
1704 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1705 APFloat Accuracy = CFP0->getValueAPF();
1706 Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
1707 "fpmath accuracy not a positive number!", &I);
1709 Assert1(false, "invalid fpmath accuracy!", &I);
1713 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1714 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1716 InstsInThisBlock.insert(&I);
1719 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
1720 /// intrinsic argument or return value) matches the type constraints specified
1721 /// by the .td file (e.g. an "any integer" argument really is an integer).
1723 /// This return true on error but does not print a message.
1724 bool Verifier::VerifyIntrinsicType(Type *Ty,
1725 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1726 SmallVectorImpl<Type*> &ArgTys) {
1727 using namespace Intrinsic;
1729 // If we ran out of descriptors, there are too many arguments.
1730 if (Infos.empty()) return true;
1731 IITDescriptor D = Infos.front();
1732 Infos = Infos.slice(1);
1735 case IITDescriptor::Void: return !Ty->isVoidTy();
1736 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1737 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1738 case IITDescriptor::Float: return !Ty->isFloatTy();
1739 case IITDescriptor::Double: return !Ty->isDoubleTy();
1740 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1741 case IITDescriptor::Vector: {
1742 VectorType *VT = dyn_cast<VectorType>(Ty);
1743 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
1744 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
1746 case IITDescriptor::Pointer: {
1747 PointerType *PT = dyn_cast<PointerType>(Ty);
1748 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1749 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
1752 case IITDescriptor::Struct: {
1753 StructType *ST = dyn_cast<StructType>(Ty);
1754 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
1757 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1758 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
1763 case IITDescriptor::Argument:
1764 // Two cases here - If this is the second occurrence of an argument, verify
1765 // that the later instance matches the previous instance.
1766 if (D.getArgumentNumber() < ArgTys.size())
1767 return Ty != ArgTys[D.getArgumentNumber()];
1769 // Otherwise, if this is the first instance of an argument, record it and
1770 // verify the "Any" kind.
1771 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1772 ArgTys.push_back(Ty);
1774 switch (D.getArgumentKind()) {
1775 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1776 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1777 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1778 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1780 llvm_unreachable("all argument kinds not covered");
1782 case IITDescriptor::ExtendVecArgument:
1783 // This may only be used when referring to a previous vector argument.
1784 return D.getArgumentNumber() >= ArgTys.size() ||
1785 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1786 VectorType::getExtendedElementVectorType(
1787 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1789 case IITDescriptor::TruncVecArgument:
1790 // This may only be used when referring to a previous vector argument.
1791 return D.getArgumentNumber() >= ArgTys.size() ||
1792 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1793 VectorType::getTruncatedElementVectorType(
1794 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1796 llvm_unreachable("unhandled");
1799 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1801 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1802 Function *IF = CI.getCalledFunction();
1803 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1806 // Verify that the intrinsic prototype lines up with what the .td files
1808 FunctionType *IFTy = IF->getFunctionType();
1809 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
1811 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1812 getIntrinsicInfoTableEntries(ID, Table);
1813 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1815 SmallVector<Type *, 4> ArgTys;
1816 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
1817 "Intrinsic has incorrect return type!", IF);
1818 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
1819 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
1820 "Intrinsic has incorrect argument type!", IF);
1821 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
1823 // Now that we have the intrinsic ID and the actual argument types (and we
1824 // know they are legal for the intrinsic!) get the intrinsic name through the
1825 // usual means. This allows us to verify the mangling of argument types into
1827 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
1828 "Intrinsic name not mangled correctly for type arguments!", IF);
1830 // If the intrinsic takes MDNode arguments, verify that they are either global
1831 // or are local to *this* function.
1832 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1833 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1834 visitMDNode(*MD, CI.getParent()->getParent());
1839 case Intrinsic::ctlz: // llvm.ctlz
1840 case Intrinsic::cttz: // llvm.cttz
1841 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1842 "is_zero_undef argument of bit counting intrinsics must be a "
1843 "constant int", &CI);
1845 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1846 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1847 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1848 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1849 Assert1(MD->getNumOperands() == 1,
1850 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1852 case Intrinsic::memcpy:
1853 case Intrinsic::memmove:
1854 case Intrinsic::memset:
1855 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1856 "alignment argument of memory intrinsics must be a constant int",
1858 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1859 "isvolatile argument of memory intrinsics must be a constant int",
1862 case Intrinsic::gcroot:
1863 case Intrinsic::gcwrite:
1864 case Intrinsic::gcread:
1865 if (ID == Intrinsic::gcroot) {
1867 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1868 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1869 Assert1(isa<Constant>(CI.getArgOperand(1)),
1870 "llvm.gcroot parameter #2 must be a constant.", &CI);
1871 if (!AI->getType()->getElementType()->isPointerTy()) {
1872 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1873 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1874 "or argument #2 must be a non-null constant.", &CI);
1878 Assert1(CI.getParent()->getParent()->hasGC(),
1879 "Enclosing function does not use GC.", &CI);
1881 case Intrinsic::init_trampoline:
1882 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1883 "llvm.init_trampoline parameter #2 must resolve to a function.",
1886 case Intrinsic::prefetch:
1887 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1888 isa<ConstantInt>(CI.getArgOperand(2)) &&
1889 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1890 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1891 "invalid arguments to llvm.prefetch",
1894 case Intrinsic::stackprotector:
1895 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1896 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1899 case Intrinsic::lifetime_start:
1900 case Intrinsic::lifetime_end:
1901 case Intrinsic::invariant_start:
1902 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1903 "size argument of memory use markers must be a constant integer",
1906 case Intrinsic::invariant_end:
1907 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1908 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1913 //===----------------------------------------------------------------------===//
1914 // Implement the public interfaces to this file...
1915 //===----------------------------------------------------------------------===//
1917 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1918 return new Verifier(action);
1922 /// verifyFunction - Check a function for errors, printing messages on stderr.
1923 /// Return true if the function is corrupt.
1925 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1926 Function &F = const_cast<Function&>(f);
1927 assert(!F.isDeclaration() && "Cannot verify external functions");
1929 FunctionPassManager FPM(F.getParent());
1930 Verifier *V = new Verifier(action);
1936 /// verifyModule - Check a module for errors, printing messages on stderr.
1937 /// Return true if the module is corrupt.
1939 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1940 std::string *ErrorInfo) {
1942 Verifier *V = new Verifier(action);
1944 PM.run(const_cast<Module&>(M));
1946 if (ErrorInfo && V->Broken)
1947 *ErrorInfo = V->MessagesStr.str();