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/Analysis/Dominators.h"
53 #include "llvm/Assembly/Writer.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/Support/CallSite.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/InstVisitor.h"
59 #include "llvm/ADT/SetVector.h"
60 #include "llvm/ADT/SmallPtrSet.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/StringExtras.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/raw_ostream.h"
70 namespace { // Anonymous namespace for class
71 struct PreVerifier : public FunctionPass {
72 static char ID; // Pass ID, replacement for typeid
74 PreVerifier() : FunctionPass(ID) {
75 initializePreVerifierPass(*PassRegistry::getPassRegistry());
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 // Check that the prerequisites for successful DominatorTree construction
84 bool runOnFunction(Function &F) {
87 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
88 if (I->empty() || !I->back().isTerminator()) {
89 dbgs() << "Basic Block in function '" << F.getName()
90 << "' does not have terminator!\n";
91 WriteAsOperand(dbgs(), I, true);
98 report_fatal_error("Broken module, no Basic Block terminator!");
105 char PreVerifier::ID = 0;
106 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
108 static char &PreVerifyID = PreVerifier::ID;
111 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
112 static char ID; // Pass ID, replacement for typeid
113 bool Broken; // Is this module found to be broken?
114 bool RealPass; // Are we not being run by a PassManager?
115 VerifierFailureAction action;
116 // What to do if verification fails.
117 Module *Mod; // Module we are verifying right now
118 LLVMContext *Context; // Context within which we are verifying
119 DominatorTree *DT; // Dominator Tree, caution can be null!
121 std::string Messages;
122 raw_string_ostream MessagesStr;
124 /// InstInThisBlock - when verifying a basic block, keep track of all of the
125 /// instructions we have seen so far. This allows us to do efficient
126 /// dominance checks for the case when an instruction has an operand that is
127 /// an instruction in the same block.
128 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
130 /// MDNodes - keep track of the metadata nodes that have been checked
132 SmallPtrSet<MDNode *, 32> MDNodes;
136 Broken(false), RealPass(true), action(AbortProcessAction),
137 Mod(0), Context(0), DT(0), MessagesStr(Messages) {
138 initializeVerifierPass(*PassRegistry::getPassRegistry());
140 explicit Verifier(VerifierFailureAction ctn)
142 Broken(false), RealPass(true), action(ctn), Mod(0), Context(0), DT(0),
143 MessagesStr(Messages) {
144 initializeVerifierPass(*PassRegistry::getPassRegistry());
147 bool doInitialization(Module &M) {
149 Context = &M.getContext();
151 // If this is a real pass, in a pass manager, we must abort before
152 // returning back to the pass manager, or else the pass manager may try to
153 // run other passes on the broken module.
155 return abortIfBroken();
159 bool runOnFunction(Function &F) {
160 // Get dominator information if we are being run by PassManager
161 if (RealPass) DT = &getAnalysis<DominatorTree>();
164 if (!Context) Context = &F.getContext();
167 InstsInThisBlock.clear();
169 // If this is a real pass, in a pass manager, we must abort before
170 // returning back to the pass manager, or else the pass manager may try to
171 // run other passes on the broken module.
173 return abortIfBroken();
178 bool doFinalization(Module &M) {
179 // Scan through, checking all of the external function's linkage now...
180 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
181 visitGlobalValue(*I);
183 // Check to make sure function prototypes are okay.
184 if (I->isDeclaration()) visitFunction(*I);
187 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
189 visitGlobalVariable(*I);
191 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
193 visitGlobalAlias(*I);
195 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
196 E = M.named_metadata_end(); I != E; ++I)
197 visitNamedMDNode(*I);
199 // If the module is broken, abort at this time.
200 return abortIfBroken();
203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.setPreservesAll();
205 AU.addRequiredID(PreVerifyID);
207 AU.addRequired<DominatorTree>();
210 /// abortIfBroken - If the module is broken and we are supposed to abort on
211 /// this condition, do so.
213 bool abortIfBroken() {
214 if (!Broken) return false;
215 MessagesStr << "Broken module found, ";
217 default: llvm_unreachable("Unknown action");
218 case AbortProcessAction:
219 MessagesStr << "compilation aborted!\n";
220 dbgs() << MessagesStr.str();
221 // Client should choose different reaction if abort is not desired
223 case PrintMessageAction:
224 MessagesStr << "verification continues.\n";
225 dbgs() << MessagesStr.str();
227 case ReturnStatusAction:
228 MessagesStr << "compilation terminated.\n";
234 // Verification methods...
235 void visitGlobalValue(GlobalValue &GV);
236 void visitGlobalVariable(GlobalVariable &GV);
237 void visitGlobalAlias(GlobalAlias &GA);
238 void visitNamedMDNode(NamedMDNode &NMD);
239 void visitMDNode(MDNode &MD, Function *F);
240 void visitFunction(Function &F);
241 void visitBasicBlock(BasicBlock &BB);
242 using InstVisitor<Verifier>::visit;
244 void visit(Instruction &I);
246 void visitTruncInst(TruncInst &I);
247 void visitZExtInst(ZExtInst &I);
248 void visitSExtInst(SExtInst &I);
249 void visitFPTruncInst(FPTruncInst &I);
250 void visitFPExtInst(FPExtInst &I);
251 void visitFPToUIInst(FPToUIInst &I);
252 void visitFPToSIInst(FPToSIInst &I);
253 void visitUIToFPInst(UIToFPInst &I);
254 void visitSIToFPInst(SIToFPInst &I);
255 void visitIntToPtrInst(IntToPtrInst &I);
256 void visitPtrToIntInst(PtrToIntInst &I);
257 void visitBitCastInst(BitCastInst &I);
258 void visitPHINode(PHINode &PN);
259 void visitBinaryOperator(BinaryOperator &B);
260 void visitICmpInst(ICmpInst &IC);
261 void visitFCmpInst(FCmpInst &FC);
262 void visitExtractElementInst(ExtractElementInst &EI);
263 void visitInsertElementInst(InsertElementInst &EI);
264 void visitShuffleVectorInst(ShuffleVectorInst &EI);
265 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
266 void visitCallInst(CallInst &CI);
267 void visitInvokeInst(InvokeInst &II);
268 void visitGetElementPtrInst(GetElementPtrInst &GEP);
269 void visitLoadInst(LoadInst &LI);
270 void visitStoreInst(StoreInst &SI);
271 void visitInstruction(Instruction &I);
272 void visitTerminatorInst(TerminatorInst &I);
273 void visitBranchInst(BranchInst &BI);
274 void visitReturnInst(ReturnInst &RI);
275 void visitSwitchInst(SwitchInst &SI);
276 void visitIndirectBrInst(IndirectBrInst &BI);
277 void visitSelectInst(SelectInst &SI);
278 void visitUserOp1(Instruction &I);
279 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
280 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
281 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
282 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
283 void visitFenceInst(FenceInst &FI);
284 void visitAllocaInst(AllocaInst &AI);
285 void visitExtractValueInst(ExtractValueInst &EVI);
286 void visitInsertValueInst(InsertValueInst &IVI);
288 void VerifyCallSite(CallSite CS);
289 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
290 int VT, unsigned ArgNo, std::string &Suffix);
291 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
292 unsigned RetNum, unsigned ParamNum, ...);
293 void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
294 bool isReturnValue, const Value *V);
295 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
298 void WriteValue(const Value *V) {
300 if (isa<Instruction>(V)) {
301 MessagesStr << *V << '\n';
303 WriteAsOperand(MessagesStr, V, true, Mod);
308 void WriteType(Type *T) {
310 MessagesStr << ' ' << *T;
314 // CheckFailed - A check failed, so print out the condition and the message
315 // that failed. This provides a nice place to put a breakpoint if you want
316 // to see why something is not correct.
317 void CheckFailed(const Twine &Message,
318 const Value *V1 = 0, const Value *V2 = 0,
319 const Value *V3 = 0, const Value *V4 = 0) {
320 MessagesStr << Message.str() << "\n";
328 void CheckFailed(const Twine &Message, const Value *V1,
329 Type *T2, const Value *V3 = 0) {
330 MessagesStr << Message.str() << "\n";
337 void CheckFailed(const Twine &Message, Type *T1,
338 Type *T2 = 0, Type *T3 = 0) {
339 MessagesStr << Message.str() << "\n";
346 } // End anonymous namespace
348 char Verifier::ID = 0;
349 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
350 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
351 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
352 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
354 // Assert - We know that cond should be true, if not print an error message.
355 #define Assert(C, M) \
356 do { if (!(C)) { CheckFailed(M); return; } } while (0)
357 #define Assert1(C, M, V1) \
358 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
359 #define Assert2(C, M, V1, V2) \
360 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
361 #define Assert3(C, M, V1, V2, V3) \
362 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
363 #define Assert4(C, M, V1, V2, V3, V4) \
364 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
366 void Verifier::visit(Instruction &I) {
367 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
368 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
369 InstVisitor<Verifier>::visit(I);
373 void Verifier::visitGlobalValue(GlobalValue &GV) {
374 Assert1(!GV.isDeclaration() ||
375 GV.isMaterializable() ||
376 GV.hasExternalLinkage() ||
377 GV.hasDLLImportLinkage() ||
378 GV.hasExternalWeakLinkage() ||
379 (isa<GlobalAlias>(GV) &&
380 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
381 "Global is external, but doesn't have external or dllimport or weak linkage!",
384 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
385 "Global is marked as dllimport, but not external", &GV);
387 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
388 "Only global variables can have appending linkage!", &GV);
390 if (GV.hasAppendingLinkage()) {
391 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
392 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
393 "Only global arrays can have appending linkage!", GVar);
396 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
397 "linker_private_weak_def_auto can only have default visibility!",
401 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
402 if (GV.hasInitializer()) {
403 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
404 "Global variable initializer type does not match global "
405 "variable type!", &GV);
407 // If the global has common linkage, it must have a zero initializer and
408 // cannot be constant.
409 if (GV.hasCommonLinkage()) {
410 Assert1(GV.getInitializer()->isNullValue(),
411 "'common' global must have a zero initializer!", &GV);
412 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
416 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
417 GV.hasExternalWeakLinkage(),
418 "invalid linkage type for global declaration", &GV);
421 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
422 GV.getName() == "llvm.global_dtors")) {
423 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
424 "invalid linkage for intrinsic global variable", &GV);
425 // Don't worry about emitting an error for it not being an array,
426 // visitGlobalValue will complain on appending non-array.
427 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
428 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
429 PointerType *FuncPtrTy =
430 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
431 Assert1(STy && STy->getNumElements() == 2 &&
432 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
433 STy->getTypeAtIndex(1) == FuncPtrTy,
434 "wrong type for intrinsic global variable", &GV);
438 visitGlobalValue(GV);
441 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
442 Assert1(!GA.getName().empty(),
443 "Alias name cannot be empty!", &GA);
444 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
446 "Alias should have external or external weak linkage!", &GA);
447 Assert1(GA.getAliasee(),
448 "Aliasee cannot be NULL!", &GA);
449 Assert1(GA.getType() == GA.getAliasee()->getType(),
450 "Alias and aliasee types should match!", &GA);
451 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
453 if (!isa<GlobalValue>(GA.getAliasee())) {
454 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
456 (CE->getOpcode() == Instruction::BitCast ||
457 CE->getOpcode() == Instruction::GetElementPtr) &&
458 isa<GlobalValue>(CE->getOperand(0)),
459 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
463 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
465 "Aliasing chain should end with function or global variable", &GA);
467 visitGlobalValue(GA);
470 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
471 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
472 MDNode *MD = NMD.getOperand(i);
476 Assert1(!MD->isFunctionLocal(),
477 "Named metadata operand cannot be function local!", MD);
482 void Verifier::visitMDNode(MDNode &MD, Function *F) {
483 // Only visit each node once. Metadata can be mutually recursive, so this
484 // avoids infinite recursion here, as well as being an optimization.
485 if (!MDNodes.insert(&MD))
488 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
489 Value *Op = MD.getOperand(i);
492 if (isa<Constant>(Op) || isa<MDString>(Op))
494 if (MDNode *N = dyn_cast<MDNode>(Op)) {
495 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
496 "Global metadata operand cannot be function local!", &MD, N);
500 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
502 // If this was an instruction, bb, or argument, verify that it is in the
503 // function that we expect.
504 Function *ActualF = 0;
505 if (Instruction *I = dyn_cast<Instruction>(Op))
506 ActualF = I->getParent()->getParent();
507 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
508 ActualF = BB->getParent();
509 else if (Argument *A = dyn_cast<Argument>(Op))
510 ActualF = A->getParent();
511 assert(ActualF && "Unimplemented function local metadata case!");
513 Assert2(ActualF == F, "function-local metadata used in wrong function",
518 // VerifyParameterAttrs - Check the given attributes for an argument or return
519 // value of the specified type. The value V is printed in error messages.
520 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
521 bool isReturnValue, const Value *V) {
522 if (Attrs == Attribute::None)
525 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
526 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
527 " only applies to the function!", V);
530 Attributes RetI = Attrs & Attribute::ParameterOnly;
531 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
532 " does not apply to return values!", V);
536 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
537 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
538 Assert1(!(MutI & (MutI - 1)), "Attributes " +
539 Attribute::getAsString(MutI) + " are incompatible!", V);
542 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
543 Assert1(!TypeI, "Wrong type for attribute " +
544 Attribute::getAsString(TypeI), V);
546 Attributes ByValI = Attrs & Attribute::ByVal;
547 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
548 Assert1(!ByValI || PTy->getElementType()->isSized(),
549 "Attribute " + Attribute::getAsString(ByValI) +
550 " does not support unsized types!", V);
553 "Attribute " + Attribute::getAsString(ByValI) +
554 " only applies to parameters with pointer type!", V);
558 // VerifyFunctionAttrs - Check parameter attributes against a function type.
559 // The value V is printed in error messages.
560 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
561 const AttrListPtr &Attrs,
566 bool SawNest = false;
568 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
569 const AttributeWithIndex &Attr = Attrs.getSlot(i);
573 Ty = FT->getReturnType();
574 else if (Attr.Index-1 < FT->getNumParams())
575 Ty = FT->getParamType(Attr.Index-1);
577 break; // VarArgs attributes, verified elsewhere.
579 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
581 if (Attr.Attrs & Attribute::Nest) {
582 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
586 if (Attr.Attrs & Attribute::StructRet)
587 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
590 Attributes FAttrs = Attrs.getFnAttributes();
591 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
592 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
593 " does not apply to the function!", V);
596 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
597 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
598 Assert1(!(MutI & (MutI - 1)), "Attributes " +
599 Attribute::getAsString(MutI) + " are incompatible!", V);
603 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
607 unsigned LastSlot = Attrs.getNumSlots() - 1;
608 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
609 if (LastIndex <= Params
610 || (LastIndex == (unsigned)~0
611 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
617 // visitFunction - Verify that a function is ok.
619 void Verifier::visitFunction(Function &F) {
620 // Check function arguments.
621 FunctionType *FT = F.getFunctionType();
622 unsigned NumArgs = F.arg_size();
624 Assert1(Context == &F.getContext(),
625 "Function context does not match Module context!", &F);
627 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
628 Assert2(FT->getNumParams() == NumArgs,
629 "# formal arguments must match # of arguments for function type!",
631 Assert1(F.getReturnType()->isFirstClassType() ||
632 F.getReturnType()->isVoidTy() ||
633 F.getReturnType()->isStructTy(),
634 "Functions cannot return aggregate values!", &F);
636 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
637 "Invalid struct return type!", &F);
639 const AttrListPtr &Attrs = F.getAttributes();
641 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
642 "Attributes after last parameter!", &F);
644 // Check function attributes.
645 VerifyFunctionAttrs(FT, Attrs, &F);
647 // Check that this function meets the restrictions on this calling convention.
648 switch (F.getCallingConv()) {
653 case CallingConv::Fast:
654 case CallingConv::Cold:
655 case CallingConv::X86_FastCall:
656 case CallingConv::X86_ThisCall:
657 case CallingConv::PTX_Kernel:
658 case CallingConv::PTX_Device:
659 Assert1(!F.isVarArg(),
660 "Varargs functions must have C calling conventions!", &F);
664 bool isLLVMdotName = F.getName().size() >= 5 &&
665 F.getName().substr(0, 5) == "llvm.";
667 // Check that the argument values match the function type for this function...
669 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
671 Assert2(I->getType() == FT->getParamType(i),
672 "Argument value does not match function argument type!",
673 I, FT->getParamType(i));
674 Assert1(I->getType()->isFirstClassType(),
675 "Function arguments must have first-class types!", I);
677 Assert2(!I->getType()->isMetadataTy(),
678 "Function takes metadata but isn't an intrinsic", I, &F);
681 if (F.isMaterializable()) {
682 // Function has a body somewhere we can't see.
683 } else if (F.isDeclaration()) {
684 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
685 F.hasExternalWeakLinkage(),
686 "invalid linkage type for function declaration", &F);
688 // Verify that this function (which has a body) is not named "llvm.*". It
689 // is not legal to define intrinsics.
690 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
692 // Check the entry node
693 BasicBlock *Entry = &F.getEntryBlock();
694 Assert1(pred_begin(Entry) == pred_end(Entry),
695 "Entry block to function must not have predecessors!", Entry);
697 // The address of the entry block cannot be taken, unless it is dead.
698 if (Entry->hasAddressTaken()) {
699 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
700 "blockaddress may not be used with the entry block!", Entry);
704 // If this function is actually an intrinsic, verify that it is only used in
705 // direct call/invokes, never having its "address taken".
706 if (F.getIntrinsicID()) {
708 if (F.hasAddressTaken(&U))
709 Assert1(0, "Invalid user of intrinsic instruction!", U);
713 // verifyBasicBlock - Verify that a basic block is well formed...
715 void Verifier::visitBasicBlock(BasicBlock &BB) {
716 InstsInThisBlock.clear();
718 // Ensure that basic blocks have terminators!
719 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
721 // Check constraints that this basic block imposes on all of the PHI nodes in
723 if (isa<PHINode>(BB.front())) {
724 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
725 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
726 std::sort(Preds.begin(), Preds.end());
728 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
729 // Ensure that PHI nodes have at least one entry!
730 Assert1(PN->getNumIncomingValues() != 0,
731 "PHI nodes must have at least one entry. If the block is dead, "
732 "the PHI should be removed!", PN);
733 Assert1(PN->getNumIncomingValues() == Preds.size(),
734 "PHINode should have one entry for each predecessor of its "
735 "parent basic block!", PN);
737 // Get and sort all incoming values in the PHI node...
739 Values.reserve(PN->getNumIncomingValues());
740 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
741 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
742 PN->getIncomingValue(i)));
743 std::sort(Values.begin(), Values.end());
745 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
746 // Check to make sure that if there is more than one entry for a
747 // particular basic block in this PHI node, that the incoming values are
750 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
751 Values[i].second == Values[i-1].second,
752 "PHI node has multiple entries for the same basic block with "
753 "different incoming values!", PN, Values[i].first,
754 Values[i].second, Values[i-1].second);
756 // Check to make sure that the predecessors and PHI node entries are
758 Assert3(Values[i].first == Preds[i],
759 "PHI node entries do not match predecessors!", PN,
760 Values[i].first, Preds[i]);
766 void Verifier::visitTerminatorInst(TerminatorInst &I) {
767 // Ensure that terminators only exist at the end of the basic block.
768 Assert1(&I == I.getParent()->getTerminator(),
769 "Terminator found in the middle of a basic block!", I.getParent());
773 void Verifier::visitBranchInst(BranchInst &BI) {
774 if (BI.isConditional()) {
775 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
776 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
778 visitTerminatorInst(BI);
781 void Verifier::visitReturnInst(ReturnInst &RI) {
782 Function *F = RI.getParent()->getParent();
783 unsigned N = RI.getNumOperands();
784 if (F->getReturnType()->isVoidTy())
786 "Found return instr that returns non-void in Function of void "
787 "return type!", &RI, F->getReturnType());
789 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
790 "Function return type does not match operand "
791 "type of return inst!", &RI, F->getReturnType());
793 // Check to make sure that the return value has necessary properties for
795 visitTerminatorInst(RI);
798 void Verifier::visitSwitchInst(SwitchInst &SI) {
799 // Check to make sure that all of the constants in the switch instruction
800 // have the same type as the switched-on value.
801 Type *SwitchTy = SI.getCondition()->getType();
802 SmallPtrSet<ConstantInt*, 32> Constants;
803 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
804 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
805 "Switch constants must all be same type as switch value!", &SI);
806 Assert2(Constants.insert(SI.getCaseValue(i)),
807 "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
810 visitTerminatorInst(SI);
813 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
814 Assert1(BI.getAddress()->getType()->isPointerTy(),
815 "Indirectbr operand must have pointer type!", &BI);
816 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
817 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
818 "Indirectbr destinations must all have pointer type!", &BI);
820 visitTerminatorInst(BI);
823 void Verifier::visitSelectInst(SelectInst &SI) {
824 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
826 "Invalid operands for select instruction!", &SI);
828 Assert1(SI.getTrueValue()->getType() == SI.getType(),
829 "Select values must have same type as select instruction!", &SI);
830 visitInstruction(SI);
833 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
834 /// a pass, if any exist, it's an error.
836 void Verifier::visitUserOp1(Instruction &I) {
837 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
840 void Verifier::visitTruncInst(TruncInst &I) {
841 // Get the source and destination types
842 Type *SrcTy = I.getOperand(0)->getType();
843 Type *DestTy = I.getType();
845 // Get the size of the types in bits, we'll need this later
846 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
847 unsigned DestBitSize = DestTy->getScalarSizeInBits();
849 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
850 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
851 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
852 "trunc source and destination must both be a vector or neither", &I);
853 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
858 void Verifier::visitZExtInst(ZExtInst &I) {
859 // Get the source and destination types
860 Type *SrcTy = I.getOperand(0)->getType();
861 Type *DestTy = I.getType();
863 // Get the size of the types in bits, we'll need this later
864 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
865 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
866 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
867 "zext source and destination must both be a vector or neither", &I);
868 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
869 unsigned DestBitSize = DestTy->getScalarSizeInBits();
871 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
876 void Verifier::visitSExtInst(SExtInst &I) {
877 // Get the source and destination types
878 Type *SrcTy = I.getOperand(0)->getType();
879 Type *DestTy = I.getType();
881 // Get the size of the types in bits, we'll need this later
882 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
883 unsigned DestBitSize = DestTy->getScalarSizeInBits();
885 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
886 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
887 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
888 "sext source and destination must both be a vector or neither", &I);
889 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
894 void Verifier::visitFPTruncInst(FPTruncInst &I) {
895 // Get the source and destination types
896 Type *SrcTy = I.getOperand(0)->getType();
897 Type *DestTy = I.getType();
898 // Get the size of the types in bits, we'll need this later
899 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
900 unsigned DestBitSize = DestTy->getScalarSizeInBits();
902 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
903 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
904 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
905 "fptrunc source and destination must both be a vector or neither",&I);
906 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
911 void Verifier::visitFPExtInst(FPExtInst &I) {
912 // Get the source and destination types
913 Type *SrcTy = I.getOperand(0)->getType();
914 Type *DestTy = I.getType();
916 // Get the size of the types in bits, we'll need this later
917 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
918 unsigned DestBitSize = DestTy->getScalarSizeInBits();
920 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
921 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
922 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
923 "fpext source and destination must both be a vector or neither", &I);
924 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
929 void Verifier::visitUIToFPInst(UIToFPInst &I) {
930 // Get the source and destination types
931 Type *SrcTy = I.getOperand(0)->getType();
932 Type *DestTy = I.getType();
934 bool SrcVec = SrcTy->isVectorTy();
935 bool DstVec = DestTy->isVectorTy();
937 Assert1(SrcVec == DstVec,
938 "UIToFP source and dest must both be vector or scalar", &I);
939 Assert1(SrcTy->isIntOrIntVectorTy(),
940 "UIToFP source must be integer or integer vector", &I);
941 Assert1(DestTy->isFPOrFPVectorTy(),
942 "UIToFP result must be FP or FP vector", &I);
944 if (SrcVec && DstVec)
945 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
946 cast<VectorType>(DestTy)->getNumElements(),
947 "UIToFP source and dest vector length mismatch", &I);
952 void Verifier::visitSIToFPInst(SIToFPInst &I) {
953 // Get the source and destination types
954 Type *SrcTy = I.getOperand(0)->getType();
955 Type *DestTy = I.getType();
957 bool SrcVec = SrcTy->isVectorTy();
958 bool DstVec = DestTy->isVectorTy();
960 Assert1(SrcVec == DstVec,
961 "SIToFP source and dest must both be vector or scalar", &I);
962 Assert1(SrcTy->isIntOrIntVectorTy(),
963 "SIToFP source must be integer or integer vector", &I);
964 Assert1(DestTy->isFPOrFPVectorTy(),
965 "SIToFP result must be FP or FP vector", &I);
967 if (SrcVec && DstVec)
968 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
969 cast<VectorType>(DestTy)->getNumElements(),
970 "SIToFP source and dest vector length mismatch", &I);
975 void Verifier::visitFPToUIInst(FPToUIInst &I) {
976 // Get the source and destination types
977 Type *SrcTy = I.getOperand(0)->getType();
978 Type *DestTy = I.getType();
980 bool SrcVec = SrcTy->isVectorTy();
981 bool DstVec = DestTy->isVectorTy();
983 Assert1(SrcVec == DstVec,
984 "FPToUI source and dest must both be vector or scalar", &I);
985 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
987 Assert1(DestTy->isIntOrIntVectorTy(),
988 "FPToUI result must be integer or integer vector", &I);
990 if (SrcVec && DstVec)
991 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
992 cast<VectorType>(DestTy)->getNumElements(),
993 "FPToUI source and dest vector length mismatch", &I);
998 void Verifier::visitFPToSIInst(FPToSIInst &I) {
999 // Get the source and destination types
1000 Type *SrcTy = I.getOperand(0)->getType();
1001 Type *DestTy = I.getType();
1003 bool SrcVec = SrcTy->isVectorTy();
1004 bool DstVec = DestTy->isVectorTy();
1006 Assert1(SrcVec == DstVec,
1007 "FPToSI source and dest must both be vector or scalar", &I);
1008 Assert1(SrcTy->isFPOrFPVectorTy(),
1009 "FPToSI source must be FP or FP vector", &I);
1010 Assert1(DestTy->isIntOrIntVectorTy(),
1011 "FPToSI result must be integer or integer vector", &I);
1013 if (SrcVec && DstVec)
1014 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1015 cast<VectorType>(DestTy)->getNumElements(),
1016 "FPToSI source and dest vector length mismatch", &I);
1018 visitInstruction(I);
1021 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1022 // Get the source and destination types
1023 Type *SrcTy = I.getOperand(0)->getType();
1024 Type *DestTy = I.getType();
1026 Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1027 Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1029 visitInstruction(I);
1032 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1033 // Get the source and destination types
1034 Type *SrcTy = I.getOperand(0)->getType();
1035 Type *DestTy = I.getType();
1037 Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1038 Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1040 visitInstruction(I);
1043 void Verifier::visitBitCastInst(BitCastInst &I) {
1044 // Get the source and destination types
1045 Type *SrcTy = I.getOperand(0)->getType();
1046 Type *DestTy = I.getType();
1048 // Get the size of the types in bits, we'll need this later
1049 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1050 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1052 // BitCast implies a no-op cast of type only. No bits change.
1053 // However, you can't cast pointers to anything but pointers.
1054 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1055 "Bitcast requires both operands to be pointer or neither", &I);
1056 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1058 // Disallow aggregates.
1059 Assert1(!SrcTy->isAggregateType(),
1060 "Bitcast operand must not be aggregate", &I);
1061 Assert1(!DestTy->isAggregateType(),
1062 "Bitcast type must not be aggregate", &I);
1064 visitInstruction(I);
1067 /// visitPHINode - Ensure that a PHI node is well formed.
1069 void Verifier::visitPHINode(PHINode &PN) {
1070 // Ensure that the PHI nodes are all grouped together at the top of the block.
1071 // This can be tested by checking whether the instruction before this is
1072 // either nonexistent (because this is begin()) or is a PHI node. If not,
1073 // then there is some other instruction before a PHI.
1074 Assert2(&PN == &PN.getParent()->front() ||
1075 isa<PHINode>(--BasicBlock::iterator(&PN)),
1076 "PHI nodes not grouped at top of basic block!",
1077 &PN, PN.getParent());
1079 // Check that all of the values of the PHI node have the same type as the
1080 // result, and that the incoming blocks are really basic blocks.
1081 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1082 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1083 "PHI node operands are not the same type as the result!", &PN);
1086 // All other PHI node constraints are checked in the visitBasicBlock method.
1088 visitInstruction(PN);
1091 void Verifier::VerifyCallSite(CallSite CS) {
1092 Instruction *I = CS.getInstruction();
1094 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1095 "Called function must be a pointer!", I);
1096 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1098 Assert1(FPTy->getElementType()->isFunctionTy(),
1099 "Called function is not pointer to function type!", I);
1100 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1102 // Verify that the correct number of arguments are being passed
1103 if (FTy->isVarArg())
1104 Assert1(CS.arg_size() >= FTy->getNumParams(),
1105 "Called function requires more parameters than were provided!",I);
1107 Assert1(CS.arg_size() == FTy->getNumParams(),
1108 "Incorrect number of arguments passed to called function!", I);
1110 // Verify that all arguments to the call match the function type.
1111 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1112 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1113 "Call parameter type does not match function signature!",
1114 CS.getArgument(i), FTy->getParamType(i), I);
1116 const AttrListPtr &Attrs = CS.getAttributes();
1118 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1119 "Attributes after last parameter!", I);
1121 // Verify call attributes.
1122 VerifyFunctionAttrs(FTy, Attrs, I);
1124 if (FTy->isVarArg())
1125 // Check attributes on the varargs part.
1126 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1127 Attributes Attr = Attrs.getParamAttributes(Idx);
1129 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1131 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1132 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1133 " cannot be used for vararg call arguments!", I);
1136 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1137 if (CS.getCalledFunction() == 0 ||
1138 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1139 for (FunctionType::param_iterator PI = FTy->param_begin(),
1140 PE = FTy->param_end(); PI != PE; ++PI)
1141 Assert1(!(*PI)->isMetadataTy(),
1142 "Function has metadata parameter but isn't an intrinsic", I);
1145 visitInstruction(*I);
1148 void Verifier::visitCallInst(CallInst &CI) {
1149 VerifyCallSite(&CI);
1151 if (Function *F = CI.getCalledFunction())
1152 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1153 visitIntrinsicFunctionCall(ID, CI);
1156 void Verifier::visitInvokeInst(InvokeInst &II) {
1157 VerifyCallSite(&II);
1158 visitTerminatorInst(II);
1161 /// visitBinaryOperator - Check that both arguments to the binary operator are
1162 /// of the same type!
1164 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1165 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1166 "Both operands to a binary operator are not of the same type!", &B);
1168 switch (B.getOpcode()) {
1169 // Check that integer arithmetic operators are only used with
1170 // integral operands.
1171 case Instruction::Add:
1172 case Instruction::Sub:
1173 case Instruction::Mul:
1174 case Instruction::SDiv:
1175 case Instruction::UDiv:
1176 case Instruction::SRem:
1177 case Instruction::URem:
1178 Assert1(B.getType()->isIntOrIntVectorTy(),
1179 "Integer arithmetic operators only work with integral types!", &B);
1180 Assert1(B.getType() == B.getOperand(0)->getType(),
1181 "Integer arithmetic operators must have same type "
1182 "for operands and result!", &B);
1184 // Check that floating-point arithmetic operators are only used with
1185 // floating-point operands.
1186 case Instruction::FAdd:
1187 case Instruction::FSub:
1188 case Instruction::FMul:
1189 case Instruction::FDiv:
1190 case Instruction::FRem:
1191 Assert1(B.getType()->isFPOrFPVectorTy(),
1192 "Floating-point arithmetic operators only work with "
1193 "floating-point types!", &B);
1194 Assert1(B.getType() == B.getOperand(0)->getType(),
1195 "Floating-point arithmetic operators must have same type "
1196 "for operands and result!", &B);
1198 // Check that logical operators are only used with integral operands.
1199 case Instruction::And:
1200 case Instruction::Or:
1201 case Instruction::Xor:
1202 Assert1(B.getType()->isIntOrIntVectorTy(),
1203 "Logical operators only work with integral types!", &B);
1204 Assert1(B.getType() == B.getOperand(0)->getType(),
1205 "Logical operators must have same type for operands and result!",
1208 case Instruction::Shl:
1209 case Instruction::LShr:
1210 case Instruction::AShr:
1211 Assert1(B.getType()->isIntOrIntVectorTy(),
1212 "Shifts only work with integral types!", &B);
1213 Assert1(B.getType() == B.getOperand(0)->getType(),
1214 "Shift return type must be same as operands!", &B);
1217 llvm_unreachable("Unknown BinaryOperator opcode!");
1220 visitInstruction(B);
1223 void Verifier::visitICmpInst(ICmpInst &IC) {
1224 // Check that the operands are the same type
1225 Type *Op0Ty = IC.getOperand(0)->getType();
1226 Type *Op1Ty = IC.getOperand(1)->getType();
1227 Assert1(Op0Ty == Op1Ty,
1228 "Both operands to ICmp instruction are not of the same type!", &IC);
1229 // Check that the operands are the right type
1230 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1231 "Invalid operand types for ICmp instruction", &IC);
1232 // Check that the predicate is valid.
1233 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1234 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1235 "Invalid predicate in ICmp instruction!", &IC);
1237 visitInstruction(IC);
1240 void Verifier::visitFCmpInst(FCmpInst &FC) {
1241 // Check that the operands are the same type
1242 Type *Op0Ty = FC.getOperand(0)->getType();
1243 Type *Op1Ty = FC.getOperand(1)->getType();
1244 Assert1(Op0Ty == Op1Ty,
1245 "Both operands to FCmp instruction are not of the same type!", &FC);
1246 // Check that the operands are the right type
1247 Assert1(Op0Ty->isFPOrFPVectorTy(),
1248 "Invalid operand types for FCmp instruction", &FC);
1249 // Check that the predicate is valid.
1250 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1251 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1252 "Invalid predicate in FCmp instruction!", &FC);
1254 visitInstruction(FC);
1257 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1258 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1260 "Invalid extractelement operands!", &EI);
1261 visitInstruction(EI);
1264 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1265 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1268 "Invalid insertelement operands!", &IE);
1269 visitInstruction(IE);
1272 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1273 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1275 "Invalid shufflevector operands!", &SV);
1276 visitInstruction(SV);
1279 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1280 Assert1(cast<PointerType>(GEP.getOperand(0)->getType())
1281 ->getElementType()->isSized(),
1282 "GEP into unsized type!", &GEP);
1284 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1286 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(), Idxs);
1287 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1288 Assert2(GEP.getType()->isPointerTy() &&
1289 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1290 "GEP is not of right type for indices!", &GEP, ElTy);
1291 visitInstruction(GEP);
1294 void Verifier::visitLoadInst(LoadInst &LI) {
1295 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1296 Assert1(PTy, "Load operand must be a pointer.", &LI);
1297 Type *ElTy = PTy->getElementType();
1298 Assert2(ElTy == LI.getType(),
1299 "Load result type does not match pointer operand type!", &LI, ElTy);
1300 visitInstruction(LI);
1303 void Verifier::visitStoreInst(StoreInst &SI) {
1304 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1305 Assert1(PTy, "Store operand must be a pointer.", &SI);
1306 Type *ElTy = PTy->getElementType();
1307 Assert2(ElTy == SI.getOperand(0)->getType(),
1308 "Stored value type does not match pointer operand type!",
1310 visitInstruction(SI);
1313 void Verifier::visitAllocaInst(AllocaInst &AI) {
1314 PointerType *PTy = AI.getType();
1315 Assert1(PTy->getAddressSpace() == 0,
1316 "Allocation instruction pointer not in the generic address space!",
1318 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1320 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1321 "Alloca array size must have integer type", &AI);
1322 visitInstruction(AI);
1325 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1326 Assert1(CXI.getOrdering() != NotAtomic,
1327 "cmpxchg instructions must be atomic.", &CXI);
1328 Assert1(CXI.getOrdering() != Unordered,
1329 "cmpxchg instructions cannot be unordered.", &CXI);
1330 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1331 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1332 Type *ElTy = PTy->getElementType();
1333 Assert2(ElTy == CXI.getOperand(1)->getType(),
1334 "Expected value type does not match pointer operand type!",
1336 Assert2(ElTy == CXI.getOperand(2)->getType(),
1337 "Stored value type does not match pointer operand type!",
1339 visitInstruction(CXI);
1342 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1343 Assert1(RMWI.getOrdering() != NotAtomic,
1344 "atomicrmw instructions must be atomic.", &RMWI);
1345 Assert1(RMWI.getOrdering() != Unordered,
1346 "atomicrmw instructions cannot be unordered.", &RMWI);
1347 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1348 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1349 Type *ElTy = PTy->getElementType();
1350 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1351 "Argument value type does not match pointer operand type!",
1353 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1354 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1355 "Invalid binary operation!", &RMWI);
1356 visitInstruction(RMWI);
1359 void Verifier::visitFenceInst(FenceInst &FI) {
1360 const AtomicOrdering Ordering = FI.getOrdering();
1361 Assert1(Ordering == Acquire || Ordering == Release ||
1362 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1363 "fence instructions may only have "
1364 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1365 visitInstruction(FI);
1368 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1369 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1370 EVI.getIndices()) ==
1372 "Invalid ExtractValueInst operands!", &EVI);
1374 visitInstruction(EVI);
1377 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1378 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1379 IVI.getIndices()) ==
1380 IVI.getOperand(1)->getType(),
1381 "Invalid InsertValueInst operands!", &IVI);
1383 visitInstruction(IVI);
1386 /// verifyInstruction - Verify that an instruction is well formed.
1388 void Verifier::visitInstruction(Instruction &I) {
1389 BasicBlock *BB = I.getParent();
1390 Assert1(BB, "Instruction not embedded in basic block!", &I);
1392 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1393 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1395 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1396 "Only PHI nodes may reference their own value!", &I);
1399 // Check that void typed values don't have names
1400 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1401 "Instruction has a name, but provides a void value!", &I);
1403 // Check that the return value of the instruction is either void or a legal
1405 Assert1(I.getType()->isVoidTy() ||
1406 I.getType()->isFirstClassType(),
1407 "Instruction returns a non-scalar type!", &I);
1409 // Check that the instruction doesn't produce metadata. Calls are already
1410 // checked against the callee type.
1411 Assert1(!I.getType()->isMetadataTy() ||
1412 isa<CallInst>(I) || isa<InvokeInst>(I),
1413 "Invalid use of metadata!", &I);
1415 // Check that all uses of the instruction, if they are instructions
1416 // themselves, actually have parent basic blocks. If the use is not an
1417 // instruction, it is an error!
1418 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1420 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1421 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1422 " embedded in a basic block!", &I, Used);
1424 CheckFailed("Use of instruction is not an instruction!", *UI);
1429 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1430 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1432 // Check to make sure that only first-class-values are operands to
1434 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1435 Assert1(0, "Instruction operands must be first-class values!", &I);
1438 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1439 // Check to make sure that the "address of" an intrinsic function is never
1441 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1442 "Cannot take the address of an intrinsic!", &I);
1443 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1445 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1446 Assert1(OpBB->getParent() == BB->getParent(),
1447 "Referring to a basic block in another function!", &I);
1448 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1449 Assert1(OpArg->getParent() == BB->getParent(),
1450 "Referring to an argument in another function!", &I);
1451 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1452 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1454 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1455 BasicBlock *OpBlock = Op->getParent();
1457 // Check that a definition dominates all of its uses.
1458 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1459 // Invoke results are only usable in the normal destination, not in the
1460 // exceptional destination.
1461 BasicBlock *NormalDest = II->getNormalDest();
1463 Assert2(NormalDest != II->getUnwindDest(),
1464 "No uses of invoke possible due to dominance structure!",
1467 // PHI nodes differ from other nodes because they actually "use" the
1468 // value in the predecessor basic blocks they correspond to.
1469 BasicBlock *UseBlock = BB;
1470 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1471 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1472 UseBlock = PN->getIncomingBlock(j);
1474 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1477 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1478 // Special case of a phi node in the normal destination or the unwind
1480 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1481 "Invoke result not available in the unwind destination!",
1484 Assert2(DT->dominates(NormalDest, UseBlock) ||
1485 !DT->isReachableFromEntry(UseBlock),
1486 "Invoke result does not dominate all uses!", Op, &I);
1488 // If the normal successor of an invoke instruction has multiple
1489 // predecessors, then the normal edge from the invoke is critical,
1490 // so the invoke value can only be live if the destination block
1491 // dominates all of it's predecessors (other than the invoke).
1492 if (!NormalDest->getSinglePredecessor() &&
1493 DT->isReachableFromEntry(UseBlock))
1494 // If it is used by something non-phi, then the other case is that
1495 // 'NormalDest' dominates all of its predecessors other than the
1496 // invoke. In this case, the invoke value can still be used.
1497 for (pred_iterator PI = pred_begin(NormalDest),
1498 E = pred_end(NormalDest); PI != E; ++PI)
1499 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1500 DT->isReachableFromEntry(*PI)) {
1501 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1505 } else if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1506 // PHI nodes are more difficult than other nodes because they actually
1507 // "use" the value in the predecessor basic blocks they correspond to.
1508 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1509 BasicBlock *PredBB = PN->getIncomingBlock(j);
1510 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1511 !DT->isReachableFromEntry(PredBB)),
1512 "Instruction does not dominate all uses!", Op, &I);
1514 if (OpBlock == BB) {
1515 // If they are in the same basic block, make sure that the definition
1516 // comes before the use.
1517 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1518 "Instruction does not dominate all uses!", Op, &I);
1521 // Definition must dominate use unless use is unreachable!
1522 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1523 !DT->isReachableFromEntry(BB),
1524 "Instruction does not dominate all uses!", Op, &I);
1526 } else if (isa<InlineAsm>(I.getOperand(i))) {
1527 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1528 (i + 3 == e && isa<InvokeInst>(I)),
1529 "Cannot take the address of an inline asm!", &I);
1532 InstsInThisBlock.insert(&I);
1535 // Flags used by TableGen to mark intrinsic parameters with the
1536 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1537 static const unsigned ExtendedElementVectorType = 0x40000000;
1538 static const unsigned TruncatedElementVectorType = 0x20000000;
1540 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1542 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1543 Function *IF = CI.getCalledFunction();
1544 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1547 #define GET_INTRINSIC_VERIFIER
1548 #include "llvm/Intrinsics.gen"
1549 #undef GET_INTRINSIC_VERIFIER
1551 // If the intrinsic takes MDNode arguments, verify that they are either global
1552 // or are local to *this* function.
1553 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1554 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1555 visitMDNode(*MD, CI.getParent()->getParent());
1560 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1561 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1562 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1563 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1564 Assert1(MD->getNumOperands() == 1,
1565 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1567 case Intrinsic::memcpy:
1568 case Intrinsic::memmove:
1569 case Intrinsic::memset:
1570 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1571 "alignment argument of memory intrinsics must be a constant int",
1573 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1574 "isvolatile argument of memory intrinsics must be a constant int",
1577 case Intrinsic::gcroot:
1578 case Intrinsic::gcwrite:
1579 case Intrinsic::gcread:
1580 if (ID == Intrinsic::gcroot) {
1582 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1583 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1584 Assert1(isa<Constant>(CI.getArgOperand(1)),
1585 "llvm.gcroot parameter #2 must be a constant.", &CI);
1586 if (!AI->getType()->getElementType()->isPointerTy()) {
1587 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1588 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1589 "or argument #2 must be a non-null constant.", &CI);
1593 Assert1(CI.getParent()->getParent()->hasGC(),
1594 "Enclosing function does not use GC.", &CI);
1596 case Intrinsic::init_trampoline:
1597 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1598 "llvm.init_trampoline parameter #2 must resolve to a function.",
1601 case Intrinsic::prefetch:
1602 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1603 isa<ConstantInt>(CI.getArgOperand(2)) &&
1604 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1605 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1606 "invalid arguments to llvm.prefetch",
1609 case Intrinsic::stackprotector:
1610 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1611 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1614 case Intrinsic::lifetime_start:
1615 case Intrinsic::lifetime_end:
1616 case Intrinsic::invariant_start:
1617 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1618 "size argument of memory use markers must be a constant integer",
1621 case Intrinsic::invariant_end:
1622 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1623 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1628 /// Produce a string to identify an intrinsic parameter or return value.
1629 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1630 /// parameters beginning with NumRets.
1632 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1633 if (ArgNo >= NumRets)
1634 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1636 return "Intrinsic result type";
1637 return "Intrinsic result type #" + utostr(ArgNo);
1640 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
1641 int VT, unsigned ArgNo, std::string &Suffix) {
1642 FunctionType *FTy = F->getFunctionType();
1644 unsigned NumElts = 0;
1646 VectorType *VTy = dyn_cast<VectorType>(Ty);
1648 EltTy = VTy->getElementType();
1649 NumElts = VTy->getNumElements();
1652 Type *RetTy = FTy->getReturnType();
1653 StructType *ST = dyn_cast<StructType>(RetTy);
1654 unsigned NumRetVals;
1655 if (RetTy->isVoidTy())
1658 NumRetVals = ST->getNumElements();
1665 // Check flags that indicate a type that is an integral vector type with
1666 // elements that are larger or smaller than the elements of the matched
1668 if ((Match & (ExtendedElementVectorType |
1669 TruncatedElementVectorType)) != 0) {
1670 IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1671 if (!VTy || !IEltTy) {
1672 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1673 "an integral vector type.", F);
1676 // Adjust the current Ty (in the opposite direction) rather than
1677 // the type being matched against.
1678 if ((Match & ExtendedElementVectorType) != 0) {
1679 if ((IEltTy->getBitWidth() & 1) != 0) {
1680 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1681 "element bit-width is odd.", F);
1684 Ty = VectorType::getTruncatedElementVectorType(VTy);
1686 Ty = VectorType::getExtendedElementVectorType(VTy);
1687 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1690 if (Match <= static_cast<int>(NumRetVals - 1)) {
1692 RetTy = ST->getElementType(Match);
1695 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1696 "match return type.", F);
1700 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1701 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1702 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1706 } else if (VT == MVT::iAny) {
1707 if (!EltTy->isIntegerTy()) {
1708 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1709 "an integer type.", F);
1713 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1717 Suffix += "v" + utostr(NumElts);
1719 Suffix += "i" + utostr(GotBits);
1721 // Check some constraints on various intrinsics.
1723 default: break; // Not everything needs to be checked.
1724 case Intrinsic::bswap:
1725 if (GotBits < 16 || GotBits % 16 != 0) {
1726 CheckFailed("Intrinsic requires even byte width argument", F);
1731 } else if (VT == MVT::fAny) {
1732 if (!EltTy->isFloatingPointTy()) {
1733 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1734 "a floating-point type.", F);
1741 Suffix += "v" + utostr(NumElts);
1743 Suffix += EVT::getEVT(EltTy).getEVTString();
1744 } else if (VT == MVT::vAny) {
1746 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1750 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1751 } else if (VT == MVT::iPTR) {
1752 if (!Ty->isPointerTy()) {
1753 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1754 "pointer and a pointer is required.", F);
1757 } else if (VT == MVT::iPTRAny) {
1758 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1759 // and iPTR. In the verifier, we can not distinguish which case we have so
1760 // allow either case to be legal.
1761 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1762 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1763 if (PointeeVT == MVT::Other) {
1764 CheckFailed("Intrinsic has pointer to complex type.");
1767 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1768 PointeeVT.getEVTString();
1770 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1771 "pointer and a pointer is required.", F);
1774 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1775 EVT VVT = EVT((MVT::SimpleValueType)VT);
1777 // If this is a vector argument, verify the number and type of elements.
1778 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1779 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1783 if (VVT.getVectorNumElements() != NumElts) {
1784 CheckFailed("Intrinsic prototype has incorrect number of "
1785 "vector elements!", F);
1788 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1790 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1792 } else if (EltTy != Ty) {
1793 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1794 "and a scalar is required.", F);
1801 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1802 /// Intrinsics.gen. This implements a little state machine that verifies the
1803 /// prototype of intrinsics.
1804 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1805 unsigned NumRetVals,
1806 unsigned NumParams, ...) {
1808 va_start(VA, NumParams);
1809 FunctionType *FTy = F->getFunctionType();
1811 // For overloaded intrinsics, the Suffix of the function name must match the
1812 // types of the arguments. This variable keeps track of the expected
1813 // suffix, to be checked at the end.
1816 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1817 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1821 Type *Ty = FTy->getReturnType();
1822 StructType *ST = dyn_cast<StructType>(Ty);
1824 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1825 CheckFailed("Intrinsic should return void", F);
1829 // Verify the return types.
1830 if (ST && ST->getNumElements() != NumRetVals) {
1831 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1835 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1836 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1838 if (ST) Ty = ST->getElementType(ArgNo);
1839 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1843 // Verify the parameter types.
1844 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1845 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1847 if (VT == MVT::isVoid && ArgNo > 0) {
1848 if (!FTy->isVarArg())
1849 CheckFailed("Intrinsic prototype has no '...'!", F);
1853 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1854 ArgNo + NumRetVals, Suffix))
1860 // For intrinsics without pointer arguments, if we computed a Suffix then the
1861 // intrinsic is overloaded and we need to make sure that the name of the
1862 // function is correct. We add the suffix to the name of the intrinsic and
1863 // compare against the given function name. If they are not the same, the
1864 // function name is invalid. This ensures that overloading of intrinsics
1865 // uses a sane and consistent naming convention. Note that intrinsics with
1866 // pointer argument may or may not be overloaded so we will check assuming it
1867 // has a suffix and not.
1868 if (!Suffix.empty()) {
1869 std::string Name(Intrinsic::getName(ID));
1870 if (Name + Suffix != F->getName()) {
1871 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1872 F->getName().substr(Name.length()) + "'. It should be '" +
1877 // Check parameter attributes.
1878 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1879 "Intrinsic has wrong parameter attributes!", F);
1883 //===----------------------------------------------------------------------===//
1884 // Implement the public interfaces to this file...
1885 //===----------------------------------------------------------------------===//
1887 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1888 return new Verifier(action);
1892 /// verifyFunction - Check a function for errors, printing messages on stderr.
1893 /// Return true if the function is corrupt.
1895 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1896 Function &F = const_cast<Function&>(f);
1897 assert(!F.isDeclaration() && "Cannot verify external functions");
1899 FunctionPassManager FPM(F.getParent());
1900 Verifier *V = new Verifier(action);
1906 /// verifyModule - Check a module for errors, printing messages on stderr.
1907 /// Return true if the module is corrupt.
1909 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1910 std::string *ErrorInfo) {
1912 Verifier *V = new Verifier(action);
1914 PM.run(const_cast<Module&>(M));
1916 if (ErrorInfo && V->Broken)
1917 *ErrorInfo = V->MessagesStr.str();