1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
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 // * All other things that are tested by asserts spread about the code...
40 //===----------------------------------------------------------------------===//
42 #include "llvm/Analysis/Verifier.h"
43 #include "llvm/CallingConv.h"
44 #include "llvm/Constants.h"
45 #include "llvm/DerivedTypes.h"
46 #include "llvm/InlineAsm.h"
47 #include "llvm/IntrinsicInst.h"
48 #include "llvm/Metadata.h"
49 #include "llvm/Module.h"
50 #include "llvm/Pass.h"
51 #include "llvm/PassManager.h"
52 #include "llvm/TypeSymbolTable.h"
53 #include "llvm/Analysis/Dominators.h"
54 #include "llvm/Assembly/Writer.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/Support/CallSite.h"
57 #include "llvm/Support/CFG.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/InstVisitor.h"
60 #include "llvm/ADT/SetVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/StringExtras.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
71 namespace { // Anonymous namespace for class
72 struct PreVerifier : public FunctionPass {
73 static char ID; // Pass ID, replacement for typeid
75 PreVerifier() : FunctionPass(ID) { }
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
81 // Check that the prerequisites for successful DominatorTree construction
83 bool runOnFunction(Function &F) {
86 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
87 if (I->empty() || !I->back().isTerminator()) {
88 dbgs() << "Basic Block in function '" << F.getName()
89 << "' does not have terminator!\n";
90 WriteAsOperand(dbgs(), I, true);
97 report_fatal_error("Broken module, no Basic Block terminator!");
104 char PreVerifier::ID = 0;
105 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
107 char &PreVerifyID = PreVerifier::ID;
110 class TypeSet : public AbstractTypeUser {
114 /// Insert a type into the set of types.
115 bool insert(const Type *Ty) {
116 if (!Types.insert(Ty))
118 if (Ty->isAbstract())
119 Ty->addAbstractTypeUser(this);
123 // Remove ourselves as abstract type listeners for any types that remain
124 // abstract when the TypeSet is destroyed.
126 for (SmallSetVector<const Type *, 16>::iterator I = Types.begin(),
127 E = Types.end(); I != E; ++I) {
129 if (Ty->isAbstract())
130 Ty->removeAbstractTypeUser(this);
134 // Abstract type user interface.
136 /// Remove types from the set when refined. Do not insert the type it was
137 /// refined to because that type hasn't been verified yet.
138 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
140 OldTy->removeAbstractTypeUser(this);
143 /// Stop listening for changes to a type which is no longer abstract.
144 void typeBecameConcrete(const DerivedType *AbsTy) {
145 AbsTy->removeAbstractTypeUser(this);
151 SmallSetVector<const Type *, 16> Types;
154 TypeSet(const TypeSet &);
155 TypeSet &operator=(const TypeSet &);
158 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
159 static char ID; // Pass ID, replacement for typeid
160 bool Broken; // Is this module found to be broken?
161 bool RealPass; // Are we not being run by a PassManager?
162 VerifierFailureAction action;
163 // What to do if verification fails.
164 Module *Mod; // Module we are verifying right now
165 LLVMContext *Context; // Context within which we are verifying
166 DominatorTree *DT; // Dominator Tree, caution can be null!
168 std::string Messages;
169 raw_string_ostream MessagesStr;
171 /// InstInThisBlock - when verifying a basic block, keep track of all of the
172 /// instructions we have seen so far. This allows us to do efficient
173 /// dominance checks for the case when an instruction has an operand that is
174 /// an instruction in the same block.
175 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
177 /// Types - keep track of the types that have been checked already.
180 /// MDNodes - keep track of the metadata nodes that have been checked
182 SmallPtrSet<MDNode *, 32> MDNodes;
186 Broken(false), RealPass(true), action(AbortProcessAction),
187 Mod(0), Context(0), DT(0), MessagesStr(Messages) {}
188 explicit Verifier(VerifierFailureAction ctn)
190 Broken(false), RealPass(true), action(ctn), Mod(0), Context(0), DT(0),
191 MessagesStr(Messages) {}
193 bool doInitialization(Module &M) {
195 Context = &M.getContext();
196 verifyTypeSymbolTable(M.getTypeSymbolTable());
198 // If this is a real pass, in a pass manager, we must abort before
199 // returning back to the pass manager, or else the pass manager may try to
200 // run other passes on the broken module.
202 return abortIfBroken();
206 bool runOnFunction(Function &F) {
207 // Get dominator information if we are being run by PassManager
208 if (RealPass) DT = &getAnalysis<DominatorTree>();
211 if (!Context) Context = &F.getContext();
214 InstsInThisBlock.clear();
216 // If this is a real pass, in a pass manager, we must abort before
217 // returning back to the pass manager, or else the pass manager may try to
218 // run other passes on the broken module.
220 return abortIfBroken();
225 bool doFinalization(Module &M) {
226 // Scan through, checking all of the external function's linkage now...
227 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
228 visitGlobalValue(*I);
230 // Check to make sure function prototypes are okay.
231 if (I->isDeclaration()) visitFunction(*I);
234 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
236 visitGlobalVariable(*I);
238 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
240 visitGlobalAlias(*I);
242 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
243 E = M.named_metadata_end(); I != E; ++I)
244 visitNamedMDNode(*I);
246 // If the module is broken, abort at this time.
247 return abortIfBroken();
250 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
251 AU.setPreservesAll();
252 AU.addRequiredID(PreVerifyID);
254 AU.addRequired<DominatorTree>();
257 /// abortIfBroken - If the module is broken and we are supposed to abort on
258 /// this condition, do so.
260 bool abortIfBroken() {
261 if (!Broken) return false;
262 MessagesStr << "Broken module found, ";
264 default: llvm_unreachable("Unknown action");
265 case AbortProcessAction:
266 MessagesStr << "compilation aborted!\n";
267 dbgs() << MessagesStr.str();
268 // Client should choose different reaction if abort is not desired
270 case PrintMessageAction:
271 MessagesStr << "verification continues.\n";
272 dbgs() << MessagesStr.str();
274 case ReturnStatusAction:
275 MessagesStr << "compilation terminated.\n";
281 // Verification methods...
282 void verifyTypeSymbolTable(TypeSymbolTable &ST);
283 void visitGlobalValue(GlobalValue &GV);
284 void visitGlobalVariable(GlobalVariable &GV);
285 void visitGlobalAlias(GlobalAlias &GA);
286 void visitNamedMDNode(NamedMDNode &NMD);
287 void visitMDNode(MDNode &MD, Function *F);
288 void visitFunction(Function &F);
289 void visitBasicBlock(BasicBlock &BB);
290 using InstVisitor<Verifier>::visit;
292 void visit(Instruction &I);
294 void visitTruncInst(TruncInst &I);
295 void visitZExtInst(ZExtInst &I);
296 void visitSExtInst(SExtInst &I);
297 void visitFPTruncInst(FPTruncInst &I);
298 void visitFPExtInst(FPExtInst &I);
299 void visitFPToUIInst(FPToUIInst &I);
300 void visitFPToSIInst(FPToSIInst &I);
301 void visitUIToFPInst(UIToFPInst &I);
302 void visitSIToFPInst(SIToFPInst &I);
303 void visitIntToPtrInst(IntToPtrInst &I);
304 void visitPtrToIntInst(PtrToIntInst &I);
305 void visitBitCastInst(BitCastInst &I);
306 void visitPHINode(PHINode &PN);
307 void visitBinaryOperator(BinaryOperator &B);
308 void visitICmpInst(ICmpInst &IC);
309 void visitFCmpInst(FCmpInst &FC);
310 void visitExtractElementInst(ExtractElementInst &EI);
311 void visitInsertElementInst(InsertElementInst &EI);
312 void visitShuffleVectorInst(ShuffleVectorInst &EI);
313 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
314 void visitCallInst(CallInst &CI);
315 void visitInvokeInst(InvokeInst &II);
316 void visitGetElementPtrInst(GetElementPtrInst &GEP);
317 void visitLoadInst(LoadInst &LI);
318 void visitStoreInst(StoreInst &SI);
319 void visitInstruction(Instruction &I);
320 void visitTerminatorInst(TerminatorInst &I);
321 void visitBranchInst(BranchInst &BI);
322 void visitReturnInst(ReturnInst &RI);
323 void visitSwitchInst(SwitchInst &SI);
324 void visitIndirectBrInst(IndirectBrInst &BI);
325 void visitSelectInst(SelectInst &SI);
326 void visitUserOp1(Instruction &I);
327 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
328 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
329 void visitAllocaInst(AllocaInst &AI);
330 void visitExtractValueInst(ExtractValueInst &EVI);
331 void visitInsertValueInst(InsertValueInst &IVI);
333 void VerifyCallSite(CallSite CS);
334 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
335 int VT, unsigned ArgNo, std::string &Suffix);
336 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
337 unsigned RetNum, unsigned ParamNum, ...);
338 void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
339 bool isReturnValue, const Value *V);
340 void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
342 void VerifyType(const Type *Ty);
344 void WriteValue(const Value *V) {
346 if (isa<Instruction>(V)) {
347 MessagesStr << *V << '\n';
349 WriteAsOperand(MessagesStr, V, true, Mod);
354 void WriteType(const Type *T) {
357 WriteTypeSymbolic(MessagesStr, T, Mod);
361 // CheckFailed - A check failed, so print out the condition and the message
362 // that failed. This provides a nice place to put a breakpoint if you want
363 // to see why something is not correct.
364 void CheckFailed(const Twine &Message,
365 const Value *V1 = 0, const Value *V2 = 0,
366 const Value *V3 = 0, const Value *V4 = 0) {
367 MessagesStr << Message.str() << "\n";
375 void CheckFailed(const Twine &Message, const Value *V1,
376 const Type *T2, const Value *V3 = 0) {
377 MessagesStr << Message.str() << "\n";
384 void CheckFailed(const Twine &Message, const Type *T1,
385 const Type *T2 = 0, const Type *T3 = 0) {
386 MessagesStr << Message.str() << "\n";
393 } // End anonymous namespace
395 char Verifier::ID = 0;
396 INITIALIZE_PASS(Verifier, "verify", "Module Verifier", false, false)
398 // Assert - We know that cond should be true, if not print an error message.
399 #define Assert(C, M) \
400 do { if (!(C)) { CheckFailed(M); return; } } while (0)
401 #define Assert1(C, M, V1) \
402 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
403 #define Assert2(C, M, V1, V2) \
404 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
405 #define Assert3(C, M, V1, V2, V3) \
406 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
407 #define Assert4(C, M, V1, V2, V3, V4) \
408 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
410 void Verifier::visit(Instruction &I) {
411 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
412 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
413 InstVisitor<Verifier>::visit(I);
417 void Verifier::visitGlobalValue(GlobalValue &GV) {
418 Assert1(!GV.isDeclaration() ||
419 GV.isMaterializable() ||
420 GV.hasExternalLinkage() ||
421 GV.hasDLLImportLinkage() ||
422 GV.hasExternalWeakLinkage() ||
423 (isa<GlobalAlias>(GV) &&
424 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
425 "Global is external, but doesn't have external or dllimport or weak linkage!",
428 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
429 "Global is marked as dllimport, but not external", &GV);
431 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
432 "Only global variables can have appending linkage!", &GV);
434 if (GV.hasAppendingLinkage()) {
435 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
436 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
437 "Only global arrays can have appending linkage!", GVar);
440 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
441 "linker_private_weak_def_auto can only have default visibility!",
445 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
446 if (GV.hasInitializer()) {
447 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
448 "Global variable initializer type does not match global "
449 "variable type!", &GV);
451 // If the global has common linkage, it must have a zero initializer and
452 // cannot be constant.
453 if (GV.hasCommonLinkage()) {
454 Assert1(GV.getInitializer()->isNullValue(),
455 "'common' global must have a zero initializer!", &GV);
456 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
460 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
461 GV.hasExternalWeakLinkage(),
462 "invalid linkage type for global declaration", &GV);
465 visitGlobalValue(GV);
468 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
469 Assert1(!GA.getName().empty(),
470 "Alias name cannot be empty!", &GA);
471 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
473 "Alias should have external or external weak linkage!", &GA);
474 Assert1(GA.getAliasee(),
475 "Aliasee cannot be NULL!", &GA);
476 Assert1(GA.getType() == GA.getAliasee()->getType(),
477 "Alias and aliasee types should match!", &GA);
479 if (!isa<GlobalValue>(GA.getAliasee())) {
480 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
482 (CE->getOpcode() == Instruction::BitCast ||
483 CE->getOpcode() == Instruction::GetElementPtr) &&
484 isa<GlobalValue>(CE->getOperand(0)),
485 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
489 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
491 "Aliasing chain should end with function or global variable", &GA);
493 visitGlobalValue(GA);
496 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
497 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
498 MDNode *MD = NMD.getOperand(i);
502 Assert1(!MD->isFunctionLocal(),
503 "Named metadata operand cannot be function local!", MD);
508 void Verifier::visitMDNode(MDNode &MD, Function *F) {
509 // Only visit each node once. Metadata can be mutually recursive, so this
510 // avoids infinite recursion here, as well as being an optimization.
511 if (!MDNodes.insert(&MD))
514 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
515 Value *Op = MD.getOperand(i);
518 if (isa<Constant>(Op) || isa<MDString>(Op))
520 if (MDNode *N = dyn_cast<MDNode>(Op)) {
521 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
522 "Global metadata operand cannot be function local!", &MD, N);
526 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
528 // If this was an instruction, bb, or argument, verify that it is in the
529 // function that we expect.
530 Function *ActualF = 0;
531 if (Instruction *I = dyn_cast<Instruction>(Op))
532 ActualF = I->getParent()->getParent();
533 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
534 ActualF = BB->getParent();
535 else if (Argument *A = dyn_cast<Argument>(Op))
536 ActualF = A->getParent();
537 assert(ActualF && "Unimplemented function local metadata case!");
539 Assert2(ActualF == F, "function-local metadata used in wrong function",
544 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
545 for (TypeSymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
546 VerifyType(I->second);
549 // VerifyParameterAttrs - Check the given attributes for an argument or return
550 // value of the specified type. The value V is printed in error messages.
551 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
552 bool isReturnValue, const Value *V) {
553 if (Attrs == Attribute::None)
556 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
557 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
558 " only applies to the function!", V);
561 Attributes RetI = Attrs & Attribute::ParameterOnly;
562 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
563 " does not apply to return values!", V);
567 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
568 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
569 Assert1(!(MutI & (MutI - 1)), "Attributes " +
570 Attribute::getAsString(MutI) + " are incompatible!", V);
573 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
574 Assert1(!TypeI, "Wrong type for attribute " +
575 Attribute::getAsString(TypeI), V);
577 Attributes ByValI = Attrs & Attribute::ByVal;
578 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
579 Assert1(!ByValI || PTy->getElementType()->isSized(),
580 "Attribute " + Attribute::getAsString(ByValI) +
581 " does not support unsized types!", V);
584 "Attribute " + Attribute::getAsString(ByValI) +
585 " only applies to parameters with pointer type!", V);
589 // VerifyFunctionAttrs - Check parameter attributes against a function type.
590 // The value V is printed in error messages.
591 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
592 const AttrListPtr &Attrs,
597 bool SawNest = false;
599 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
600 const AttributeWithIndex &Attr = Attrs.getSlot(i);
604 Ty = FT->getReturnType();
605 else if (Attr.Index-1 < FT->getNumParams())
606 Ty = FT->getParamType(Attr.Index-1);
608 break; // VarArgs attributes, verified elsewhere.
610 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
612 if (Attr.Attrs & Attribute::Nest) {
613 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
617 if (Attr.Attrs & Attribute::StructRet)
618 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
621 Attributes FAttrs = Attrs.getFnAttributes();
622 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
623 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
624 " does not apply to the function!", V);
627 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
628 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
629 Assert1(!(MutI & (MutI - 1)), "Attributes " +
630 Attribute::getAsString(MutI) + " are incompatible!", V);
634 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
638 unsigned LastSlot = Attrs.getNumSlots() - 1;
639 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
640 if (LastIndex <= Params
641 || (LastIndex == (unsigned)~0
642 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
648 // visitFunction - Verify that a function is ok.
650 void Verifier::visitFunction(Function &F) {
651 // Check function arguments.
652 const FunctionType *FT = F.getFunctionType();
653 unsigned NumArgs = F.arg_size();
655 Assert1(Context == &F.getContext(),
656 "Function context does not match Module context!", &F);
658 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
659 Assert2(FT->getNumParams() == NumArgs,
660 "# formal arguments must match # of arguments for function type!",
662 Assert1(F.getReturnType()->isFirstClassType() ||
663 F.getReturnType()->isVoidTy() ||
664 F.getReturnType()->isStructTy(),
665 "Functions cannot return aggregate values!", &F);
667 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
668 "Invalid struct return type!", &F);
670 const AttrListPtr &Attrs = F.getAttributes();
672 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
673 "Attributes after last parameter!", &F);
675 // Check function attributes.
676 VerifyFunctionAttrs(FT, Attrs, &F);
678 // Check that this function meets the restrictions on this calling convention.
679 switch (F.getCallingConv()) {
684 case CallingConv::Fast:
685 case CallingConv::Cold:
686 case CallingConv::X86_FastCall:
687 case CallingConv::X86_ThisCall:
688 case CallingConv::PTX_Kernel:
689 case CallingConv::PTX_Device:
690 Assert1(!F.isVarArg(),
691 "Varargs functions must have C calling conventions!", &F);
695 bool isLLVMdotName = F.getName().size() >= 5 &&
696 F.getName().substr(0, 5) == "llvm.";
698 // Check that the argument values match the function type for this function...
700 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
702 Assert2(I->getType() == FT->getParamType(i),
703 "Argument value does not match function argument type!",
704 I, FT->getParamType(i));
705 Assert1(I->getType()->isFirstClassType(),
706 "Function arguments must have first-class types!", I);
708 Assert2(!I->getType()->isMetadataTy(),
709 "Function takes metadata but isn't an intrinsic", I, &F);
712 if (F.isMaterializable()) {
713 // Function has a body somewhere we can't see.
714 } else if (F.isDeclaration()) {
715 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
716 F.hasExternalWeakLinkage(),
717 "invalid linkage type for function declaration", &F);
719 // Verify that this function (which has a body) is not named "llvm.*". It
720 // is not legal to define intrinsics.
721 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
723 // Check the entry node
724 BasicBlock *Entry = &F.getEntryBlock();
725 Assert1(pred_begin(Entry) == pred_end(Entry),
726 "Entry block to function must not have predecessors!", Entry);
728 // The address of the entry block cannot be taken, unless it is dead.
729 if (Entry->hasAddressTaken()) {
730 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
731 "blockaddress may not be used with the entry block!", Entry);
735 // If this function is actually an intrinsic, verify that it is only used in
736 // direct call/invokes, never having its "address taken".
737 if (F.getIntrinsicID()) {
739 if (F.hasAddressTaken(&U))
740 Assert1(0, "Invalid user of intrinsic instruction!", U);
744 // verifyBasicBlock - Verify that a basic block is well formed...
746 void Verifier::visitBasicBlock(BasicBlock &BB) {
747 InstsInThisBlock.clear();
749 // Ensure that basic blocks have terminators!
750 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
752 // Check constraints that this basic block imposes on all of the PHI nodes in
754 if (isa<PHINode>(BB.front())) {
755 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
756 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
757 std::sort(Preds.begin(), Preds.end());
759 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
760 // Ensure that PHI nodes have at least one entry!
761 Assert1(PN->getNumIncomingValues() != 0,
762 "PHI nodes must have at least one entry. If the block is dead, "
763 "the PHI should be removed!", PN);
764 Assert1(PN->getNumIncomingValues() == Preds.size(),
765 "PHINode should have one entry for each predecessor of its "
766 "parent basic block!", PN);
768 // Get and sort all incoming values in the PHI node...
770 Values.reserve(PN->getNumIncomingValues());
771 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
772 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
773 PN->getIncomingValue(i)));
774 std::sort(Values.begin(), Values.end());
776 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
777 // Check to make sure that if there is more than one entry for a
778 // particular basic block in this PHI node, that the incoming values are
781 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
782 Values[i].second == Values[i-1].second,
783 "PHI node has multiple entries for the same basic block with "
784 "different incoming values!", PN, Values[i].first,
785 Values[i].second, Values[i-1].second);
787 // Check to make sure that the predecessors and PHI node entries are
789 Assert3(Values[i].first == Preds[i],
790 "PHI node entries do not match predecessors!", PN,
791 Values[i].first, Preds[i]);
797 void Verifier::visitTerminatorInst(TerminatorInst &I) {
798 // Ensure that terminators only exist at the end of the basic block.
799 Assert1(&I == I.getParent()->getTerminator(),
800 "Terminator found in the middle of a basic block!", I.getParent());
804 void Verifier::visitBranchInst(BranchInst &BI) {
805 if (BI.isConditional()) {
806 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
807 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
809 visitTerminatorInst(BI);
812 void Verifier::visitReturnInst(ReturnInst &RI) {
813 Function *F = RI.getParent()->getParent();
814 unsigned N = RI.getNumOperands();
815 if (F->getReturnType()->isVoidTy())
817 "Found return instr that returns non-void in Function of void "
818 "return type!", &RI, F->getReturnType());
819 else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
820 // Exactly one return value and it matches the return type. Good.
821 } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
822 // The return type is a struct; check for multiple return values.
823 Assert2(STy->getNumElements() == N,
824 "Incorrect number of return values in ret instruction!",
825 &RI, F->getReturnType());
826 for (unsigned i = 0; i != N; ++i)
827 Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
828 "Function return type does not match operand "
829 "type of return inst!", &RI, F->getReturnType());
830 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
831 // The return type is an array; check for multiple return values.
832 Assert2(ATy->getNumElements() == N,
833 "Incorrect number of return values in ret instruction!",
834 &RI, F->getReturnType());
835 for (unsigned i = 0; i != N; ++i)
836 Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
837 "Function return type does not match operand "
838 "type of return inst!", &RI, F->getReturnType());
840 CheckFailed("Function return type does not match operand "
841 "type of return inst!", &RI, F->getReturnType());
844 // Check to make sure that the return value has necessary properties for
846 visitTerminatorInst(RI);
849 void Verifier::visitSwitchInst(SwitchInst &SI) {
850 // Check to make sure that all of the constants in the switch instruction
851 // have the same type as the switched-on value.
852 const Type *SwitchTy = SI.getCondition()->getType();
853 SmallPtrSet<ConstantInt*, 32> Constants;
854 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
855 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
856 "Switch constants must all be same type as switch value!", &SI);
857 Assert2(Constants.insert(SI.getCaseValue(i)),
858 "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
861 visitTerminatorInst(SI);
864 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
865 Assert1(BI.getAddress()->getType()->isPointerTy(),
866 "Indirectbr operand must have pointer type!", &BI);
867 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
868 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
869 "Indirectbr destinations must all have pointer type!", &BI);
871 visitTerminatorInst(BI);
874 void Verifier::visitSelectInst(SelectInst &SI) {
875 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
877 "Invalid operands for select instruction!", &SI);
879 Assert1(SI.getTrueValue()->getType() == SI.getType(),
880 "Select values must have same type as select instruction!", &SI);
881 visitInstruction(SI);
884 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
885 /// a pass, if any exist, it's an error.
887 void Verifier::visitUserOp1(Instruction &I) {
888 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
891 void Verifier::visitTruncInst(TruncInst &I) {
892 // Get the source and destination types
893 const Type *SrcTy = I.getOperand(0)->getType();
894 const Type *DestTy = I.getType();
896 // Get the size of the types in bits, we'll need this later
897 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
898 unsigned DestBitSize = DestTy->getScalarSizeInBits();
900 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
901 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
902 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
903 "trunc source and destination must both be a vector or neither", &I);
904 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
909 void Verifier::visitZExtInst(ZExtInst &I) {
910 // Get the source and destination types
911 const Type *SrcTy = I.getOperand(0)->getType();
912 const Type *DestTy = I.getType();
914 // Get the size of the types in bits, we'll need this later
915 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
916 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
917 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
918 "zext source and destination must both be a vector or neither", &I);
919 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
920 unsigned DestBitSize = DestTy->getScalarSizeInBits();
922 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
927 void Verifier::visitSExtInst(SExtInst &I) {
928 // Get the source and destination types
929 const Type *SrcTy = I.getOperand(0)->getType();
930 const Type *DestTy = I.getType();
932 // Get the size of the types in bits, we'll need this later
933 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
934 unsigned DestBitSize = DestTy->getScalarSizeInBits();
936 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
937 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
938 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
939 "sext source and destination must both be a vector or neither", &I);
940 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
945 void Verifier::visitFPTruncInst(FPTruncInst &I) {
946 // Get the source and destination types
947 const Type *SrcTy = I.getOperand(0)->getType();
948 const Type *DestTy = I.getType();
949 // Get the size of the types in bits, we'll need this later
950 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
951 unsigned DestBitSize = DestTy->getScalarSizeInBits();
953 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
954 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
955 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
956 "fptrunc source and destination must both be a vector or neither",&I);
957 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
962 void Verifier::visitFPExtInst(FPExtInst &I) {
963 // Get the source and destination types
964 const Type *SrcTy = I.getOperand(0)->getType();
965 const Type *DestTy = I.getType();
967 // Get the size of the types in bits, we'll need this later
968 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
969 unsigned DestBitSize = DestTy->getScalarSizeInBits();
971 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
972 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
973 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
974 "fpext source and destination must both be a vector or neither", &I);
975 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
980 void Verifier::visitUIToFPInst(UIToFPInst &I) {
981 // Get the source and destination types
982 const Type *SrcTy = I.getOperand(0)->getType();
983 const Type *DestTy = I.getType();
985 bool SrcVec = SrcTy->isVectorTy();
986 bool DstVec = DestTy->isVectorTy();
988 Assert1(SrcVec == DstVec,
989 "UIToFP source and dest must both be vector or scalar", &I);
990 Assert1(SrcTy->isIntOrIntVectorTy(),
991 "UIToFP source must be integer or integer vector", &I);
992 Assert1(DestTy->isFPOrFPVectorTy(),
993 "UIToFP result must be FP or FP vector", &I);
995 if (SrcVec && DstVec)
996 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
997 cast<VectorType>(DestTy)->getNumElements(),
998 "UIToFP source and dest vector length mismatch", &I);
1000 visitInstruction(I);
1003 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1004 // Get the source and destination types
1005 const Type *SrcTy = I.getOperand(0)->getType();
1006 const Type *DestTy = I.getType();
1008 bool SrcVec = SrcTy->isVectorTy();
1009 bool DstVec = DestTy->isVectorTy();
1011 Assert1(SrcVec == DstVec,
1012 "SIToFP source and dest must both be vector or scalar", &I);
1013 Assert1(SrcTy->isIntOrIntVectorTy(),
1014 "SIToFP source must be integer or integer vector", &I);
1015 Assert1(DestTy->isFPOrFPVectorTy(),
1016 "SIToFP result must be FP or FP vector", &I);
1018 if (SrcVec && DstVec)
1019 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1020 cast<VectorType>(DestTy)->getNumElements(),
1021 "SIToFP source and dest vector length mismatch", &I);
1023 visitInstruction(I);
1026 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1027 // Get the source and destination types
1028 const Type *SrcTy = I.getOperand(0)->getType();
1029 const Type *DestTy = I.getType();
1031 bool SrcVec = SrcTy->isVectorTy();
1032 bool DstVec = DestTy->isVectorTy();
1034 Assert1(SrcVec == DstVec,
1035 "FPToUI source and dest must both be vector or scalar", &I);
1036 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1038 Assert1(DestTy->isIntOrIntVectorTy(),
1039 "FPToUI result must be integer or integer vector", &I);
1041 if (SrcVec && DstVec)
1042 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1043 cast<VectorType>(DestTy)->getNumElements(),
1044 "FPToUI source and dest vector length mismatch", &I);
1046 visitInstruction(I);
1049 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1050 // Get the source and destination types
1051 const Type *SrcTy = I.getOperand(0)->getType();
1052 const Type *DestTy = I.getType();
1054 bool SrcVec = SrcTy->isVectorTy();
1055 bool DstVec = DestTy->isVectorTy();
1057 Assert1(SrcVec == DstVec,
1058 "FPToSI source and dest must both be vector or scalar", &I);
1059 Assert1(SrcTy->isFPOrFPVectorTy(),
1060 "FPToSI source must be FP or FP vector", &I);
1061 Assert1(DestTy->isIntOrIntVectorTy(),
1062 "FPToSI result must be integer or integer vector", &I);
1064 if (SrcVec && DstVec)
1065 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1066 cast<VectorType>(DestTy)->getNumElements(),
1067 "FPToSI source and dest vector length mismatch", &I);
1069 visitInstruction(I);
1072 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1073 // Get the source and destination types
1074 const Type *SrcTy = I.getOperand(0)->getType();
1075 const Type *DestTy = I.getType();
1077 Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1078 Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1080 visitInstruction(I);
1083 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1084 // Get the source and destination types
1085 const Type *SrcTy = I.getOperand(0)->getType();
1086 const Type *DestTy = I.getType();
1088 Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1089 Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1091 visitInstruction(I);
1094 void Verifier::visitBitCastInst(BitCastInst &I) {
1095 // Get the source and destination types
1096 const Type *SrcTy = I.getOperand(0)->getType();
1097 const Type *DestTy = I.getType();
1099 // Get the size of the types in bits, we'll need this later
1100 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1101 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1103 // BitCast implies a no-op cast of type only. No bits change.
1104 // However, you can't cast pointers to anything but pointers.
1105 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1106 "Bitcast requires both operands to be pointer or neither", &I);
1107 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1109 // Disallow aggregates.
1110 Assert1(!SrcTy->isAggregateType(),
1111 "Bitcast operand must not be aggregate", &I);
1112 Assert1(!DestTy->isAggregateType(),
1113 "Bitcast type must not be aggregate", &I);
1115 visitInstruction(I);
1118 /// visitPHINode - Ensure that a PHI node is well formed.
1120 void Verifier::visitPHINode(PHINode &PN) {
1121 // Ensure that the PHI nodes are all grouped together at the top of the block.
1122 // This can be tested by checking whether the instruction before this is
1123 // either nonexistent (because this is begin()) or is a PHI node. If not,
1124 // then there is some other instruction before a PHI.
1125 Assert2(&PN == &PN.getParent()->front() ||
1126 isa<PHINode>(--BasicBlock::iterator(&PN)),
1127 "PHI nodes not grouped at top of basic block!",
1128 &PN, PN.getParent());
1130 // Check that all of the values of the PHI node have the same type as the
1131 // result, and that the incoming blocks are really basic blocks.
1132 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1133 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1134 "PHI node operands are not the same type as the result!", &PN);
1135 Assert1(isa<BasicBlock>(PN.getOperand(
1136 PHINode::getOperandNumForIncomingBlock(i))),
1137 "PHI node incoming block is not a BasicBlock!", &PN);
1140 // All other PHI node constraints are checked in the visitBasicBlock method.
1142 visitInstruction(PN);
1145 void Verifier::VerifyCallSite(CallSite CS) {
1146 Instruction *I = CS.getInstruction();
1148 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1149 "Called function must be a pointer!", I);
1150 const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1152 Assert1(FPTy->getElementType()->isFunctionTy(),
1153 "Called function is not pointer to function type!", I);
1154 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1156 // Verify that the correct number of arguments are being passed
1157 if (FTy->isVarArg())
1158 Assert1(CS.arg_size() >= FTy->getNumParams(),
1159 "Called function requires more parameters than were provided!",I);
1161 Assert1(CS.arg_size() == FTy->getNumParams(),
1162 "Incorrect number of arguments passed to called function!", I);
1164 // Verify that all arguments to the call match the function type.
1165 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1166 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1167 "Call parameter type does not match function signature!",
1168 CS.getArgument(i), FTy->getParamType(i), I);
1170 const AttrListPtr &Attrs = CS.getAttributes();
1172 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1173 "Attributes after last parameter!", I);
1175 // Verify call attributes.
1176 VerifyFunctionAttrs(FTy, Attrs, I);
1178 if (FTy->isVarArg())
1179 // Check attributes on the varargs part.
1180 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1181 Attributes Attr = Attrs.getParamAttributes(Idx);
1183 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1185 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1186 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1187 " cannot be used for vararg call arguments!", I);
1190 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1191 if (!CS.getCalledFunction() ||
1192 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1193 for (FunctionType::param_iterator PI = FTy->param_begin(),
1194 PE = FTy->param_end(); PI != PE; ++PI)
1195 Assert1(!PI->get()->isMetadataTy(),
1196 "Function has metadata parameter but isn't an intrinsic", I);
1199 visitInstruction(*I);
1202 void Verifier::visitCallInst(CallInst &CI) {
1203 VerifyCallSite(&CI);
1205 if (Function *F = CI.getCalledFunction())
1206 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1207 visitIntrinsicFunctionCall(ID, CI);
1210 void Verifier::visitInvokeInst(InvokeInst &II) {
1211 VerifyCallSite(&II);
1212 visitTerminatorInst(II);
1215 /// visitBinaryOperator - Check that both arguments to the binary operator are
1216 /// of the same type!
1218 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1219 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1220 "Both operands to a binary operator are not of the same type!", &B);
1222 switch (B.getOpcode()) {
1223 // Check that integer arithmetic operators are only used with
1224 // integral operands.
1225 case Instruction::Add:
1226 case Instruction::Sub:
1227 case Instruction::Mul:
1228 case Instruction::SDiv:
1229 case Instruction::UDiv:
1230 case Instruction::SRem:
1231 case Instruction::URem:
1232 Assert1(B.getType()->isIntOrIntVectorTy(),
1233 "Integer arithmetic operators only work with integral types!", &B);
1234 Assert1(B.getType() == B.getOperand(0)->getType(),
1235 "Integer arithmetic operators must have same type "
1236 "for operands and result!", &B);
1238 // Check that floating-point arithmetic operators are only used with
1239 // floating-point operands.
1240 case Instruction::FAdd:
1241 case Instruction::FSub:
1242 case Instruction::FMul:
1243 case Instruction::FDiv:
1244 case Instruction::FRem:
1245 Assert1(B.getType()->isFPOrFPVectorTy(),
1246 "Floating-point arithmetic operators only work with "
1247 "floating-point types!", &B);
1248 Assert1(B.getType() == B.getOperand(0)->getType(),
1249 "Floating-point arithmetic operators must have same type "
1250 "for operands and result!", &B);
1252 // Check that logical operators are only used with integral operands.
1253 case Instruction::And:
1254 case Instruction::Or:
1255 case Instruction::Xor:
1256 Assert1(B.getType()->isIntOrIntVectorTy(),
1257 "Logical operators only work with integral types!", &B);
1258 Assert1(B.getType() == B.getOperand(0)->getType(),
1259 "Logical operators must have same type for operands and result!",
1262 case Instruction::Shl:
1263 case Instruction::LShr:
1264 case Instruction::AShr:
1265 Assert1(B.getType()->isIntOrIntVectorTy(),
1266 "Shifts only work with integral types!", &B);
1267 Assert1(B.getType() == B.getOperand(0)->getType(),
1268 "Shift return type must be same as operands!", &B);
1271 llvm_unreachable("Unknown BinaryOperator opcode!");
1274 visitInstruction(B);
1277 void Verifier::visitICmpInst(ICmpInst &IC) {
1278 // Check that the operands are the same type
1279 const Type *Op0Ty = IC.getOperand(0)->getType();
1280 const Type *Op1Ty = IC.getOperand(1)->getType();
1281 Assert1(Op0Ty == Op1Ty,
1282 "Both operands to ICmp instruction are not of the same type!", &IC);
1283 // Check that the operands are the right type
1284 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1285 "Invalid operand types for ICmp instruction", &IC);
1286 // Check that the predicate is valid.
1287 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1288 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1289 "Invalid predicate in ICmp instruction!", &IC);
1291 visitInstruction(IC);
1294 void Verifier::visitFCmpInst(FCmpInst &FC) {
1295 // Check that the operands are the same type
1296 const Type *Op0Ty = FC.getOperand(0)->getType();
1297 const Type *Op1Ty = FC.getOperand(1)->getType();
1298 Assert1(Op0Ty == Op1Ty,
1299 "Both operands to FCmp instruction are not of the same type!", &FC);
1300 // Check that the operands are the right type
1301 Assert1(Op0Ty->isFPOrFPVectorTy(),
1302 "Invalid operand types for FCmp instruction", &FC);
1303 // Check that the predicate is valid.
1304 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1305 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1306 "Invalid predicate in FCmp instruction!", &FC);
1308 visitInstruction(FC);
1311 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1312 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1314 "Invalid extractelement operands!", &EI);
1315 visitInstruction(EI);
1318 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1319 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1322 "Invalid insertelement operands!", &IE);
1323 visitInstruction(IE);
1326 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1327 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1329 "Invalid shufflevector operands!", &SV);
1330 visitInstruction(SV);
1333 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1334 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1336 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1337 Idxs.begin(), Idxs.end());
1338 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1339 Assert2(GEP.getType()->isPointerTy() &&
1340 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1341 "GEP is not of right type for indices!", &GEP, ElTy);
1342 visitInstruction(GEP);
1345 void Verifier::visitLoadInst(LoadInst &LI) {
1346 const PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1347 Assert1(PTy, "Load operand must be a pointer.", &LI);
1348 const Type *ElTy = PTy->getElementType();
1349 Assert2(ElTy == LI.getType(),
1350 "Load result type does not match pointer operand type!", &LI, ElTy);
1351 visitInstruction(LI);
1354 void Verifier::visitStoreInst(StoreInst &SI) {
1355 const PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1356 Assert1(PTy, "Store operand must be a pointer.", &SI);
1357 const Type *ElTy = PTy->getElementType();
1358 Assert2(ElTy == SI.getOperand(0)->getType(),
1359 "Stored value type does not match pointer operand type!",
1361 visitInstruction(SI);
1364 void Verifier::visitAllocaInst(AllocaInst &AI) {
1365 const PointerType *PTy = AI.getType();
1366 Assert1(PTy->getAddressSpace() == 0,
1367 "Allocation instruction pointer not in the generic address space!",
1369 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1371 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1372 "Alloca array size must have integer type", &AI);
1373 visitInstruction(AI);
1376 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1377 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1378 EVI.idx_begin(), EVI.idx_end()) ==
1380 "Invalid ExtractValueInst operands!", &EVI);
1382 visitInstruction(EVI);
1385 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1386 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1387 IVI.idx_begin(), IVI.idx_end()) ==
1388 IVI.getOperand(1)->getType(),
1389 "Invalid InsertValueInst operands!", &IVI);
1391 visitInstruction(IVI);
1394 /// verifyInstruction - Verify that an instruction is well formed.
1396 void Verifier::visitInstruction(Instruction &I) {
1397 BasicBlock *BB = I.getParent();
1398 Assert1(BB, "Instruction not embedded in basic block!", &I);
1400 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1401 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1403 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1404 "Only PHI nodes may reference their own value!", &I);
1407 // Check that void typed values don't have names
1408 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1409 "Instruction has a name, but provides a void value!", &I);
1411 // Check that the return value of the instruction is either void or a legal
1413 Assert1(I.getType()->isVoidTy() ||
1414 I.getType()->isFirstClassType(),
1415 "Instruction returns a non-scalar type!", &I);
1417 // Check that the instruction doesn't produce metadata. Calls are already
1418 // checked against the callee type.
1419 Assert1(!I.getType()->isMetadataTy() ||
1420 isa<CallInst>(I) || isa<InvokeInst>(I),
1421 "Invalid use of metadata!", &I);
1423 // Check that all uses of the instruction, if they are instructions
1424 // themselves, actually have parent basic blocks. If the use is not an
1425 // instruction, it is an error!
1426 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1428 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1429 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1430 " embedded in a basic block!", &I, Used);
1432 CheckFailed("Use of instruction is not an instruction!", *UI);
1437 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1438 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1440 // Check to make sure that only first-class-values are operands to
1442 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1443 Assert1(0, "Instruction operands must be first-class values!", &I);
1446 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1447 // Check to make sure that the "address of" an intrinsic function is never
1449 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1450 "Cannot take the address of an intrinsic!", &I);
1451 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1453 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1454 Assert1(OpBB->getParent() == BB->getParent(),
1455 "Referring to a basic block in another function!", &I);
1456 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1457 Assert1(OpArg->getParent() == BB->getParent(),
1458 "Referring to an argument in another function!", &I);
1459 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1460 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1462 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1463 BasicBlock *OpBlock = Op->getParent();
1465 // Check that a definition dominates all of its uses.
1466 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1467 // Invoke results are only usable in the normal destination, not in the
1468 // exceptional destination.
1469 BasicBlock *NormalDest = II->getNormalDest();
1471 Assert2(NormalDest != II->getUnwindDest(),
1472 "No uses of invoke possible due to dominance structure!",
1475 // PHI nodes differ from other nodes because they actually "use" the
1476 // value in the predecessor basic blocks they correspond to.
1477 BasicBlock *UseBlock = BB;
1478 if (isa<PHINode>(I))
1479 UseBlock = dyn_cast<BasicBlock>(I.getOperand(i+1));
1480 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1483 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1484 // Special case of a phi node in the normal destination or the unwind
1486 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1487 "Invoke result not available in the unwind destination!",
1490 Assert2(DT->dominates(NormalDest, UseBlock) ||
1491 !DT->isReachableFromEntry(UseBlock),
1492 "Invoke result does not dominate all uses!", Op, &I);
1494 // If the normal successor of an invoke instruction has multiple
1495 // predecessors, then the normal edge from the invoke is critical,
1496 // so the invoke value can only be live if the destination block
1497 // dominates all of it's predecessors (other than the invoke).
1498 if (!NormalDest->getSinglePredecessor() &&
1499 DT->isReachableFromEntry(UseBlock))
1500 // If it is used by something non-phi, then the other case is that
1501 // 'NormalDest' dominates all of its predecessors other than the
1502 // invoke. In this case, the invoke value can still be used.
1503 for (pred_iterator PI = pred_begin(NormalDest),
1504 E = pred_end(NormalDest); PI != E; ++PI)
1505 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1506 DT->isReachableFromEntry(*PI)) {
1507 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1511 } else if (isa<PHINode>(I)) {
1512 // PHI nodes are more difficult than other nodes because they actually
1513 // "use" the value in the predecessor basic blocks they correspond to.
1514 BasicBlock *PredBB = dyn_cast<BasicBlock>(I.getOperand(i+1));
1515 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1516 !DT->isReachableFromEntry(PredBB)),
1517 "Instruction does not dominate all uses!", Op, &I);
1519 if (OpBlock == BB) {
1520 // If they are in the same basic block, make sure that the definition
1521 // comes before the use.
1522 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1523 "Instruction does not dominate all uses!", Op, &I);
1526 // Definition must dominate use unless use is unreachable!
1527 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1528 !DT->isReachableFromEntry(BB),
1529 "Instruction does not dominate all uses!", Op, &I);
1531 } else if (isa<InlineAsm>(I.getOperand(i))) {
1532 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1533 (i + 3 == e && isa<InvokeInst>(I)),
1534 "Cannot take the address of an inline asm!", &I);
1537 InstsInThisBlock.insert(&I);
1539 VerifyType(I.getType());
1542 /// VerifyType - Verify that a type is well formed.
1544 void Verifier::VerifyType(const Type *Ty) {
1545 if (!Types.insert(Ty)) return;
1547 Assert1(Context == &Ty->getContext(),
1548 "Type context does not match Module context!", Ty);
1550 switch (Ty->getTypeID()) {
1551 case Type::FunctionTyID: {
1552 const FunctionType *FTy = cast<FunctionType>(Ty);
1554 const Type *RetTy = FTy->getReturnType();
1555 Assert2(FunctionType::isValidReturnType(RetTy),
1556 "Function type with invalid return type", RetTy, FTy);
1559 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1560 const Type *ElTy = FTy->getParamType(i);
1561 Assert2(FunctionType::isValidArgumentType(ElTy),
1562 "Function type with invalid parameter type", ElTy, FTy);
1567 case Type::StructTyID: {
1568 const StructType *STy = cast<StructType>(Ty);
1569 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1570 const Type *ElTy = STy->getElementType(i);
1571 Assert2(StructType::isValidElementType(ElTy),
1572 "Structure type with invalid element type", ElTy, STy);
1577 case Type::ArrayTyID: {
1578 const ArrayType *ATy = cast<ArrayType>(Ty);
1579 Assert1(ArrayType::isValidElementType(ATy->getElementType()),
1580 "Array type with invalid element type", ATy);
1581 VerifyType(ATy->getElementType());
1584 case Type::PointerTyID: {
1585 const PointerType *PTy = cast<PointerType>(Ty);
1586 Assert1(PointerType::isValidElementType(PTy->getElementType()),
1587 "Pointer type with invalid element type", PTy);
1588 VerifyType(PTy->getElementType());
1591 case Type::VectorTyID: {
1592 const VectorType *VTy = cast<VectorType>(Ty);
1593 Assert1(VectorType::isValidElementType(VTy->getElementType()),
1594 "Vector type with invalid element type", VTy);
1595 VerifyType(VTy->getElementType());
1603 // Flags used by TableGen to mark intrinsic parameters with the
1604 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1605 static const unsigned ExtendedElementVectorType = 0x40000000;
1606 static const unsigned TruncatedElementVectorType = 0x20000000;
1608 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1610 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1611 Function *IF = CI.getCalledFunction();
1612 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1615 #define GET_INTRINSIC_VERIFIER
1616 #include "llvm/Intrinsics.gen"
1617 #undef GET_INTRINSIC_VERIFIER
1619 // If the intrinsic takes MDNode arguments, verify that they are either global
1620 // or are local to *this* function.
1621 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1622 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1623 visitMDNode(*MD, CI.getParent()->getParent());
1628 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1629 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1630 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1631 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1632 Assert1(MD->getNumOperands() == 1,
1633 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1635 case Intrinsic::memcpy:
1636 case Intrinsic::memmove:
1637 case Intrinsic::memset:
1638 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1639 "alignment argument of memory intrinsics must be a constant int",
1642 case Intrinsic::gcroot:
1643 case Intrinsic::gcwrite:
1644 case Intrinsic::gcread:
1645 if (ID == Intrinsic::gcroot) {
1647 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1648 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1649 Assert1(isa<Constant>(CI.getArgOperand(1)),
1650 "llvm.gcroot parameter #2 must be a constant.", &CI);
1651 if (!AI->getType()->getElementType()->isPointerTy()) {
1652 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1653 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1654 "or argument #2 must be a non-null constant.", &CI);
1658 Assert1(CI.getParent()->getParent()->hasGC(),
1659 "Enclosing function does not use GC.", &CI);
1661 case Intrinsic::init_trampoline:
1662 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1663 "llvm.init_trampoline parameter #2 must resolve to a function.",
1666 case Intrinsic::prefetch:
1667 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1668 isa<ConstantInt>(CI.getArgOperand(2)) &&
1669 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1670 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1671 "invalid arguments to llvm.prefetch",
1674 case Intrinsic::stackprotector:
1675 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1676 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1679 case Intrinsic::lifetime_start:
1680 case Intrinsic::lifetime_end:
1681 case Intrinsic::invariant_start:
1682 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1683 "size argument of memory use markers must be a constant integer",
1686 case Intrinsic::invariant_end:
1687 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1688 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1693 /// Produce a string to identify an intrinsic parameter or return value.
1694 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1695 /// parameters beginning with NumRets.
1697 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1698 if (ArgNo >= NumRets)
1699 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1701 return "Intrinsic result type";
1702 return "Intrinsic result type #" + utostr(ArgNo);
1705 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1706 int VT, unsigned ArgNo, std::string &Suffix) {
1707 const FunctionType *FTy = F->getFunctionType();
1709 unsigned NumElts = 0;
1710 const Type *EltTy = Ty;
1711 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1713 EltTy = VTy->getElementType();
1714 NumElts = VTy->getNumElements();
1717 const Type *RetTy = FTy->getReturnType();
1718 const StructType *ST = dyn_cast<StructType>(RetTy);
1719 unsigned NumRetVals;
1720 if (RetTy->isVoidTy())
1723 NumRetVals = ST->getNumElements();
1730 // Check flags that indicate a type that is an integral vector type with
1731 // elements that are larger or smaller than the elements of the matched
1733 if ((Match & (ExtendedElementVectorType |
1734 TruncatedElementVectorType)) != 0) {
1735 const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1736 if (!VTy || !IEltTy) {
1737 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1738 "an integral vector type.", F);
1741 // Adjust the current Ty (in the opposite direction) rather than
1742 // the type being matched against.
1743 if ((Match & ExtendedElementVectorType) != 0) {
1744 if ((IEltTy->getBitWidth() & 1) != 0) {
1745 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1746 "element bit-width is odd.", F);
1749 Ty = VectorType::getTruncatedElementVectorType(VTy);
1751 Ty = VectorType::getExtendedElementVectorType(VTy);
1752 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1755 if (Match <= static_cast<int>(NumRetVals - 1)) {
1757 RetTy = ST->getElementType(Match);
1760 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1761 "match return type.", F);
1765 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1766 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1767 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1771 } else if (VT == MVT::iAny) {
1772 if (!EltTy->isIntegerTy()) {
1773 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1774 "an integer type.", F);
1778 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1782 Suffix += "v" + utostr(NumElts);
1784 Suffix += "i" + utostr(GotBits);
1786 // Check some constraints on various intrinsics.
1788 default: break; // Not everything needs to be checked.
1789 case Intrinsic::bswap:
1790 if (GotBits < 16 || GotBits % 16 != 0) {
1791 CheckFailed("Intrinsic requires even byte width argument", F);
1796 } else if (VT == MVT::fAny) {
1797 if (!EltTy->isFloatingPointTy()) {
1798 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1799 "a floating-point type.", F);
1806 Suffix += "v" + utostr(NumElts);
1808 Suffix += EVT::getEVT(EltTy).getEVTString();
1809 } else if (VT == MVT::vAny) {
1811 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1815 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1816 } else if (VT == MVT::iPTR) {
1817 if (!Ty->isPointerTy()) {
1818 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1819 "pointer and a pointer is required.", F);
1822 } else if (VT == MVT::iPTRAny) {
1823 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1824 // and iPTR. In the verifier, we can not distinguish which case we have so
1825 // allow either case to be legal.
1826 if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1827 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1828 if (PointeeVT == MVT::Other) {
1829 CheckFailed("Intrinsic has pointer to complex type.");
1832 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1833 PointeeVT.getEVTString();
1835 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1836 "pointer and a pointer is required.", F);
1839 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1840 EVT VVT = EVT((MVT::SimpleValueType)VT);
1842 // If this is a vector argument, verify the number and type of elements.
1843 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1844 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1848 if (VVT.getVectorNumElements() != NumElts) {
1849 CheckFailed("Intrinsic prototype has incorrect number of "
1850 "vector elements!", F);
1853 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1855 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1857 } else if (EltTy != Ty) {
1858 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1859 "and a scalar is required.", F);
1866 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1867 /// Intrinsics.gen. This implements a little state machine that verifies the
1868 /// prototype of intrinsics.
1869 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1870 unsigned NumRetVals,
1871 unsigned NumParams, ...) {
1873 va_start(VA, NumParams);
1874 const FunctionType *FTy = F->getFunctionType();
1876 // For overloaded intrinsics, the Suffix of the function name must match the
1877 // types of the arguments. This variable keeps track of the expected
1878 // suffix, to be checked at the end.
1881 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1882 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1886 const Type *Ty = FTy->getReturnType();
1887 const StructType *ST = dyn_cast<StructType>(Ty);
1889 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1890 CheckFailed("Intrinsic should return void", F);
1894 // Verify the return types.
1895 if (ST && ST->getNumElements() != NumRetVals) {
1896 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1900 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1901 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1903 if (ST) Ty = ST->getElementType(ArgNo);
1904 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1908 // Verify the parameter types.
1909 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1910 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1912 if (VT == MVT::isVoid && ArgNo > 0) {
1913 if (!FTy->isVarArg())
1914 CheckFailed("Intrinsic prototype has no '...'!", F);
1918 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1919 ArgNo + NumRetVals, Suffix))
1925 // For intrinsics without pointer arguments, if we computed a Suffix then the
1926 // intrinsic is overloaded and we need to make sure that the name of the
1927 // function is correct. We add the suffix to the name of the intrinsic and
1928 // compare against the given function name. If they are not the same, the
1929 // function name is invalid. This ensures that overloading of intrinsics
1930 // uses a sane and consistent naming convention. Note that intrinsics with
1931 // pointer argument may or may not be overloaded so we will check assuming it
1932 // has a suffix and not.
1933 if (!Suffix.empty()) {
1934 std::string Name(Intrinsic::getName(ID));
1935 if (Name + Suffix != F->getName()) {
1936 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1937 F->getName().substr(Name.length()) + "'. It should be '" +
1942 // Check parameter attributes.
1943 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1944 "Intrinsic has wrong parameter attributes!", F);
1948 //===----------------------------------------------------------------------===//
1949 // Implement the public interfaces to this file...
1950 //===----------------------------------------------------------------------===//
1952 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1953 return new Verifier(action);
1957 /// verifyFunction - Check a function for errors, printing messages on stderr.
1958 /// Return true if the function is corrupt.
1960 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1961 Function &F = const_cast<Function&>(f);
1962 assert(!F.isDeclaration() && "Cannot verify external functions");
1964 FunctionPassManager FPM(F.getParent());
1965 Verifier *V = new Verifier(action);
1971 /// verifyModule - Check a module for errors, printing messages on stderr.
1972 /// Return true if the module is corrupt.
1974 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1975 std::string *ErrorInfo) {
1977 Verifier *V = new Verifier(action);
1979 PM.run(const_cast<Module&>(M));
1981 if (ErrorInfo && V->Broken)
1982 *ErrorInfo = V->MessagesStr.str();