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 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
42 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
48 #include "llvm/Analysis/Verifier.h"
49 #include "llvm/CallingConv.h"
50 #include "llvm/Constants.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/InlineAsm.h"
53 #include "llvm/IntrinsicInst.h"
54 #include "llvm/Metadata.h"
55 #include "llvm/Module.h"
56 #include "llvm/Pass.h"
57 #include "llvm/PassManager.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Assembly/Writer.h"
60 #include "llvm/CodeGen/ValueTypes.h"
61 #include "llvm/Support/CallSite.h"
62 #include "llvm/Support/CFG.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/InstVisitor.h"
65 #include "llvm/ADT/SetVector.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/SmallVector.h"
68 #include "llvm/ADT/StringExtras.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/raw_ostream.h"
76 namespace { // Anonymous namespace for class
77 struct PreVerifier : public FunctionPass {
78 static char ID; // Pass ID, replacement for typeid
80 PreVerifier() : FunctionPass(ID) {
81 initializePreVerifierPass(*PassRegistry::getPassRegistry());
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 // Check that the prerequisites for successful DominatorTree construction
90 bool runOnFunction(Function &F) {
93 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
94 if (I->empty() || !I->back().isTerminator()) {
95 dbgs() << "Basic Block in function '" << F.getName()
96 << "' does not have terminator!\n";
97 WriteAsOperand(dbgs(), I, true);
104 report_fatal_error("Broken module, no Basic Block terminator!");
111 char PreVerifier::ID = 0;
112 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
114 static char &PreVerifyID = PreVerifier::ID;
117 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
118 static char ID; // Pass ID, replacement for typeid
119 bool Broken; // Is this module found to be broken?
120 bool RealPass; // Are we not being run by a PassManager?
121 VerifierFailureAction action;
122 // What to do if verification fails.
123 Module *Mod; // Module we are verifying right now
124 LLVMContext *Context; // Context within which we are verifying
125 DominatorTree *DT; // Dominator Tree, caution can be null!
127 std::string Messages;
128 raw_string_ostream MessagesStr;
130 /// InstInThisBlock - when verifying a basic block, keep track of all of the
131 /// instructions we have seen so far. This allows us to do efficient
132 /// dominance checks for the case when an instruction has an operand that is
133 /// an instruction in the same block.
134 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
136 /// MDNodes - keep track of the metadata nodes that have been checked
138 SmallPtrSet<MDNode *, 32> MDNodes;
140 /// PersonalityFn - The personality function referenced by the
141 /// LandingPadInsts. All LandingPadInsts within the same function must use
142 /// the same personality function.
143 const Value *PersonalityFn;
146 : FunctionPass(ID), Broken(false), RealPass(true),
147 action(AbortProcessAction), Mod(0), Context(0), DT(0),
148 MessagesStr(Messages), PersonalityFn(0) {
149 initializeVerifierPass(*PassRegistry::getPassRegistry());
151 explicit Verifier(VerifierFailureAction ctn)
152 : FunctionPass(ID), Broken(false), RealPass(true), action(ctn), Mod(0),
153 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
154 initializeVerifierPass(*PassRegistry::getPassRegistry());
157 bool doInitialization(Module &M) {
159 Context = &M.getContext();
161 // If this is a real pass, in a pass manager, we must abort before
162 // returning back to the pass manager, or else the pass manager may try to
163 // run other passes on the broken module.
165 return abortIfBroken();
169 bool runOnFunction(Function &F) {
170 // Get dominator information if we are being run by PassManager
171 if (RealPass) DT = &getAnalysis<DominatorTree>();
174 if (!Context) Context = &F.getContext();
177 InstsInThisBlock.clear();
179 // If this is a real pass, in a pass manager, we must abort before
180 // returning back to the pass manager, or else the pass manager may try to
181 // run other passes on the broken module.
183 return abortIfBroken();
188 bool doFinalization(Module &M) {
189 // Scan through, checking all of the external function's linkage now...
190 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
191 visitGlobalValue(*I);
193 // Check to make sure function prototypes are okay.
194 if (I->isDeclaration()) visitFunction(*I);
197 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
199 visitGlobalVariable(*I);
201 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
203 visitGlobalAlias(*I);
205 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
206 E = M.named_metadata_end(); I != E; ++I)
207 visitNamedMDNode(*I);
209 // If the module is broken, abort at this time.
210 return abortIfBroken();
213 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
214 AU.setPreservesAll();
215 AU.addRequiredID(PreVerifyID);
217 AU.addRequired<DominatorTree>();
220 /// abortIfBroken - If the module is broken and we are supposed to abort on
221 /// this condition, do so.
223 bool abortIfBroken() {
224 if (!Broken) return false;
225 MessagesStr << "Broken module found, ";
227 default: llvm_unreachable("Unknown action");
228 case AbortProcessAction:
229 MessagesStr << "compilation aborted!\n";
230 dbgs() << MessagesStr.str();
231 // Client should choose different reaction if abort is not desired
233 case PrintMessageAction:
234 MessagesStr << "verification continues.\n";
235 dbgs() << MessagesStr.str();
237 case ReturnStatusAction:
238 MessagesStr << "compilation terminated.\n";
244 // Verification methods...
245 void visitGlobalValue(GlobalValue &GV);
246 void visitGlobalVariable(GlobalVariable &GV);
247 void visitGlobalAlias(GlobalAlias &GA);
248 void visitNamedMDNode(NamedMDNode &NMD);
249 void visitMDNode(MDNode &MD, Function *F);
250 void visitFunction(Function &F);
251 void visitBasicBlock(BasicBlock &BB);
252 using InstVisitor<Verifier>::visit;
254 void visit(Instruction &I);
256 void visitTruncInst(TruncInst &I);
257 void visitZExtInst(ZExtInst &I);
258 void visitSExtInst(SExtInst &I);
259 void visitFPTruncInst(FPTruncInst &I);
260 void visitFPExtInst(FPExtInst &I);
261 void visitFPToUIInst(FPToUIInst &I);
262 void visitFPToSIInst(FPToSIInst &I);
263 void visitUIToFPInst(UIToFPInst &I);
264 void visitSIToFPInst(SIToFPInst &I);
265 void visitIntToPtrInst(IntToPtrInst &I);
266 void visitPtrToIntInst(PtrToIntInst &I);
267 void visitBitCastInst(BitCastInst &I);
268 void visitPHINode(PHINode &PN);
269 void visitBinaryOperator(BinaryOperator &B);
270 void visitICmpInst(ICmpInst &IC);
271 void visitFCmpInst(FCmpInst &FC);
272 void visitExtractElementInst(ExtractElementInst &EI);
273 void visitInsertElementInst(InsertElementInst &EI);
274 void visitShuffleVectorInst(ShuffleVectorInst &EI);
275 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
276 void visitCallInst(CallInst &CI);
277 void visitInvokeInst(InvokeInst &II);
278 void visitGetElementPtrInst(GetElementPtrInst &GEP);
279 void visitLoadInst(LoadInst &LI);
280 void visitStoreInst(StoreInst &SI);
281 void visitInstruction(Instruction &I);
282 void visitTerminatorInst(TerminatorInst &I);
283 void visitBranchInst(BranchInst &BI);
284 void visitReturnInst(ReturnInst &RI);
285 void visitSwitchInst(SwitchInst &SI);
286 void visitIndirectBrInst(IndirectBrInst &BI);
287 void visitSelectInst(SelectInst &SI);
288 void visitUserOp1(Instruction &I);
289 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
290 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
291 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
292 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
293 void visitFenceInst(FenceInst &FI);
294 void visitAllocaInst(AllocaInst &AI);
295 void visitExtractValueInst(ExtractValueInst &EVI);
296 void visitInsertValueInst(InsertValueInst &IVI);
297 void visitLandingPadInst(LandingPadInst &LPI);
299 void VerifyCallSite(CallSite CS);
300 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
301 int VT, unsigned ArgNo, std::string &Suffix);
302 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
303 unsigned RetNum, unsigned ParamNum, ...);
304 void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
305 bool isReturnValue, const Value *V);
306 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
309 void WriteValue(const Value *V) {
311 if (isa<Instruction>(V)) {
312 MessagesStr << *V << '\n';
314 WriteAsOperand(MessagesStr, V, true, Mod);
319 void WriteType(Type *T) {
321 MessagesStr << ' ' << *T;
325 // CheckFailed - A check failed, so print out the condition and the message
326 // that failed. This provides a nice place to put a breakpoint if you want
327 // to see why something is not correct.
328 void CheckFailed(const Twine &Message,
329 const Value *V1 = 0, const Value *V2 = 0,
330 const Value *V3 = 0, const Value *V4 = 0) {
331 MessagesStr << Message.str() << "\n";
339 void CheckFailed(const Twine &Message, const Value *V1,
340 Type *T2, const Value *V3 = 0) {
341 MessagesStr << Message.str() << "\n";
348 void CheckFailed(const Twine &Message, Type *T1,
349 Type *T2 = 0, Type *T3 = 0) {
350 MessagesStr << Message.str() << "\n";
357 } // End anonymous namespace
359 char Verifier::ID = 0;
360 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
361 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
362 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
363 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
365 // Assert - We know that cond should be true, if not print an error message.
366 #define Assert(C, M) \
367 do { if (!(C)) { CheckFailed(M); return; } } while (0)
368 #define Assert1(C, M, V1) \
369 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
370 #define Assert2(C, M, V1, V2) \
371 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
372 #define Assert3(C, M, V1, V2, V3) \
373 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
374 #define Assert4(C, M, V1, V2, V3, V4) \
375 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
377 void Verifier::visit(Instruction &I) {
378 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
379 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
380 InstVisitor<Verifier>::visit(I);
384 void Verifier::visitGlobalValue(GlobalValue &GV) {
385 Assert1(!GV.isDeclaration() ||
386 GV.isMaterializable() ||
387 GV.hasExternalLinkage() ||
388 GV.hasDLLImportLinkage() ||
389 GV.hasExternalWeakLinkage() ||
390 (isa<GlobalAlias>(GV) &&
391 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
392 "Global is external, but doesn't have external or dllimport or weak linkage!",
395 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
396 "Global is marked as dllimport, but not external", &GV);
398 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
399 "Only global variables can have appending linkage!", &GV);
401 if (GV.hasAppendingLinkage()) {
402 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
403 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
404 "Only global arrays can have appending linkage!", GVar);
407 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
408 "linker_private_weak_def_auto can only have default visibility!",
412 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
413 if (GV.hasInitializer()) {
414 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
415 "Global variable initializer type does not match global "
416 "variable type!", &GV);
418 // If the global has common linkage, it must have a zero initializer and
419 // cannot be constant.
420 if (GV.hasCommonLinkage()) {
421 Assert1(GV.getInitializer()->isNullValue(),
422 "'common' global must have a zero initializer!", &GV);
423 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
427 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
428 GV.hasExternalWeakLinkage(),
429 "invalid linkage type for global declaration", &GV);
432 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
433 GV.getName() == "llvm.global_dtors")) {
434 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
435 "invalid linkage for intrinsic global variable", &GV);
436 // Don't worry about emitting an error for it not being an array,
437 // visitGlobalValue will complain on appending non-array.
438 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
439 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
440 PointerType *FuncPtrTy =
441 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
442 Assert1(STy && STy->getNumElements() == 2 &&
443 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
444 STy->getTypeAtIndex(1) == FuncPtrTy,
445 "wrong type for intrinsic global variable", &GV);
449 visitGlobalValue(GV);
452 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
453 Assert1(!GA.getName().empty(),
454 "Alias name cannot be empty!", &GA);
455 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
457 "Alias should have external or external weak linkage!", &GA);
458 Assert1(GA.getAliasee(),
459 "Aliasee cannot be NULL!", &GA);
460 Assert1(GA.getType() == GA.getAliasee()->getType(),
461 "Alias and aliasee types should match!", &GA);
462 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
464 if (!isa<GlobalValue>(GA.getAliasee())) {
465 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
467 (CE->getOpcode() == Instruction::BitCast ||
468 CE->getOpcode() == Instruction::GetElementPtr) &&
469 isa<GlobalValue>(CE->getOperand(0)),
470 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
474 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
476 "Aliasing chain should end with function or global variable", &GA);
478 visitGlobalValue(GA);
481 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
482 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
483 MDNode *MD = NMD.getOperand(i);
487 Assert1(!MD->isFunctionLocal(),
488 "Named metadata operand cannot be function local!", MD);
493 void Verifier::visitMDNode(MDNode &MD, Function *F) {
494 // Only visit each node once. Metadata can be mutually recursive, so this
495 // avoids infinite recursion here, as well as being an optimization.
496 if (!MDNodes.insert(&MD))
499 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
500 Value *Op = MD.getOperand(i);
503 if (isa<Constant>(Op) || isa<MDString>(Op))
505 if (MDNode *N = dyn_cast<MDNode>(Op)) {
506 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
507 "Global metadata operand cannot be function local!", &MD, N);
511 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
513 // If this was an instruction, bb, or argument, verify that it is in the
514 // function that we expect.
515 Function *ActualF = 0;
516 if (Instruction *I = dyn_cast<Instruction>(Op))
517 ActualF = I->getParent()->getParent();
518 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
519 ActualF = BB->getParent();
520 else if (Argument *A = dyn_cast<Argument>(Op))
521 ActualF = A->getParent();
522 assert(ActualF && "Unimplemented function local metadata case!");
524 Assert2(ActualF == F, "function-local metadata used in wrong function",
529 // VerifyParameterAttrs - Check the given attributes for an argument or return
530 // value of the specified type. The value V is printed in error messages.
531 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
532 bool isReturnValue, const Value *V) {
533 if (Attrs == Attribute::None)
536 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
537 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
538 " only applies to the function!", V);
541 Attributes RetI = Attrs & Attribute::ParameterOnly;
542 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
543 " does not apply to return values!", V);
547 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
548 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
549 Assert1(!(MutI & (MutI - 1)), "Attributes " +
550 Attribute::getAsString(MutI) + " are incompatible!", V);
553 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
554 Assert1(!TypeI, "Wrong type for attribute " +
555 Attribute::getAsString(TypeI), V);
557 Attributes ByValI = Attrs & Attribute::ByVal;
558 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
559 Assert1(!ByValI || PTy->getElementType()->isSized(),
560 "Attribute " + Attribute::getAsString(ByValI) +
561 " does not support unsized types!", V);
564 "Attribute " + Attribute::getAsString(ByValI) +
565 " only applies to parameters with pointer type!", V);
569 // VerifyFunctionAttrs - Check parameter attributes against a function type.
570 // The value V is printed in error messages.
571 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
572 const AttrListPtr &Attrs,
577 bool SawNest = false;
579 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
580 const AttributeWithIndex &Attr = Attrs.getSlot(i);
584 Ty = FT->getReturnType();
585 else if (Attr.Index-1 < FT->getNumParams())
586 Ty = FT->getParamType(Attr.Index-1);
588 break; // VarArgs attributes, verified elsewhere.
590 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
592 if (Attr.Attrs & Attribute::Nest) {
593 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
597 if (Attr.Attrs & Attribute::StructRet)
598 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
601 Attributes FAttrs = Attrs.getFnAttributes();
602 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
603 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
604 " does not apply to the function!", V);
607 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
608 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
609 Assert1(!(MutI & (MutI - 1)), "Attributes " +
610 Attribute::getAsString(MutI) + " are incompatible!", V);
614 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
618 unsigned LastSlot = Attrs.getNumSlots() - 1;
619 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
620 if (LastIndex <= Params
621 || (LastIndex == (unsigned)~0
622 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
628 // visitFunction - Verify that a function is ok.
630 void Verifier::visitFunction(Function &F) {
631 // Check function arguments.
632 FunctionType *FT = F.getFunctionType();
633 unsigned NumArgs = F.arg_size();
635 Assert1(Context == &F.getContext(),
636 "Function context does not match Module context!", &F);
638 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
639 Assert2(FT->getNumParams() == NumArgs,
640 "# formal arguments must match # of arguments for function type!",
642 Assert1(F.getReturnType()->isFirstClassType() ||
643 F.getReturnType()->isVoidTy() ||
644 F.getReturnType()->isStructTy(),
645 "Functions cannot return aggregate values!", &F);
647 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
648 "Invalid struct return type!", &F);
650 const AttrListPtr &Attrs = F.getAttributes();
652 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
653 "Attributes after last parameter!", &F);
655 // Check function attributes.
656 VerifyFunctionAttrs(FT, Attrs, &F);
658 // Check that this function meets the restrictions on this calling convention.
659 switch (F.getCallingConv()) {
664 case CallingConv::Fast:
665 case CallingConv::Cold:
666 case CallingConv::X86_FastCall:
667 case CallingConv::X86_ThisCall:
668 case CallingConv::PTX_Kernel:
669 case CallingConv::PTX_Device:
670 Assert1(!F.isVarArg(),
671 "Varargs functions must have C calling conventions!", &F);
675 bool isLLVMdotName = F.getName().size() >= 5 &&
676 F.getName().substr(0, 5) == "llvm.";
678 // Check that the argument values match the function type for this function...
680 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
682 Assert2(I->getType() == FT->getParamType(i),
683 "Argument value does not match function argument type!",
684 I, FT->getParamType(i));
685 Assert1(I->getType()->isFirstClassType(),
686 "Function arguments must have first-class types!", I);
688 Assert2(!I->getType()->isMetadataTy(),
689 "Function takes metadata but isn't an intrinsic", I, &F);
692 if (F.isMaterializable()) {
693 // Function has a body somewhere we can't see.
694 } else if (F.isDeclaration()) {
695 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
696 F.hasExternalWeakLinkage(),
697 "invalid linkage type for function declaration", &F);
699 // Verify that this function (which has a body) is not named "llvm.*". It
700 // is not legal to define intrinsics.
701 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
703 // Check the entry node
704 BasicBlock *Entry = &F.getEntryBlock();
705 Assert1(pred_begin(Entry) == pred_end(Entry),
706 "Entry block to function must not have predecessors!", Entry);
708 // The address of the entry block cannot be taken, unless it is dead.
709 if (Entry->hasAddressTaken()) {
710 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
711 "blockaddress may not be used with the entry block!", Entry);
715 // If this function is actually an intrinsic, verify that it is only used in
716 // direct call/invokes, never having its "address taken".
717 if (F.getIntrinsicID()) {
719 if (F.hasAddressTaken(&U))
720 Assert1(0, "Invalid user of intrinsic instruction!", U);
724 // verifyBasicBlock - Verify that a basic block is well formed...
726 void Verifier::visitBasicBlock(BasicBlock &BB) {
727 InstsInThisBlock.clear();
729 // Ensure that basic blocks have terminators!
730 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
732 // Check constraints that this basic block imposes on all of the PHI nodes in
734 if (isa<PHINode>(BB.front())) {
735 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
736 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
737 std::sort(Preds.begin(), Preds.end());
739 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
740 // Ensure that PHI nodes have at least one entry!
741 Assert1(PN->getNumIncomingValues() != 0,
742 "PHI nodes must have at least one entry. If the block is dead, "
743 "the PHI should be removed!", PN);
744 Assert1(PN->getNumIncomingValues() == Preds.size(),
745 "PHINode should have one entry for each predecessor of its "
746 "parent basic block!", PN);
748 // Get and sort all incoming values in the PHI node...
750 Values.reserve(PN->getNumIncomingValues());
751 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
752 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
753 PN->getIncomingValue(i)));
754 std::sort(Values.begin(), Values.end());
756 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
757 // Check to make sure that if there is more than one entry for a
758 // particular basic block in this PHI node, that the incoming values are
761 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
762 Values[i].second == Values[i-1].second,
763 "PHI node has multiple entries for the same basic block with "
764 "different incoming values!", PN, Values[i].first,
765 Values[i].second, Values[i-1].second);
767 // Check to make sure that the predecessors and PHI node entries are
769 Assert3(Values[i].first == Preds[i],
770 "PHI node entries do not match predecessors!", PN,
771 Values[i].first, Preds[i]);
777 void Verifier::visitTerminatorInst(TerminatorInst &I) {
778 // Ensure that terminators only exist at the end of the basic block.
779 Assert1(&I == I.getParent()->getTerminator(),
780 "Terminator found in the middle of a basic block!", I.getParent());
784 void Verifier::visitBranchInst(BranchInst &BI) {
785 if (BI.isConditional()) {
786 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
787 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
789 visitTerminatorInst(BI);
792 void Verifier::visitReturnInst(ReturnInst &RI) {
793 Function *F = RI.getParent()->getParent();
794 unsigned N = RI.getNumOperands();
795 if (F->getReturnType()->isVoidTy())
797 "Found return instr that returns non-void in Function of void "
798 "return type!", &RI, F->getReturnType());
800 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
801 "Function return type does not match operand "
802 "type of return inst!", &RI, F->getReturnType());
804 // Check to make sure that the return value has necessary properties for
806 visitTerminatorInst(RI);
809 void Verifier::visitSwitchInst(SwitchInst &SI) {
810 // Check to make sure that all of the constants in the switch instruction
811 // have the same type as the switched-on value.
812 Type *SwitchTy = SI.getCondition()->getType();
813 SmallPtrSet<ConstantInt*, 32> Constants;
814 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
815 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
816 "Switch constants must all be same type as switch value!", &SI);
817 Assert2(Constants.insert(SI.getCaseValue(i)),
818 "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
821 visitTerminatorInst(SI);
824 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
825 Assert1(BI.getAddress()->getType()->isPointerTy(),
826 "Indirectbr operand must have pointer type!", &BI);
827 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
828 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
829 "Indirectbr destinations must all have pointer type!", &BI);
831 visitTerminatorInst(BI);
834 void Verifier::visitSelectInst(SelectInst &SI) {
835 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
837 "Invalid operands for select instruction!", &SI);
839 Assert1(SI.getTrueValue()->getType() == SI.getType(),
840 "Select values must have same type as select instruction!", &SI);
841 visitInstruction(SI);
844 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
845 /// a pass, if any exist, it's an error.
847 void Verifier::visitUserOp1(Instruction &I) {
848 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
851 void Verifier::visitTruncInst(TruncInst &I) {
852 // Get the source and destination types
853 Type *SrcTy = I.getOperand(0)->getType();
854 Type *DestTy = I.getType();
856 // Get the size of the types in bits, we'll need this later
857 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
858 unsigned DestBitSize = DestTy->getScalarSizeInBits();
860 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
861 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
862 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
863 "trunc source and destination must both be a vector or neither", &I);
864 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
869 void Verifier::visitZExtInst(ZExtInst &I) {
870 // Get the source and destination types
871 Type *SrcTy = I.getOperand(0)->getType();
872 Type *DestTy = I.getType();
874 // Get the size of the types in bits, we'll need this later
875 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
876 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
877 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
878 "zext source and destination must both be a vector or neither", &I);
879 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
880 unsigned DestBitSize = DestTy->getScalarSizeInBits();
882 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
887 void Verifier::visitSExtInst(SExtInst &I) {
888 // Get the source and destination types
889 Type *SrcTy = I.getOperand(0)->getType();
890 Type *DestTy = I.getType();
892 // Get the size of the types in bits, we'll need this later
893 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
894 unsigned DestBitSize = DestTy->getScalarSizeInBits();
896 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
897 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
898 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
899 "sext source and destination must both be a vector or neither", &I);
900 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
905 void Verifier::visitFPTruncInst(FPTruncInst &I) {
906 // Get the source and destination types
907 Type *SrcTy = I.getOperand(0)->getType();
908 Type *DestTy = I.getType();
909 // Get the size of the types in bits, we'll need this later
910 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
911 unsigned DestBitSize = DestTy->getScalarSizeInBits();
913 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
914 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
915 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
916 "fptrunc source and destination must both be a vector or neither",&I);
917 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
922 void Verifier::visitFPExtInst(FPExtInst &I) {
923 // Get the source and destination types
924 Type *SrcTy = I.getOperand(0)->getType();
925 Type *DestTy = I.getType();
927 // Get the size of the types in bits, we'll need this later
928 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
929 unsigned DestBitSize = DestTy->getScalarSizeInBits();
931 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
932 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
933 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
934 "fpext source and destination must both be a vector or neither", &I);
935 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
940 void Verifier::visitUIToFPInst(UIToFPInst &I) {
941 // Get the source and destination types
942 Type *SrcTy = I.getOperand(0)->getType();
943 Type *DestTy = I.getType();
945 bool SrcVec = SrcTy->isVectorTy();
946 bool DstVec = DestTy->isVectorTy();
948 Assert1(SrcVec == DstVec,
949 "UIToFP source and dest must both be vector or scalar", &I);
950 Assert1(SrcTy->isIntOrIntVectorTy(),
951 "UIToFP source must be integer or integer vector", &I);
952 Assert1(DestTy->isFPOrFPVectorTy(),
953 "UIToFP result must be FP or FP vector", &I);
955 if (SrcVec && DstVec)
956 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
957 cast<VectorType>(DestTy)->getNumElements(),
958 "UIToFP source and dest vector length mismatch", &I);
963 void Verifier::visitSIToFPInst(SIToFPInst &I) {
964 // Get the source and destination types
965 Type *SrcTy = I.getOperand(0)->getType();
966 Type *DestTy = I.getType();
968 bool SrcVec = SrcTy->isVectorTy();
969 bool DstVec = DestTy->isVectorTy();
971 Assert1(SrcVec == DstVec,
972 "SIToFP source and dest must both be vector or scalar", &I);
973 Assert1(SrcTy->isIntOrIntVectorTy(),
974 "SIToFP source must be integer or integer vector", &I);
975 Assert1(DestTy->isFPOrFPVectorTy(),
976 "SIToFP result must be FP or FP vector", &I);
978 if (SrcVec && DstVec)
979 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
980 cast<VectorType>(DestTy)->getNumElements(),
981 "SIToFP source and dest vector length mismatch", &I);
986 void Verifier::visitFPToUIInst(FPToUIInst &I) {
987 // Get the source and destination types
988 Type *SrcTy = I.getOperand(0)->getType();
989 Type *DestTy = I.getType();
991 bool SrcVec = SrcTy->isVectorTy();
992 bool DstVec = DestTy->isVectorTy();
994 Assert1(SrcVec == DstVec,
995 "FPToUI source and dest must both be vector or scalar", &I);
996 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
998 Assert1(DestTy->isIntOrIntVectorTy(),
999 "FPToUI result must be integer or integer vector", &I);
1001 if (SrcVec && DstVec)
1002 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1003 cast<VectorType>(DestTy)->getNumElements(),
1004 "FPToUI source and dest vector length mismatch", &I);
1006 visitInstruction(I);
1009 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1010 // Get the source and destination types
1011 Type *SrcTy = I.getOperand(0)->getType();
1012 Type *DestTy = I.getType();
1014 bool SrcVec = SrcTy->isVectorTy();
1015 bool DstVec = DestTy->isVectorTy();
1017 Assert1(SrcVec == DstVec,
1018 "FPToSI source and dest must both be vector or scalar", &I);
1019 Assert1(SrcTy->isFPOrFPVectorTy(),
1020 "FPToSI source must be FP or FP vector", &I);
1021 Assert1(DestTy->isIntOrIntVectorTy(),
1022 "FPToSI result must be integer or integer vector", &I);
1024 if (SrcVec && DstVec)
1025 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1026 cast<VectorType>(DestTy)->getNumElements(),
1027 "FPToSI source and dest vector length mismatch", &I);
1029 visitInstruction(I);
1032 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1033 // Get the source and destination types
1034 Type *SrcTy = I.getOperand(0)->getType();
1035 Type *DestTy = I.getType();
1037 Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1038 Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1040 visitInstruction(I);
1043 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1044 // Get the source and destination types
1045 Type *SrcTy = I.getOperand(0)->getType();
1046 Type *DestTy = I.getType();
1048 Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1049 Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1051 visitInstruction(I);
1054 void Verifier::visitBitCastInst(BitCastInst &I) {
1055 // Get the source and destination types
1056 Type *SrcTy = I.getOperand(0)->getType();
1057 Type *DestTy = I.getType();
1059 // Get the size of the types in bits, we'll need this later
1060 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1061 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1063 // BitCast implies a no-op cast of type only. No bits change.
1064 // However, you can't cast pointers to anything but pointers.
1065 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1066 "Bitcast requires both operands to be pointer or neither", &I);
1067 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1069 // Disallow aggregates.
1070 Assert1(!SrcTy->isAggregateType(),
1071 "Bitcast operand must not be aggregate", &I);
1072 Assert1(!DestTy->isAggregateType(),
1073 "Bitcast type must not be aggregate", &I);
1075 visitInstruction(I);
1078 /// visitPHINode - Ensure that a PHI node is well formed.
1080 void Verifier::visitPHINode(PHINode &PN) {
1081 // Ensure that the PHI nodes are all grouped together at the top of the block.
1082 // This can be tested by checking whether the instruction before this is
1083 // either nonexistent (because this is begin()) or is a PHI node. If not,
1084 // then there is some other instruction before a PHI.
1085 Assert2(&PN == &PN.getParent()->front() ||
1086 isa<PHINode>(--BasicBlock::iterator(&PN)),
1087 "PHI nodes not grouped at top of basic block!",
1088 &PN, PN.getParent());
1090 // Check that all of the values of the PHI node have the same type as the
1091 // result, and that the incoming blocks are really basic blocks.
1092 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1093 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1094 "PHI node operands are not the same type as the result!", &PN);
1097 // All other PHI node constraints are checked in the visitBasicBlock method.
1099 visitInstruction(PN);
1102 void Verifier::VerifyCallSite(CallSite CS) {
1103 Instruction *I = CS.getInstruction();
1105 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1106 "Called function must be a pointer!", I);
1107 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1109 Assert1(FPTy->getElementType()->isFunctionTy(),
1110 "Called function is not pointer to function type!", I);
1111 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1113 // Verify that the correct number of arguments are being passed
1114 if (FTy->isVarArg())
1115 Assert1(CS.arg_size() >= FTy->getNumParams(),
1116 "Called function requires more parameters than were provided!",I);
1118 Assert1(CS.arg_size() == FTy->getNumParams(),
1119 "Incorrect number of arguments passed to called function!", I);
1121 // Verify that all arguments to the call match the function type.
1122 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1123 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1124 "Call parameter type does not match function signature!",
1125 CS.getArgument(i), FTy->getParamType(i), I);
1127 const AttrListPtr &Attrs = CS.getAttributes();
1129 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1130 "Attributes after last parameter!", I);
1132 // Verify call attributes.
1133 VerifyFunctionAttrs(FTy, Attrs, I);
1135 if (FTy->isVarArg())
1136 // Check attributes on the varargs part.
1137 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1138 Attributes Attr = Attrs.getParamAttributes(Idx);
1140 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1142 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1143 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1144 " cannot be used for vararg call arguments!", I);
1147 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1148 if (CS.getCalledFunction() == 0 ||
1149 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1150 for (FunctionType::param_iterator PI = FTy->param_begin(),
1151 PE = FTy->param_end(); PI != PE; ++PI)
1152 Assert1(!(*PI)->isMetadataTy(),
1153 "Function has metadata parameter but isn't an intrinsic", I);
1156 visitInstruction(*I);
1159 void Verifier::visitCallInst(CallInst &CI) {
1160 VerifyCallSite(&CI);
1162 if (Function *F = CI.getCalledFunction())
1163 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1164 visitIntrinsicFunctionCall(ID, CI);
1167 void Verifier::visitInvokeInst(InvokeInst &II) {
1168 VerifyCallSite(&II);
1169 visitTerminatorInst(II);
1172 /// visitBinaryOperator - Check that both arguments to the binary operator are
1173 /// of the same type!
1175 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1176 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1177 "Both operands to a binary operator are not of the same type!", &B);
1179 switch (B.getOpcode()) {
1180 // Check that integer arithmetic operators are only used with
1181 // integral operands.
1182 case Instruction::Add:
1183 case Instruction::Sub:
1184 case Instruction::Mul:
1185 case Instruction::SDiv:
1186 case Instruction::UDiv:
1187 case Instruction::SRem:
1188 case Instruction::URem:
1189 Assert1(B.getType()->isIntOrIntVectorTy(),
1190 "Integer arithmetic operators only work with integral types!", &B);
1191 Assert1(B.getType() == B.getOperand(0)->getType(),
1192 "Integer arithmetic operators must have same type "
1193 "for operands and result!", &B);
1195 // Check that floating-point arithmetic operators are only used with
1196 // floating-point operands.
1197 case Instruction::FAdd:
1198 case Instruction::FSub:
1199 case Instruction::FMul:
1200 case Instruction::FDiv:
1201 case Instruction::FRem:
1202 Assert1(B.getType()->isFPOrFPVectorTy(),
1203 "Floating-point arithmetic operators only work with "
1204 "floating-point types!", &B);
1205 Assert1(B.getType() == B.getOperand(0)->getType(),
1206 "Floating-point arithmetic operators must have same type "
1207 "for operands and result!", &B);
1209 // Check that logical operators are only used with integral operands.
1210 case Instruction::And:
1211 case Instruction::Or:
1212 case Instruction::Xor:
1213 Assert1(B.getType()->isIntOrIntVectorTy(),
1214 "Logical operators only work with integral types!", &B);
1215 Assert1(B.getType() == B.getOperand(0)->getType(),
1216 "Logical operators must have same type for operands and result!",
1219 case Instruction::Shl:
1220 case Instruction::LShr:
1221 case Instruction::AShr:
1222 Assert1(B.getType()->isIntOrIntVectorTy(),
1223 "Shifts only work with integral types!", &B);
1224 Assert1(B.getType() == B.getOperand(0)->getType(),
1225 "Shift return type must be same as operands!", &B);
1228 llvm_unreachable("Unknown BinaryOperator opcode!");
1231 visitInstruction(B);
1234 void Verifier::visitICmpInst(ICmpInst &IC) {
1235 // Check that the operands are the same type
1236 Type *Op0Ty = IC.getOperand(0)->getType();
1237 Type *Op1Ty = IC.getOperand(1)->getType();
1238 Assert1(Op0Ty == Op1Ty,
1239 "Both operands to ICmp instruction are not of the same type!", &IC);
1240 // Check that the operands are the right type
1241 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1242 "Invalid operand types for ICmp instruction", &IC);
1243 // Check that the predicate is valid.
1244 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1245 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1246 "Invalid predicate in ICmp instruction!", &IC);
1248 visitInstruction(IC);
1251 void Verifier::visitFCmpInst(FCmpInst &FC) {
1252 // Check that the operands are the same type
1253 Type *Op0Ty = FC.getOperand(0)->getType();
1254 Type *Op1Ty = FC.getOperand(1)->getType();
1255 Assert1(Op0Ty == Op1Ty,
1256 "Both operands to FCmp instruction are not of the same type!", &FC);
1257 // Check that the operands are the right type
1258 Assert1(Op0Ty->isFPOrFPVectorTy(),
1259 "Invalid operand types for FCmp instruction", &FC);
1260 // Check that the predicate is valid.
1261 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1262 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1263 "Invalid predicate in FCmp instruction!", &FC);
1265 visitInstruction(FC);
1268 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1269 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1271 "Invalid extractelement operands!", &EI);
1272 visitInstruction(EI);
1275 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1276 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1279 "Invalid insertelement operands!", &IE);
1280 visitInstruction(IE);
1283 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1284 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1286 "Invalid shufflevector operands!", &SV);
1287 visitInstruction(SV);
1290 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1291 Assert1(cast<PointerType>(GEP.getOperand(0)->getType())
1292 ->getElementType()->isSized(),
1293 "GEP into unsized type!", &GEP);
1295 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1297 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(), Idxs);
1298 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1299 Assert2(GEP.getType()->isPointerTy() &&
1300 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1301 "GEP is not of right type for indices!", &GEP, ElTy);
1302 visitInstruction(GEP);
1305 void Verifier::visitLoadInst(LoadInst &LI) {
1306 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1307 Assert1(PTy, "Load operand must be a pointer.", &LI);
1308 Type *ElTy = PTy->getElementType();
1309 Assert2(ElTy == LI.getType(),
1310 "Load result type does not match pointer operand type!", &LI, ElTy);
1311 visitInstruction(LI);
1314 void Verifier::visitStoreInst(StoreInst &SI) {
1315 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1316 Assert1(PTy, "Store operand must be a pointer.", &SI);
1317 Type *ElTy = PTy->getElementType();
1318 Assert2(ElTy == SI.getOperand(0)->getType(),
1319 "Stored value type does not match pointer operand type!",
1321 visitInstruction(SI);
1324 void Verifier::visitAllocaInst(AllocaInst &AI) {
1325 PointerType *PTy = AI.getType();
1326 Assert1(PTy->getAddressSpace() == 0,
1327 "Allocation instruction pointer not in the generic address space!",
1329 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1331 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1332 "Alloca array size must have integer type", &AI);
1333 visitInstruction(AI);
1336 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1337 Assert1(CXI.getOrdering() != NotAtomic,
1338 "cmpxchg instructions must be atomic.", &CXI);
1339 Assert1(CXI.getOrdering() != Unordered,
1340 "cmpxchg instructions cannot be unordered.", &CXI);
1341 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1342 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1343 Type *ElTy = PTy->getElementType();
1344 Assert2(ElTy == CXI.getOperand(1)->getType(),
1345 "Expected value type does not match pointer operand type!",
1347 Assert2(ElTy == CXI.getOperand(2)->getType(),
1348 "Stored value type does not match pointer operand type!",
1350 visitInstruction(CXI);
1353 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1354 Assert1(RMWI.getOrdering() != NotAtomic,
1355 "atomicrmw instructions must be atomic.", &RMWI);
1356 Assert1(RMWI.getOrdering() != Unordered,
1357 "atomicrmw instructions cannot be unordered.", &RMWI);
1358 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1359 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1360 Type *ElTy = PTy->getElementType();
1361 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1362 "Argument value type does not match pointer operand type!",
1364 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1365 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1366 "Invalid binary operation!", &RMWI);
1367 visitInstruction(RMWI);
1370 void Verifier::visitFenceInst(FenceInst &FI) {
1371 const AtomicOrdering Ordering = FI.getOrdering();
1372 Assert1(Ordering == Acquire || Ordering == Release ||
1373 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1374 "fence instructions may only have "
1375 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1376 visitInstruction(FI);
1379 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1380 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1381 EVI.getIndices()) ==
1383 "Invalid ExtractValueInst operands!", &EVI);
1385 visitInstruction(EVI);
1388 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1389 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1390 IVI.getIndices()) ==
1391 IVI.getOperand(1)->getType(),
1392 "Invalid InsertValueInst operands!", &IVI);
1394 visitInstruction(IVI);
1397 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1398 BasicBlock *BB = LPI.getParent();
1400 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1402 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1403 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1405 // The landingpad instruction defines its parent as a landing pad block. The
1406 // landing pad block may be branched to only by the unwind edge of an invoke.
1407 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1408 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1409 Assert1(II && II->getUnwindDest() == BB,
1410 "Block containing LandingPadInst must be jumped to "
1411 "only by the unwind edge of an invoke.", &LPI);
1414 // The landingpad instruction must be the first non-PHI instruction in the
1416 BasicBlock::iterator I = BB->begin(), E = BB->end();
1417 while (I != E && isa<PHINode>(I))
1419 Assert1(I != E && isa<LandingPadInst>(I) && I == LPI,
1420 "LandingPadInst not the first non-PHI instruction in the block.",
1423 // The personality functions for all landingpad instructions within the same
1424 // function should match.
1426 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1427 "Personality function doesn't match others in function", &LPI);
1428 PersonalityFn = LPI.getPersonalityFn();
1430 visitInstruction(LPI);
1433 /// verifyInstruction - Verify that an instruction is well formed.
1435 void Verifier::visitInstruction(Instruction &I) {
1436 BasicBlock *BB = I.getParent();
1437 Assert1(BB, "Instruction not embedded in basic block!", &I);
1439 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1440 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1442 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1443 "Only PHI nodes may reference their own value!", &I);
1446 // Check that void typed values don't have names
1447 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1448 "Instruction has a name, but provides a void value!", &I);
1450 // Check that the return value of the instruction is either void or a legal
1452 Assert1(I.getType()->isVoidTy() ||
1453 I.getType()->isFirstClassType(),
1454 "Instruction returns a non-scalar type!", &I);
1456 // Check that the instruction doesn't produce metadata. Calls are already
1457 // checked against the callee type.
1458 Assert1(!I.getType()->isMetadataTy() ||
1459 isa<CallInst>(I) || isa<InvokeInst>(I),
1460 "Invalid use of metadata!", &I);
1462 // Check that all uses of the instruction, if they are instructions
1463 // themselves, actually have parent basic blocks. If the use is not an
1464 // instruction, it is an error!
1465 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1467 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1468 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1469 " embedded in a basic block!", &I, Used);
1471 CheckFailed("Use of instruction is not an instruction!", *UI);
1476 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1477 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1479 // Check to make sure that only first-class-values are operands to
1481 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1482 Assert1(0, "Instruction operands must be first-class values!", &I);
1485 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1486 // Check to make sure that the "address of" an intrinsic function is never
1488 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1489 "Cannot take the address of an intrinsic!", &I);
1490 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1492 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1493 Assert1(OpBB->getParent() == BB->getParent(),
1494 "Referring to a basic block in another function!", &I);
1495 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1496 Assert1(OpArg->getParent() == BB->getParent(),
1497 "Referring to an argument in another function!", &I);
1498 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1499 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1501 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1502 BasicBlock *OpBlock = Op->getParent();
1504 // Check that a definition dominates all of its uses.
1505 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1506 // Invoke results are only usable in the normal destination, not in the
1507 // exceptional destination.
1508 BasicBlock *NormalDest = II->getNormalDest();
1510 Assert2(NormalDest != II->getUnwindDest(),
1511 "No uses of invoke possible due to dominance structure!",
1514 // PHI nodes differ from other nodes because they actually "use" the
1515 // value in the predecessor basic blocks they correspond to.
1516 BasicBlock *UseBlock = BB;
1517 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1518 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1519 UseBlock = PN->getIncomingBlock(j);
1521 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1524 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1525 // Special case of a phi node in the normal destination or the unwind
1527 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1528 "Invoke result not available in the unwind destination!",
1531 Assert2(DT->dominates(NormalDest, UseBlock) ||
1532 !DT->isReachableFromEntry(UseBlock),
1533 "Invoke result does not dominate all uses!", Op, &I);
1535 // If the normal successor of an invoke instruction has multiple
1536 // predecessors, then the normal edge from the invoke is critical,
1537 // so the invoke value can only be live if the destination block
1538 // dominates all of it's predecessors (other than the invoke).
1539 if (!NormalDest->getSinglePredecessor() &&
1540 DT->isReachableFromEntry(UseBlock))
1541 // If it is used by something non-phi, then the other case is that
1542 // 'NormalDest' dominates all of its predecessors other than the
1543 // invoke. In this case, the invoke value can still be used.
1544 for (pred_iterator PI = pred_begin(NormalDest),
1545 E = pred_end(NormalDest); PI != E; ++PI)
1546 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1547 DT->isReachableFromEntry(*PI)) {
1548 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1552 } else if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1553 // PHI nodes are more difficult than other nodes because they actually
1554 // "use" the value in the predecessor basic blocks they correspond to.
1555 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1556 BasicBlock *PredBB = PN->getIncomingBlock(j);
1557 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1558 !DT->isReachableFromEntry(PredBB)),
1559 "Instruction does not dominate all uses!", Op, &I);
1561 if (OpBlock == BB) {
1562 // If they are in the same basic block, make sure that the definition
1563 // comes before the use.
1564 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1565 "Instruction does not dominate all uses!", Op, &I);
1568 // Definition must dominate use unless use is unreachable!
1569 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1570 !DT->isReachableFromEntry(BB),
1571 "Instruction does not dominate all uses!", Op, &I);
1573 } else if (isa<InlineAsm>(I.getOperand(i))) {
1574 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1575 (i + 3 == e && isa<InvokeInst>(I)),
1576 "Cannot take the address of an inline asm!", &I);
1579 InstsInThisBlock.insert(&I);
1582 // Flags used by TableGen to mark intrinsic parameters with the
1583 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1584 static const unsigned ExtendedElementVectorType = 0x40000000;
1585 static const unsigned TruncatedElementVectorType = 0x20000000;
1587 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1589 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1590 Function *IF = CI.getCalledFunction();
1591 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1594 #define GET_INTRINSIC_VERIFIER
1595 #include "llvm/Intrinsics.gen"
1596 #undef GET_INTRINSIC_VERIFIER
1598 // If the intrinsic takes MDNode arguments, verify that they are either global
1599 // or are local to *this* function.
1600 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1601 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1602 visitMDNode(*MD, CI.getParent()->getParent());
1607 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1608 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1609 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1610 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1611 Assert1(MD->getNumOperands() == 1,
1612 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1614 case Intrinsic::memcpy:
1615 case Intrinsic::memmove:
1616 case Intrinsic::memset:
1617 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1618 "alignment argument of memory intrinsics must be a constant int",
1620 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1621 "isvolatile argument of memory intrinsics must be a constant int",
1624 case Intrinsic::gcroot:
1625 case Intrinsic::gcwrite:
1626 case Intrinsic::gcread:
1627 if (ID == Intrinsic::gcroot) {
1629 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1630 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1631 Assert1(isa<Constant>(CI.getArgOperand(1)),
1632 "llvm.gcroot parameter #2 must be a constant.", &CI);
1633 if (!AI->getType()->getElementType()->isPointerTy()) {
1634 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1635 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1636 "or argument #2 must be a non-null constant.", &CI);
1640 Assert1(CI.getParent()->getParent()->hasGC(),
1641 "Enclosing function does not use GC.", &CI);
1643 case Intrinsic::init_trampoline:
1644 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1645 "llvm.init_trampoline parameter #2 must resolve to a function.",
1648 case Intrinsic::prefetch:
1649 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1650 isa<ConstantInt>(CI.getArgOperand(2)) &&
1651 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1652 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1653 "invalid arguments to llvm.prefetch",
1656 case Intrinsic::stackprotector:
1657 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1658 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1661 case Intrinsic::lifetime_start:
1662 case Intrinsic::lifetime_end:
1663 case Intrinsic::invariant_start:
1664 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1665 "size argument of memory use markers must be a constant integer",
1668 case Intrinsic::invariant_end:
1669 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1670 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1675 /// Produce a string to identify an intrinsic parameter or return value.
1676 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1677 /// parameters beginning with NumRets.
1679 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1680 if (ArgNo >= NumRets)
1681 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1683 return "Intrinsic result type";
1684 return "Intrinsic result type #" + utostr(ArgNo);
1687 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
1688 int VT, unsigned ArgNo, std::string &Suffix) {
1689 FunctionType *FTy = F->getFunctionType();
1691 unsigned NumElts = 0;
1693 VectorType *VTy = dyn_cast<VectorType>(Ty);
1695 EltTy = VTy->getElementType();
1696 NumElts = VTy->getNumElements();
1699 Type *RetTy = FTy->getReturnType();
1700 StructType *ST = dyn_cast<StructType>(RetTy);
1701 unsigned NumRetVals;
1702 if (RetTy->isVoidTy())
1705 NumRetVals = ST->getNumElements();
1712 // Check flags that indicate a type that is an integral vector type with
1713 // elements that are larger or smaller than the elements of the matched
1715 if ((Match & (ExtendedElementVectorType |
1716 TruncatedElementVectorType)) != 0) {
1717 IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1718 if (!VTy || !IEltTy) {
1719 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1720 "an integral vector type.", F);
1723 // Adjust the current Ty (in the opposite direction) rather than
1724 // the type being matched against.
1725 if ((Match & ExtendedElementVectorType) != 0) {
1726 if ((IEltTy->getBitWidth() & 1) != 0) {
1727 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1728 "element bit-width is odd.", F);
1731 Ty = VectorType::getTruncatedElementVectorType(VTy);
1733 Ty = VectorType::getExtendedElementVectorType(VTy);
1734 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1737 if (Match <= static_cast<int>(NumRetVals - 1)) {
1739 RetTy = ST->getElementType(Match);
1742 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1743 "match return type.", F);
1747 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1748 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1749 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1753 } else if (VT == MVT::iAny) {
1754 if (!EltTy->isIntegerTy()) {
1755 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1756 "an integer type.", F);
1760 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1764 Suffix += "v" + utostr(NumElts);
1766 Suffix += "i" + utostr(GotBits);
1768 // Check some constraints on various intrinsics.
1770 default: break; // Not everything needs to be checked.
1771 case Intrinsic::bswap:
1772 if (GotBits < 16 || GotBits % 16 != 0) {
1773 CheckFailed("Intrinsic requires even byte width argument", F);
1778 } else if (VT == MVT::fAny) {
1779 if (!EltTy->isFloatingPointTy()) {
1780 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1781 "a floating-point type.", F);
1788 Suffix += "v" + utostr(NumElts);
1790 Suffix += EVT::getEVT(EltTy).getEVTString();
1791 } else if (VT == MVT::vAny) {
1793 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1797 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1798 } else if (VT == MVT::iPTR) {
1799 if (!Ty->isPointerTy()) {
1800 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1801 "pointer and a pointer is required.", F);
1804 } else if (VT == MVT::iPTRAny) {
1805 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1806 // and iPTR. In the verifier, we can not distinguish which case we have so
1807 // allow either case to be legal.
1808 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1809 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1810 if (PointeeVT == MVT::Other) {
1811 CheckFailed("Intrinsic has pointer to complex type.");
1814 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1815 PointeeVT.getEVTString();
1817 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1818 "pointer and a pointer is required.", F);
1821 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1822 EVT VVT = EVT((MVT::SimpleValueType)VT);
1824 // If this is a vector argument, verify the number and type of elements.
1825 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1826 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1830 if (VVT.getVectorNumElements() != NumElts) {
1831 CheckFailed("Intrinsic prototype has incorrect number of "
1832 "vector elements!", F);
1835 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1837 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1839 } else if (EltTy != Ty) {
1840 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1841 "and a scalar is required.", F);
1848 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1849 /// Intrinsics.gen. This implements a little state machine that verifies the
1850 /// prototype of intrinsics.
1851 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1852 unsigned NumRetVals,
1853 unsigned NumParams, ...) {
1855 va_start(VA, NumParams);
1856 FunctionType *FTy = F->getFunctionType();
1858 // For overloaded intrinsics, the Suffix of the function name must match the
1859 // types of the arguments. This variable keeps track of the expected
1860 // suffix, to be checked at the end.
1863 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1864 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1868 Type *Ty = FTy->getReturnType();
1869 StructType *ST = dyn_cast<StructType>(Ty);
1871 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1872 CheckFailed("Intrinsic should return void", F);
1876 // Verify the return types.
1877 if (ST && ST->getNumElements() != NumRetVals) {
1878 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1882 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1883 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1885 if (ST) Ty = ST->getElementType(ArgNo);
1886 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1890 // Verify the parameter types.
1891 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1892 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1894 if (VT == MVT::isVoid && ArgNo > 0) {
1895 if (!FTy->isVarArg())
1896 CheckFailed("Intrinsic prototype has no '...'!", F);
1900 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1901 ArgNo + NumRetVals, Suffix))
1907 // For intrinsics without pointer arguments, if we computed a Suffix then the
1908 // intrinsic is overloaded and we need to make sure that the name of the
1909 // function is correct. We add the suffix to the name of the intrinsic and
1910 // compare against the given function name. If they are not the same, the
1911 // function name is invalid. This ensures that overloading of intrinsics
1912 // uses a sane and consistent naming convention. Note that intrinsics with
1913 // pointer argument may or may not be overloaded so we will check assuming it
1914 // has a suffix and not.
1915 if (!Suffix.empty()) {
1916 std::string Name(Intrinsic::getName(ID));
1917 if (Name + Suffix != F->getName()) {
1918 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1919 F->getName().substr(Name.length()) + "'. It should be '" +
1924 // Check parameter attributes.
1925 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1926 "Intrinsic has wrong parameter attributes!", F);
1930 //===----------------------------------------------------------------------===//
1931 // Implement the public interfaces to this file...
1932 //===----------------------------------------------------------------------===//
1934 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1935 return new Verifier(action);
1939 /// verifyFunction - Check a function for errors, printing messages on stderr.
1940 /// Return true if the function is corrupt.
1942 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1943 Function &F = const_cast<Function&>(f);
1944 assert(!F.isDeclaration() && "Cannot verify external functions");
1946 FunctionPassManager FPM(F.getParent());
1947 Verifier *V = new Verifier(action);
1953 /// verifyModule - Check a module for errors, printing messages on stderr.
1954 /// Return true if the module is corrupt.
1956 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1957 std::string *ErrorInfo) {
1959 Verifier *V = new Verifier(action);
1961 PM.run(const_cast<Module&>(M));
1963 if (ErrorInfo && V->Broken)
1964 *ErrorInfo = V->MessagesStr.str();