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/ModuleProvider.h"
51 #include "llvm/Pass.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/Analysis/Dominators.h"
54 #include "llvm/Assembly/Writer.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/Support/CallSite.h"
57 #include "llvm/Support/CFG.h"
58 #include "llvm/Support/InstVisitor.h"
59 #include "llvm/Support/Streams.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/Compiler.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
71 namespace { // Anonymous namespace for class
72 struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
73 static char ID; // Pass ID, replacement for typeid
75 PreVerifier() : FunctionPass(&ID) { }
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
81 // Check that the prerequisites for successful DominatorTree construction
83 bool runOnFunction(Function &F) {
86 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
87 if (I->empty() || !I->back().isTerminator()) {
88 cerr << "Basic Block does not have terminator!\n";
89 WriteAsOperand(*cerr, I, true);
96 llvm_report_error("Broken module, no Basic Block terminator!");
103 char PreVerifier::ID = 0;
104 static RegisterPass<PreVerifier>
105 PreVer("preverify", "Preliminary module verification");
106 static const PassInfo *const PreVerifyID = &PreVer;
109 struct VISIBILITY_HIDDEN
110 Verifier : public FunctionPass, InstVisitor<Verifier> {
111 static char ID; // Pass ID, replacement for typeid
112 bool Broken; // Is this module found to be broken?
113 bool RealPass; // Are we not being run by a PassManager?
114 VerifierFailureAction action;
115 // What to do if verification fails.
116 Module *Mod; // Module we are verifying right now
117 DominatorTree *DT; // Dominator Tree, caution can be null!
119 std::string Messages;
120 raw_string_ostream MessagesStr;
122 /// InstInThisBlock - when verifying a basic block, keep track of all of the
123 /// instructions we have seen so far. This allows us to do efficient
124 /// dominance checks for the case when an instruction has an operand that is
125 /// an instruction in the same block.
126 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
130 Broken(false), RealPass(true), action(AbortProcessAction),
131 DT(0), MessagesStr(Messages) {}
132 explicit Verifier(VerifierFailureAction ctn)
134 Broken(false), RealPass(true), action(ctn), DT(0),
135 MessagesStr(Messages) {}
136 explicit Verifier(bool AB)
138 Broken(false), RealPass(true),
139 action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
140 MessagesStr(Messages) {}
141 explicit Verifier(DominatorTree &dt)
143 Broken(false), RealPass(false), action(PrintMessageAction),
144 DT(&dt), MessagesStr(Messages) {}
147 bool doInitialization(Module &M) {
149 verifyTypeSymbolTable(M.getTypeSymbolTable());
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>();
166 InstsInThisBlock.clear();
168 // If this is a real pass, in a pass manager, we must abort before
169 // returning back to the pass manager, or else the pass manager may try to
170 // run other passes on the broken module.
172 return abortIfBroken();
177 bool doFinalization(Module &M) {
178 // Scan through, checking all of the external function's linkage now...
179 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
180 visitGlobalValue(*I);
182 // Check to make sure function prototypes are okay.
183 if (I->isDeclaration()) visitFunction(*I);
186 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
188 visitGlobalVariable(*I);
190 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
192 visitGlobalAlias(*I);
194 // If the module is broken, abort at this time.
195 return abortIfBroken();
198 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
199 AU.setPreservesAll();
200 AU.addRequiredID(PreVerifyID);
202 AU.addRequired<DominatorTree>();
205 /// abortIfBroken - If the module is broken and we are supposed to abort on
206 /// this condition, do so.
208 bool abortIfBroken() {
209 if (!Broken) return false;
210 MessagesStr << "Broken module found, ";
212 default: llvm_unreachable("Unknown action");
213 case AbortProcessAction:
214 MessagesStr << "compilation aborted!\n";
215 errs() << MessagesStr.str();
216 // Client should choose different reaction if abort is not desired
218 case PrintMessageAction:
219 MessagesStr << "verification continues.\n";
220 errs() << MessagesStr.str();
222 case ReturnStatusAction:
223 MessagesStr << "compilation terminated.\n";
229 // Verification methods...
230 void verifyTypeSymbolTable(TypeSymbolTable &ST);
231 void visitGlobalValue(GlobalValue &GV);
232 void visitGlobalVariable(GlobalVariable &GV);
233 void visitGlobalAlias(GlobalAlias &GA);
234 void visitFunction(Function &F);
235 void visitBasicBlock(BasicBlock &BB);
236 using InstVisitor<Verifier>::visit;
238 void visit(Instruction &I);
240 void visitTruncInst(TruncInst &I);
241 void visitZExtInst(ZExtInst &I);
242 void visitSExtInst(SExtInst &I);
243 void visitFPTruncInst(FPTruncInst &I);
244 void visitFPExtInst(FPExtInst &I);
245 void visitFPToUIInst(FPToUIInst &I);
246 void visitFPToSIInst(FPToSIInst &I);
247 void visitUIToFPInst(UIToFPInst &I);
248 void visitSIToFPInst(SIToFPInst &I);
249 void visitIntToPtrInst(IntToPtrInst &I);
250 void visitPtrToIntInst(PtrToIntInst &I);
251 void visitBitCastInst(BitCastInst &I);
252 void visitPHINode(PHINode &PN);
253 void visitBinaryOperator(BinaryOperator &B);
254 void visitICmpInst(ICmpInst &IC);
255 void visitFCmpInst(FCmpInst &FC);
256 void visitExtractElementInst(ExtractElementInst &EI);
257 void visitInsertElementInst(InsertElementInst &EI);
258 void visitShuffleVectorInst(ShuffleVectorInst &EI);
259 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
260 void visitCallInst(CallInst &CI);
261 void visitInvokeInst(InvokeInst &II);
262 void visitGetElementPtrInst(GetElementPtrInst &GEP);
263 void visitLoadInst(LoadInst &LI);
264 void visitStoreInst(StoreInst &SI);
265 void visitInstruction(Instruction &I);
266 void visitTerminatorInst(TerminatorInst &I);
267 void visitReturnInst(ReturnInst &RI);
268 void visitSwitchInst(SwitchInst &SI);
269 void visitSelectInst(SelectInst &SI);
270 void visitUserOp1(Instruction &I);
271 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
272 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
273 void visitAllocationInst(AllocationInst &AI);
274 void visitExtractValueInst(ExtractValueInst &EVI);
275 void visitInsertValueInst(InsertValueInst &IVI);
277 void VerifyCallSite(CallSite CS);
278 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
279 int VT, unsigned ArgNo, std::string &Suffix);
280 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
281 unsigned RetNum, unsigned ParamNum, ...);
282 void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
283 bool isReturnValue, const Value *V);
284 void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
287 void WriteValue(const Value *V) {
289 if (isa<Instruction>(V)) {
292 WriteAsOperand(MessagesStr, V, true, Mod);
297 void WriteType(const Type *T) {
300 WriteTypeSymbolic(MessagesStr, T, Mod);
304 // CheckFailed - A check failed, so print out the condition and the message
305 // that failed. This provides a nice place to put a breakpoint if you want
306 // to see why something is not correct.
307 void CheckFailed(const Twine &Message,
308 const Value *V1 = 0, const Value *V2 = 0,
309 const Value *V3 = 0, const Value *V4 = 0) {
310 MessagesStr << Message.str() << "\n";
318 void CheckFailed(const Twine &Message, const Value* V1,
319 const Type* T2, const Value* V3 = 0) {
320 MessagesStr << Message.str() << "\n";
327 } // End anonymous namespace
329 char Verifier::ID = 0;
330 static RegisterPass<Verifier> X("verify", "Module Verifier");
332 // Assert - We know that cond should be true, if not print an error message.
333 #define Assert(C, M) \
334 do { if (!(C)) { CheckFailed(M); return; } } while (0)
335 #define Assert1(C, M, V1) \
336 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
337 #define Assert2(C, M, V1, V2) \
338 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
339 #define Assert3(C, M, V1, V2, V3) \
340 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
341 #define Assert4(C, M, V1, V2, V3, V4) \
342 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
344 void Verifier::visit(Instruction &I) {
345 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
346 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
347 InstVisitor<Verifier>::visit(I);
351 void Verifier::visitGlobalValue(GlobalValue &GV) {
352 Assert1(!GV.isDeclaration() ||
353 GV.hasExternalLinkage() ||
354 GV.hasDLLImportLinkage() ||
355 GV.hasExternalWeakLinkage() ||
356 GV.hasGhostLinkage() ||
357 (isa<GlobalAlias>(GV) &&
358 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
359 "Global is external, but doesn't have external or dllimport or weak linkage!",
362 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
363 "Global is marked as dllimport, but not external", &GV);
365 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
366 "Only global variables can have appending linkage!", &GV);
368 if (GV.hasAppendingLinkage()) {
369 GlobalVariable &GVar = cast<GlobalVariable>(GV);
370 Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
371 "Only global arrays can have appending linkage!", &GV);
375 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
376 if (GV.hasInitializer()) {
377 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
378 "Global variable initializer type does not match global "
379 "variable type!", &GV);
381 // If the global has common linkage, it must have a zero initializer and
382 // cannot be constant.
383 if (GV.hasCommonLinkage()) {
384 Assert1(GV.getInitializer()->isNullValue(),
385 "'common' global must have a zero initializer!", &GV);
386 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
390 // Verify that any metadata used in a global initializer points only to
392 if (MDNode *FirstNode = dyn_cast<MDNode>(GV.getInitializer())) {
393 SmallVector<const MDNode *, 4> NodesToAnalyze;
394 NodesToAnalyze.push_back(FirstNode);
395 while (!NodesToAnalyze.empty()) {
396 const MDNode *N = NodesToAnalyze.back();
397 NodesToAnalyze.pop_back();
399 for (MDNode::const_elem_iterator I = N->elem_begin(),
400 E = N->elem_end(); I != E; ++I)
401 if (const Value *V = *I) {
402 if (const MDNode *Next = dyn_cast<MDNode>(V))
403 NodesToAnalyze.push_back(Next);
405 Assert3(isa<Constant>(V),
406 "reference to instruction from global metadata node",
412 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
413 GV.hasExternalWeakLinkage(),
414 "invalid linkage type for global declaration", &GV);
417 visitGlobalValue(GV);
420 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
421 Assert1(!GA.getName().empty(),
422 "Alias name cannot be empty!", &GA);
423 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
425 "Alias should have external or external weak linkage!", &GA);
426 Assert1(GA.getAliasee(),
427 "Aliasee cannot be NULL!", &GA);
428 Assert1(GA.getType() == GA.getAliasee()->getType(),
429 "Alias and aliasee types should match!", &GA);
431 if (!isa<GlobalValue>(GA.getAliasee())) {
432 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
434 (CE->getOpcode() == Instruction::BitCast ||
435 CE->getOpcode() == Instruction::GetElementPtr) &&
436 isa<GlobalValue>(CE->getOperand(0)),
437 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
441 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
443 "Aliasing chain should end with function or global variable", &GA);
445 visitGlobalValue(GA);
448 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
451 // VerifyParameterAttrs - Check the given attributes for an argument or return
452 // value of the specified type. The value V is printed in error messages.
453 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
454 bool isReturnValue, const Value *V) {
455 if (Attrs == Attribute::None)
458 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
459 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
460 " only applies to the function!", V);
463 Attributes RetI = Attrs & Attribute::ParameterOnly;
464 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
465 " does not apply to return values!", V);
469 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
470 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
471 Assert1(!(MutI & (MutI - 1)), "Attributes " +
472 Attribute::getAsString(MutI) + " are incompatible!", V);
475 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
476 Assert1(!TypeI, "Wrong type for attribute " +
477 Attribute::getAsString(TypeI), V);
479 Attributes ByValI = Attrs & Attribute::ByVal;
480 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
481 Assert1(!ByValI || PTy->getElementType()->isSized(),
482 "Attribute " + Attribute::getAsString(ByValI) +
483 " does not support unsized types!", V);
486 "Attribute " + Attribute::getAsString(ByValI) +
487 " only applies to parameters with pointer type!", V);
491 // VerifyFunctionAttrs - Check parameter attributes against a function type.
492 // The value V is printed in error messages.
493 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
494 const AttrListPtr &Attrs,
499 bool SawNest = false;
501 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
502 const AttributeWithIndex &Attr = Attrs.getSlot(i);
506 Ty = FT->getReturnType();
507 else if (Attr.Index-1 < FT->getNumParams())
508 Ty = FT->getParamType(Attr.Index-1);
510 break; // VarArgs attributes, verified elsewhere.
512 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
514 if (Attr.Attrs & Attribute::Nest) {
515 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
519 if (Attr.Attrs & Attribute::StructRet)
520 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
523 Attributes FAttrs = Attrs.getFnAttributes();
524 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
525 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
526 " does not apply to the function!", V);
529 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
530 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
531 Assert1(!(MutI & (MutI - 1)), "Attributes " +
532 Attribute::getAsString(MutI) + " are incompatible!", V);
536 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
540 unsigned LastSlot = Attrs.getNumSlots() - 1;
541 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
542 if (LastIndex <= Params
543 || (LastIndex == (unsigned)~0
544 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
549 // visitFunction - Verify that a function is ok.
551 void Verifier::visitFunction(Function &F) {
552 // Check function arguments.
553 const FunctionType *FT = F.getFunctionType();
554 unsigned NumArgs = F.arg_size();
556 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
557 Assert2(FT->getNumParams() == NumArgs,
558 "# formal arguments must match # of arguments for function type!",
560 Assert1(F.getReturnType()->isFirstClassType() ||
561 F.getReturnType() == Type::getVoidTy(F.getContext()) ||
562 isa<StructType>(F.getReturnType()),
563 "Functions cannot return aggregate values!", &F);
565 Assert1(!F.hasStructRetAttr() ||
566 F.getReturnType() == Type::getVoidTy(F.getContext()),
567 "Invalid struct return type!", &F);
569 const AttrListPtr &Attrs = F.getAttributes();
571 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
572 "Attributes after last parameter!", &F);
574 // Check function attributes.
575 VerifyFunctionAttrs(FT, Attrs, &F);
577 // Check that this function meets the restrictions on this calling convention.
578 switch (F.getCallingConv()) {
583 case CallingConv::Fast:
584 case CallingConv::Cold:
585 case CallingConv::X86_FastCall:
586 Assert1(!F.isVarArg(),
587 "Varargs functions must have C calling conventions!", &F);
591 bool isLLVMdotName = F.getName().size() >= 5 &&
592 F.getName().substr(0, 5) == "llvm.";
594 Assert1(F.getReturnType() != Type::getMetadataTy(F.getContext()),
595 "Function may not return metadata unless it's an intrinsic", &F);
597 // Check that the argument values match the function type for this function...
599 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
601 Assert2(I->getType() == FT->getParamType(i),
602 "Argument value does not match function argument type!",
603 I, FT->getParamType(i));
604 Assert1(I->getType()->isFirstClassType(),
605 "Function arguments must have first-class types!", I);
607 Assert2(I->getType() != Type::getMetadataTy(F.getContext()),
608 "Function takes metadata but isn't an intrinsic", I, &F);
611 if (F.isDeclaration()) {
612 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
613 F.hasExternalWeakLinkage() || F.hasGhostLinkage(),
614 "invalid linkage type for function declaration", &F);
616 // Verify that this function (which has a body) is not named "llvm.*". It
617 // is not legal to define intrinsics.
618 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
620 // Check the entry node
621 BasicBlock *Entry = &F.getEntryBlock();
622 Assert1(pred_begin(Entry) == pred_end(Entry),
623 "Entry block to function must not have predecessors!", Entry);
628 // verifyBasicBlock - Verify that a basic block is well formed...
630 void Verifier::visitBasicBlock(BasicBlock &BB) {
631 InstsInThisBlock.clear();
633 // Ensure that basic blocks have terminators!
634 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
636 // Check constraints that this basic block imposes on all of the PHI nodes in
638 if (isa<PHINode>(BB.front())) {
639 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
640 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
641 std::sort(Preds.begin(), Preds.end());
643 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
645 // Ensure that PHI nodes have at least one entry!
646 Assert1(PN->getNumIncomingValues() != 0,
647 "PHI nodes must have at least one entry. If the block is dead, "
648 "the PHI should be removed!", PN);
649 Assert1(PN->getNumIncomingValues() == Preds.size(),
650 "PHINode should have one entry for each predecessor of its "
651 "parent basic block!", PN);
653 // Get and sort all incoming values in the PHI node...
655 Values.reserve(PN->getNumIncomingValues());
656 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
657 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
658 PN->getIncomingValue(i)));
659 std::sort(Values.begin(), Values.end());
661 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
662 // Check to make sure that if there is more than one entry for a
663 // particular basic block in this PHI node, that the incoming values are
666 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
667 Values[i].second == Values[i-1].second,
668 "PHI node has multiple entries for the same basic block with "
669 "different incoming values!", PN, Values[i].first,
670 Values[i].second, Values[i-1].second);
672 // Check to make sure that the predecessors and PHI node entries are
674 Assert3(Values[i].first == Preds[i],
675 "PHI node entries do not match predecessors!", PN,
676 Values[i].first, Preds[i]);
682 void Verifier::visitTerminatorInst(TerminatorInst &I) {
683 // Ensure that terminators only exist at the end of the basic block.
684 Assert1(&I == I.getParent()->getTerminator(),
685 "Terminator found in the middle of a basic block!", I.getParent());
689 void Verifier::visitReturnInst(ReturnInst &RI) {
690 Function *F = RI.getParent()->getParent();
691 unsigned N = RI.getNumOperands();
692 if (F->getReturnType() == Type::getVoidTy(RI.getContext()))
694 "Found return instr that returns non-void in Function of void "
695 "return type!", &RI, F->getReturnType());
696 else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
697 // Exactly one return value and it matches the return type. Good.
698 } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
699 // The return type is a struct; check for multiple return values.
700 Assert2(STy->getNumElements() == N,
701 "Incorrect number of return values in ret instruction!",
702 &RI, F->getReturnType());
703 for (unsigned i = 0; i != N; ++i)
704 Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
705 "Function return type does not match operand "
706 "type of return inst!", &RI, F->getReturnType());
707 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
708 // The return type is an array; check for multiple return values.
709 Assert2(ATy->getNumElements() == N,
710 "Incorrect number of return values in ret instruction!",
711 &RI, F->getReturnType());
712 for (unsigned i = 0; i != N; ++i)
713 Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
714 "Function return type does not match operand "
715 "type of return inst!", &RI, F->getReturnType());
717 CheckFailed("Function return type does not match operand "
718 "type of return inst!", &RI, F->getReturnType());
721 // Check to make sure that the return value has necessary properties for
723 visitTerminatorInst(RI);
726 void Verifier::visitSwitchInst(SwitchInst &SI) {
727 // Check to make sure that all of the constants in the switch instruction
728 // have the same type as the switched-on value.
729 const Type *SwitchTy = SI.getCondition()->getType();
730 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
731 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
732 "Switch constants must all be same type as switch value!", &SI);
734 visitTerminatorInst(SI);
737 void Verifier::visitSelectInst(SelectInst &SI) {
738 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
740 "Invalid operands for select instruction!", &SI);
742 Assert1(SI.getTrueValue()->getType() == SI.getType(),
743 "Select values must have same type as select instruction!", &SI);
744 visitInstruction(SI);
748 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
749 /// a pass, if any exist, it's an error.
751 void Verifier::visitUserOp1(Instruction &I) {
752 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
755 void Verifier::visitTruncInst(TruncInst &I) {
756 // Get the source and destination types
757 const Type *SrcTy = I.getOperand(0)->getType();
758 const Type *DestTy = I.getType();
760 // Get the size of the types in bits, we'll need this later
761 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
762 unsigned DestBitSize = DestTy->getScalarSizeInBits();
764 Assert1(SrcTy->isIntOrIntVector(), "Trunc only operates on integer", &I);
765 Assert1(DestTy->isIntOrIntVector(), "Trunc only produces integer", &I);
766 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
767 "trunc source and destination must both be a vector or neither", &I);
768 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
773 void Verifier::visitZExtInst(ZExtInst &I) {
774 // Get the source and destination types
775 const Type *SrcTy = I.getOperand(0)->getType();
776 const Type *DestTy = I.getType();
778 // Get the size of the types in bits, we'll need this later
779 Assert1(SrcTy->isIntOrIntVector(), "ZExt only operates on integer", &I);
780 Assert1(DestTy->isIntOrIntVector(), "ZExt only produces an integer", &I);
781 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
782 "zext source and destination must both be a vector or neither", &I);
783 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
784 unsigned DestBitSize = DestTy->getScalarSizeInBits();
786 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
791 void Verifier::visitSExtInst(SExtInst &I) {
792 // Get the source and destination types
793 const Type *SrcTy = I.getOperand(0)->getType();
794 const Type *DestTy = I.getType();
796 // Get the size of the types in bits, we'll need this later
797 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
798 unsigned DestBitSize = DestTy->getScalarSizeInBits();
800 Assert1(SrcTy->isIntOrIntVector(), "SExt only operates on integer", &I);
801 Assert1(DestTy->isIntOrIntVector(), "SExt only produces an integer", &I);
802 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
803 "sext source and destination must both be a vector or neither", &I);
804 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
809 void Verifier::visitFPTruncInst(FPTruncInst &I) {
810 // Get the source and destination types
811 const Type *SrcTy = I.getOperand(0)->getType();
812 const Type *DestTy = I.getType();
813 // Get the size of the types in bits, we'll need this later
814 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
815 unsigned DestBitSize = DestTy->getScalarSizeInBits();
817 Assert1(SrcTy->isFPOrFPVector(),"FPTrunc only operates on FP", &I);
818 Assert1(DestTy->isFPOrFPVector(),"FPTrunc only produces an FP", &I);
819 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
820 "fptrunc source and destination must both be a vector or neither",&I);
821 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
826 void Verifier::visitFPExtInst(FPExtInst &I) {
827 // Get the source and destination types
828 const Type *SrcTy = I.getOperand(0)->getType();
829 const Type *DestTy = I.getType();
831 // Get the size of the types in bits, we'll need this later
832 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
833 unsigned DestBitSize = DestTy->getScalarSizeInBits();
835 Assert1(SrcTy->isFPOrFPVector(),"FPExt only operates on FP", &I);
836 Assert1(DestTy->isFPOrFPVector(),"FPExt only produces an FP", &I);
837 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
838 "fpext source and destination must both be a vector or neither", &I);
839 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
844 void Verifier::visitUIToFPInst(UIToFPInst &I) {
845 // Get the source and destination types
846 const Type *SrcTy = I.getOperand(0)->getType();
847 const Type *DestTy = I.getType();
849 bool SrcVec = isa<VectorType>(SrcTy);
850 bool DstVec = isa<VectorType>(DestTy);
852 Assert1(SrcVec == DstVec,
853 "UIToFP source and dest must both be vector or scalar", &I);
854 Assert1(SrcTy->isIntOrIntVector(),
855 "UIToFP source must be integer or integer vector", &I);
856 Assert1(DestTy->isFPOrFPVector(),
857 "UIToFP result must be FP or FP vector", &I);
859 if (SrcVec && DstVec)
860 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
861 cast<VectorType>(DestTy)->getNumElements(),
862 "UIToFP source and dest vector length mismatch", &I);
867 void Verifier::visitSIToFPInst(SIToFPInst &I) {
868 // Get the source and destination types
869 const Type *SrcTy = I.getOperand(0)->getType();
870 const Type *DestTy = I.getType();
872 bool SrcVec = SrcTy->getTypeID() == Type::VectorTyID;
873 bool DstVec = DestTy->getTypeID() == Type::VectorTyID;
875 Assert1(SrcVec == DstVec,
876 "SIToFP source and dest must both be vector or scalar", &I);
877 Assert1(SrcTy->isIntOrIntVector(),
878 "SIToFP source must be integer or integer vector", &I);
879 Assert1(DestTy->isFPOrFPVector(),
880 "SIToFP result must be FP or FP vector", &I);
882 if (SrcVec && DstVec)
883 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
884 cast<VectorType>(DestTy)->getNumElements(),
885 "SIToFP source and dest vector length mismatch", &I);
890 void Verifier::visitFPToUIInst(FPToUIInst &I) {
891 // Get the source and destination types
892 const Type *SrcTy = I.getOperand(0)->getType();
893 const Type *DestTy = I.getType();
895 bool SrcVec = isa<VectorType>(SrcTy);
896 bool DstVec = isa<VectorType>(DestTy);
898 Assert1(SrcVec == DstVec,
899 "FPToUI source and dest must both be vector or scalar", &I);
900 Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
901 Assert1(DestTy->isIntOrIntVector(),
902 "FPToUI result must be integer or integer vector", &I);
904 if (SrcVec && DstVec)
905 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
906 cast<VectorType>(DestTy)->getNumElements(),
907 "FPToUI source and dest vector length mismatch", &I);
912 void Verifier::visitFPToSIInst(FPToSIInst &I) {
913 // Get the source and destination types
914 const Type *SrcTy = I.getOperand(0)->getType();
915 const Type *DestTy = I.getType();
917 bool SrcVec = isa<VectorType>(SrcTy);
918 bool DstVec = isa<VectorType>(DestTy);
920 Assert1(SrcVec == DstVec,
921 "FPToSI source and dest must both be vector or scalar", &I);
922 Assert1(SrcTy->isFPOrFPVector(),
923 "FPToSI source must be FP or FP vector", &I);
924 Assert1(DestTy->isIntOrIntVector(),
925 "FPToSI result must be integer or integer vector", &I);
927 if (SrcVec && DstVec)
928 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
929 cast<VectorType>(DestTy)->getNumElements(),
930 "FPToSI source and dest vector length mismatch", &I);
935 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
936 // Get the source and destination types
937 const Type *SrcTy = I.getOperand(0)->getType();
938 const Type *DestTy = I.getType();
940 Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
941 Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
946 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
947 // Get the source and destination types
948 const Type *SrcTy = I.getOperand(0)->getType();
949 const Type *DestTy = I.getType();
951 Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
952 Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
957 void Verifier::visitBitCastInst(BitCastInst &I) {
958 // Get the source and destination types
959 const Type *SrcTy = I.getOperand(0)->getType();
960 const Type *DestTy = I.getType();
962 // Get the size of the types in bits, we'll need this later
963 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
964 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
966 // BitCast implies a no-op cast of type only. No bits change.
967 // However, you can't cast pointers to anything but pointers.
968 Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
969 "Bitcast requires both operands to be pointer or neither", &I);
970 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
972 // Disallow aggregates.
973 Assert1(!SrcTy->isAggregateType(),
974 "Bitcast operand must not be aggregate", &I);
975 Assert1(!DestTy->isAggregateType(),
976 "Bitcast type must not be aggregate", &I);
981 /// visitPHINode - Ensure that a PHI node is well formed.
983 void Verifier::visitPHINode(PHINode &PN) {
984 // Ensure that the PHI nodes are all grouped together at the top of the block.
985 // This can be tested by checking whether the instruction before this is
986 // either nonexistent (because this is begin()) or is a PHI node. If not,
987 // then there is some other instruction before a PHI.
988 Assert2(&PN == &PN.getParent()->front() ||
989 isa<PHINode>(--BasicBlock::iterator(&PN)),
990 "PHI nodes not grouped at top of basic block!",
991 &PN, PN.getParent());
993 // Check that all of the operands of the PHI node have the same type as the
995 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
996 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
997 "PHI node operands are not the same type as the result!", &PN);
999 // All other PHI node constraints are checked in the visitBasicBlock method.
1001 visitInstruction(PN);
1004 void Verifier::VerifyCallSite(CallSite CS) {
1005 Instruction *I = CS.getInstruction();
1007 Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
1008 "Called function must be a pointer!", I);
1009 const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1010 Assert1(isa<FunctionType>(FPTy->getElementType()),
1011 "Called function is not pointer to function type!", I);
1013 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1015 // Verify that the correct number of arguments are being passed
1016 if (FTy->isVarArg())
1017 Assert1(CS.arg_size() >= FTy->getNumParams(),
1018 "Called function requires more parameters than were provided!",I);
1020 Assert1(CS.arg_size() == FTy->getNumParams(),
1021 "Incorrect number of arguments passed to called function!", I);
1023 // Verify that all arguments to the call match the function type...
1024 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1025 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1026 "Call parameter type does not match function signature!",
1027 CS.getArgument(i), FTy->getParamType(i), I);
1029 const AttrListPtr &Attrs = CS.getAttributes();
1031 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1032 "Attributes after last parameter!", I);
1034 // Verify call attributes.
1035 VerifyFunctionAttrs(FTy, Attrs, I);
1037 if (FTy->isVarArg())
1038 // Check attributes on the varargs part.
1039 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1040 Attributes Attr = Attrs.getParamAttributes(Idx);
1042 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1044 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1045 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1046 " cannot be used for vararg call arguments!", I);
1049 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1050 if (!CS.getCalledFunction() || CS.getCalledFunction()->getName().size() < 5 ||
1051 CS.getCalledFunction()->getName().substr(0, 5) != "llvm.") {
1052 Assert1(FTy->getReturnType() != Type::getMetadataTy(I->getContext()),
1053 "Only intrinsics may return metadata", I);
1054 for (FunctionType::param_iterator PI = FTy->param_begin(),
1055 PE = FTy->param_end(); PI != PE; ++PI)
1056 Assert1(PI->get() != Type::getMetadataTy(I->getContext()),
1057 "Function has metadata parameter but isn't an intrinsic", I);
1060 visitInstruction(*I);
1063 void Verifier::visitCallInst(CallInst &CI) {
1064 VerifyCallSite(&CI);
1066 if (Function *F = CI.getCalledFunction())
1067 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1068 visitIntrinsicFunctionCall(ID, CI);
1071 void Verifier::visitInvokeInst(InvokeInst &II) {
1072 VerifyCallSite(&II);
1075 /// visitBinaryOperator - Check that both arguments to the binary operator are
1076 /// of the same type!
1078 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1079 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1080 "Both operands to a binary operator are not of the same type!", &B);
1082 switch (B.getOpcode()) {
1083 // Check that integer arithmetic operators are only used with
1084 // integral operands.
1085 case Instruction::Add:
1086 case Instruction::Sub:
1087 case Instruction::Mul:
1088 case Instruction::SDiv:
1089 case Instruction::UDiv:
1090 case Instruction::SRem:
1091 case Instruction::URem:
1092 Assert1(B.getType()->isIntOrIntVector(),
1093 "Integer arithmetic operators only work with integral types!", &B);
1094 Assert1(B.getType() == B.getOperand(0)->getType(),
1095 "Integer arithmetic operators must have same type "
1096 "for operands and result!", &B);
1098 // Check that floating-point arithmetic operators are only used with
1099 // floating-point operands.
1100 case Instruction::FAdd:
1101 case Instruction::FSub:
1102 case Instruction::FMul:
1103 case Instruction::FDiv:
1104 case Instruction::FRem:
1105 Assert1(B.getType()->isFPOrFPVector(),
1106 "Floating-point arithmetic operators only work with "
1107 "floating-point types!", &B);
1108 Assert1(B.getType() == B.getOperand(0)->getType(),
1109 "Floating-point arithmetic operators must have same type "
1110 "for operands and result!", &B);
1112 // Check that logical operators are only used with integral operands.
1113 case Instruction::And:
1114 case Instruction::Or:
1115 case Instruction::Xor:
1116 Assert1(B.getType()->isIntOrIntVector(),
1117 "Logical operators only work with integral types!", &B);
1118 Assert1(B.getType() == B.getOperand(0)->getType(),
1119 "Logical operators must have same type for operands and result!",
1122 case Instruction::Shl:
1123 case Instruction::LShr:
1124 case Instruction::AShr:
1125 Assert1(B.getType()->isIntOrIntVector(),
1126 "Shifts only work with integral types!", &B);
1127 Assert1(B.getType() == B.getOperand(0)->getType(),
1128 "Shift return type must be same as operands!", &B);
1131 llvm_unreachable("Unknown BinaryOperator opcode!");
1134 visitInstruction(B);
1137 void Verifier::visitICmpInst(ICmpInst& IC) {
1138 // Check that the operands are the same type
1139 const Type* Op0Ty = IC.getOperand(0)->getType();
1140 const Type* Op1Ty = IC.getOperand(1)->getType();
1141 Assert1(Op0Ty == Op1Ty,
1142 "Both operands to ICmp instruction are not of the same type!", &IC);
1143 // Check that the operands are the right type
1144 Assert1(Op0Ty->isIntOrIntVector() || isa<PointerType>(Op0Ty),
1145 "Invalid operand types for ICmp instruction", &IC);
1147 visitInstruction(IC);
1150 void Verifier::visitFCmpInst(FCmpInst& FC) {
1151 // Check that the operands are the same type
1152 const Type* Op0Ty = FC.getOperand(0)->getType();
1153 const Type* Op1Ty = FC.getOperand(1)->getType();
1154 Assert1(Op0Ty == Op1Ty,
1155 "Both operands to FCmp instruction are not of the same type!", &FC);
1156 // Check that the operands are the right type
1157 Assert1(Op0Ty->isFPOrFPVector(),
1158 "Invalid operand types for FCmp instruction", &FC);
1159 visitInstruction(FC);
1162 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1163 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1165 "Invalid extractelement operands!", &EI);
1166 visitInstruction(EI);
1169 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1170 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1173 "Invalid insertelement operands!", &IE);
1174 visitInstruction(IE);
1177 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1178 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1180 "Invalid shufflevector operands!", &SV);
1182 const VectorType *VTy = dyn_cast<VectorType>(SV.getOperand(0)->getType());
1183 Assert1(VTy, "Operands are not a vector type", &SV);
1185 // Check to see if Mask is valid.
1186 if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1187 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1188 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1189 Assert1(!CI->uge(VTy->getNumElements()*2),
1190 "Invalid shufflevector shuffle mask!", &SV);
1192 Assert1(isa<UndefValue>(MV->getOperand(i)),
1193 "Invalid shufflevector shuffle mask!", &SV);
1197 Assert1(isa<UndefValue>(SV.getOperand(2)) ||
1198 isa<ConstantAggregateZero>(SV.getOperand(2)),
1199 "Invalid shufflevector shuffle mask!", &SV);
1202 visitInstruction(SV);
1205 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1206 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1208 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1209 Idxs.begin(), Idxs.end());
1210 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1211 Assert2(isa<PointerType>(GEP.getType()) &&
1212 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1213 "GEP is not of right type for indices!", &GEP, ElTy);
1214 visitInstruction(GEP);
1217 void Verifier::visitLoadInst(LoadInst &LI) {
1219 cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
1220 Assert2(ElTy == LI.getType(),
1221 "Load result type does not match pointer operand type!", &LI, ElTy);
1222 Assert1(ElTy != Type::getMetadataTy(LI.getContext()),
1223 "Can't load metadata!", &LI);
1224 visitInstruction(LI);
1227 void Verifier::visitStoreInst(StoreInst &SI) {
1229 cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
1230 Assert2(ElTy == SI.getOperand(0)->getType(),
1231 "Stored value type does not match pointer operand type!", &SI, ElTy);
1232 Assert1(ElTy != Type::getMetadataTy(SI.getContext()),
1233 "Can't store metadata!", &SI);
1234 visitInstruction(SI);
1237 void Verifier::visitAllocationInst(AllocationInst &AI) {
1238 const PointerType *PTy = AI.getType();
1239 Assert1(PTy->getAddressSpace() == 0,
1240 "Allocation instruction pointer not in the generic address space!",
1242 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1244 visitInstruction(AI);
1247 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1248 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1249 EVI.idx_begin(), EVI.idx_end()) ==
1251 "Invalid ExtractValueInst operands!", &EVI);
1253 visitInstruction(EVI);
1256 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1257 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1258 IVI.idx_begin(), IVI.idx_end()) ==
1259 IVI.getOperand(1)->getType(),
1260 "Invalid InsertValueInst operands!", &IVI);
1262 visitInstruction(IVI);
1265 /// verifyInstruction - Verify that an instruction is well formed.
1267 void Verifier::visitInstruction(Instruction &I) {
1268 BasicBlock *BB = I.getParent();
1269 Assert1(BB, "Instruction not embedded in basic block!", &I);
1271 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1272 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1274 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1275 "Only PHI nodes may reference their own value!", &I);
1278 // Verify that if this is a terminator that it is at the end of the block.
1279 if (isa<TerminatorInst>(I))
1280 Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1283 // Check that void typed values don't have names
1284 Assert1(I.getType() != Type::getVoidTy(I.getContext()) || !I.hasName(),
1285 "Instruction has a name, but provides a void value!", &I);
1287 // Check that the return value of the instruction is either void or a legal
1289 Assert1(I.getType() == Type::getVoidTy(I.getContext()) ||
1290 I.getType()->isFirstClassType()
1291 || ((isa<CallInst>(I) || isa<InvokeInst>(I))
1292 && isa<StructType>(I.getType())),
1293 "Instruction returns a non-scalar type!", &I);
1295 // Check that the instruction doesn't produce metadata or metadata*. Calls
1296 // all already checked against the callee type.
1297 Assert1(I.getType() != Type::getMetadataTy(I.getContext()) ||
1298 isa<CallInst>(I) || isa<InvokeInst>(I),
1299 "Invalid use of metadata!", &I);
1301 if (const PointerType *PTy = dyn_cast<PointerType>(I.getType()))
1302 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1303 "Instructions may not produce pointer to metadata.", &I);
1306 // Check that all uses of the instruction, if they are instructions
1307 // themselves, actually have parent basic blocks. If the use is not an
1308 // instruction, it is an error!
1309 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1311 Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
1313 Instruction *Used = cast<Instruction>(*UI);
1314 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1315 " embedded in a basic block!", &I, Used);
1318 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1319 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1321 // Check to make sure that only first-class-values are operands to
1323 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1324 Assert1(0, "Instruction operands must be first-class values!", &I);
1327 if (const PointerType *PTy =
1328 dyn_cast<PointerType>(I.getOperand(i)->getType()))
1329 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1330 "Invalid use of metadata pointer.", &I);
1332 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1333 // Check to make sure that the "address of" an intrinsic function is never
1335 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1336 "Cannot take the address of an intrinsic!", &I);
1337 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1339 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1340 Assert1(OpBB->getParent() == BB->getParent(),
1341 "Referring to a basic block in another function!", &I);
1342 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1343 Assert1(OpArg->getParent() == BB->getParent(),
1344 "Referring to an argument in another function!", &I);
1345 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1346 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1348 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1349 BasicBlock *OpBlock = Op->getParent();
1351 // Check that a definition dominates all of its uses.
1352 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1353 // Invoke results are only usable in the normal destination, not in the
1354 // exceptional destination.
1355 BasicBlock *NormalDest = II->getNormalDest();
1357 Assert2(NormalDest != II->getUnwindDest(),
1358 "No uses of invoke possible due to dominance structure!",
1361 // PHI nodes differ from other nodes because they actually "use" the
1362 // value in the predecessor basic blocks they correspond to.
1363 BasicBlock *UseBlock = BB;
1364 if (isa<PHINode>(I))
1365 UseBlock = cast<BasicBlock>(I.getOperand(i+1));
1367 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1368 // Special case of a phi node in the normal destination or the unwind
1370 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1371 "Invoke result not available in the unwind destination!",
1374 Assert2(DT->dominates(NormalDest, UseBlock) ||
1375 !DT->isReachableFromEntry(UseBlock),
1376 "Invoke result does not dominate all uses!", Op, &I);
1378 // If the normal successor of an invoke instruction has multiple
1379 // predecessors, then the normal edge from the invoke is critical,
1380 // so the invoke value can only be live if the destination block
1381 // dominates all of it's predecessors (other than the invoke).
1382 if (!NormalDest->getSinglePredecessor() &&
1383 DT->isReachableFromEntry(UseBlock))
1384 // If it is used by something non-phi, then the other case is that
1385 // 'NormalDest' dominates all of its predecessors other than the
1386 // invoke. In this case, the invoke value can still be used.
1387 for (pred_iterator PI = pred_begin(NormalDest),
1388 E = pred_end(NormalDest); PI != E; ++PI)
1389 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1390 DT->isReachableFromEntry(*PI)) {
1391 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1395 } else if (isa<PHINode>(I)) {
1396 // PHI nodes are more difficult than other nodes because they actually
1397 // "use" the value in the predecessor basic blocks they correspond to.
1398 BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
1399 Assert2(DT->dominates(OpBlock, PredBB) ||
1400 !DT->isReachableFromEntry(PredBB),
1401 "Instruction does not dominate all uses!", Op, &I);
1403 if (OpBlock == BB) {
1404 // If they are in the same basic block, make sure that the definition
1405 // comes before the use.
1406 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1407 "Instruction does not dominate all uses!", Op, &I);
1410 // Definition must dominate use unless use is unreachable!
1411 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1412 !DT->isReachableFromEntry(BB),
1413 "Instruction does not dominate all uses!", Op, &I);
1415 } else if (isa<InlineAsm>(I.getOperand(i))) {
1416 Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
1417 "Cannot take the address of an inline asm!", &I);
1420 InstsInThisBlock.insert(&I);
1423 // Flags used by TableGen to mark intrinsic parameters with the
1424 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1425 static const unsigned ExtendedElementVectorType = 0x40000000;
1426 static const unsigned TruncatedElementVectorType = 0x20000000;
1428 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1430 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1431 Function *IF = CI.getCalledFunction();
1432 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1435 #define GET_INTRINSIC_VERIFIER
1436 #include "llvm/Intrinsics.gen"
1437 #undef GET_INTRINSIC_VERIFIER
1442 case Intrinsic::dbg_declare: // llvm.dbg.declare
1443 if (Constant *C = dyn_cast<Constant>(CI.getOperand(1)))
1444 Assert1(C && !isa<ConstantPointerNull>(C),
1445 "invalid llvm.dbg.declare intrinsic call", &CI);
1447 case Intrinsic::memcpy:
1448 case Intrinsic::memmove:
1449 case Intrinsic::memset:
1450 Assert1(isa<ConstantInt>(CI.getOperand(4)),
1451 "alignment argument of memory intrinsics must be a constant int",
1454 case Intrinsic::gcroot:
1455 case Intrinsic::gcwrite:
1456 case Intrinsic::gcread:
1457 if (ID == Intrinsic::gcroot) {
1459 dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
1460 Assert1(AI && isa<PointerType>(AI->getType()->getElementType()),
1461 "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
1462 Assert1(isa<Constant>(CI.getOperand(2)),
1463 "llvm.gcroot parameter #2 must be a constant.", &CI);
1466 Assert1(CI.getParent()->getParent()->hasGC(),
1467 "Enclosing function does not use GC.", &CI);
1469 case Intrinsic::init_trampoline:
1470 Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1471 "llvm.init_trampoline parameter #2 must resolve to a function.",
1474 case Intrinsic::prefetch:
1475 Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
1476 isa<ConstantInt>(CI.getOperand(3)) &&
1477 cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
1478 cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
1479 "invalid arguments to llvm.prefetch",
1482 case Intrinsic::stackprotector:
1483 Assert1(isa<AllocaInst>(CI.getOperand(2)->stripPointerCasts()),
1484 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1490 /// Produce a string to identify an intrinsic parameter or return value.
1491 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1492 /// parameters beginning with NumRets.
1494 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1495 if (ArgNo < NumRets) {
1497 return "Intrinsic result type";
1499 return "Intrinsic result type #" + utostr(ArgNo);
1501 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1504 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1505 int VT, unsigned ArgNo, std::string &Suffix) {
1506 const FunctionType *FTy = F->getFunctionType();
1508 unsigned NumElts = 0;
1509 const Type *EltTy = Ty;
1510 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1512 EltTy = VTy->getElementType();
1513 NumElts = VTy->getNumElements();
1516 const Type *RetTy = FTy->getReturnType();
1517 const StructType *ST = dyn_cast<StructType>(RetTy);
1518 unsigned NumRets = 1;
1520 NumRets = ST->getNumElements();
1525 // Check flags that indicate a type that is an integral vector type with
1526 // elements that are larger or smaller than the elements of the matched
1528 if ((Match & (ExtendedElementVectorType |
1529 TruncatedElementVectorType)) != 0) {
1530 const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1531 if (!VTy || !IEltTy) {
1532 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1533 "an integral vector type.", F);
1536 // Adjust the current Ty (in the opposite direction) rather than
1537 // the type being matched against.
1538 if ((Match & ExtendedElementVectorType) != 0) {
1539 if ((IEltTy->getBitWidth() & 1) != 0) {
1540 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " vector "
1541 "element bit-width is odd.", F);
1544 Ty = VectorType::getTruncatedElementVectorType(VTy);
1546 Ty = VectorType::getExtendedElementVectorType(VTy);
1547 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1550 if (Match <= static_cast<int>(NumRets - 1)) {
1552 RetTy = ST->getElementType(Match);
1555 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1556 "match return type.", F);
1560 if (Ty != FTy->getParamType(Match - NumRets)) {
1561 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1562 "match parameter %" + utostr(Match - NumRets) + ".", F);
1566 } else if (VT == MVT::iAny) {
1567 if (!EltTy->isInteger()) {
1568 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1569 "an integer type.", F);
1573 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1577 Suffix += "v" + utostr(NumElts);
1579 Suffix += "i" + utostr(GotBits);
1581 // Check some constraints on various intrinsics.
1583 default: break; // Not everything needs to be checked.
1584 case Intrinsic::bswap:
1585 if (GotBits < 16 || GotBits % 16 != 0) {
1586 CheckFailed("Intrinsic requires even byte width argument", F);
1591 } else if (VT == MVT::fAny) {
1592 if (!EltTy->isFloatingPoint()) {
1593 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1594 "a floating-point type.", F);
1601 Suffix += "v" + utostr(NumElts);
1603 Suffix += EVT::getEVT(EltTy).getEVTString();
1604 } else if (VT == MVT::vAny) {
1606 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a vector type.", F);
1609 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1610 } else if (VT == MVT::iPTR) {
1611 if (!isa<PointerType>(Ty)) {
1612 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1613 "pointer and a pointer is required.", F);
1616 } else if (VT == MVT::iPTRAny) {
1617 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1618 // and iPTR. In the verifier, we can not distinguish which case we have so
1619 // allow either case to be legal.
1620 if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1621 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1622 EVT::getEVT(PTyp->getElementType()).getEVTString();
1624 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1625 "pointer and a pointer is required.", F);
1628 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1629 EVT VVT = EVT((MVT::SimpleValueType)VT);
1631 // If this is a vector argument, verify the number and type of elements.
1632 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1633 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1637 if (VVT.getVectorNumElements() != NumElts) {
1638 CheckFailed("Intrinsic prototype has incorrect number of "
1639 "vector elements!", F);
1642 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1644 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is wrong!", F);
1646 } else if (EltTy != Ty) {
1647 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is a vector "
1648 "and a scalar is required.", F);
1655 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1656 /// Intrinsics.gen. This implements a little state machine that verifies the
1657 /// prototype of intrinsics.
1658 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1660 unsigned ParamNum, ...) {
1662 va_start(VA, ParamNum);
1663 const FunctionType *FTy = F->getFunctionType();
1665 // For overloaded intrinsics, the Suffix of the function name must match the
1666 // types of the arguments. This variable keeps track of the expected
1667 // suffix, to be checked at the end.
1670 if (FTy->getNumParams() + FTy->isVarArg() != ParamNum) {
1671 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1675 const Type *Ty = FTy->getReturnType();
1676 const StructType *ST = dyn_cast<StructType>(Ty);
1678 // Verify the return types.
1679 if (ST && ST->getNumElements() != RetNum) {
1680 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1684 for (unsigned ArgNo = 0; ArgNo < RetNum; ++ArgNo) {
1685 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1687 if (ST) Ty = ST->getElementType(ArgNo);
1689 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1693 // Verify the parameter types.
1694 for (unsigned ArgNo = 0; ArgNo < ParamNum; ++ArgNo) {
1695 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1697 if (VT == MVT::isVoid && ArgNo > 0) {
1698 if (!FTy->isVarArg())
1699 CheckFailed("Intrinsic prototype has no '...'!", F);
1703 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT, ArgNo + RetNum,
1710 // For intrinsics without pointer arguments, if we computed a Suffix then the
1711 // intrinsic is overloaded and we need to make sure that the name of the
1712 // function is correct. We add the suffix to the name of the intrinsic and
1713 // compare against the given function name. If they are not the same, the
1714 // function name is invalid. This ensures that overloading of intrinsics
1715 // uses a sane and consistent naming convention. Note that intrinsics with
1716 // pointer argument may or may not be overloaded so we will check assuming it
1717 // has a suffix and not.
1718 if (!Suffix.empty()) {
1719 std::string Name(Intrinsic::getName(ID));
1720 if (Name + Suffix != F->getName()) {
1721 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1722 F->getName().substr(Name.length()) + "'. It should be '" +
1727 // Check parameter attributes.
1728 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1729 "Intrinsic has wrong parameter attributes!", F);
1733 //===----------------------------------------------------------------------===//
1734 // Implement the public interfaces to this file...
1735 //===----------------------------------------------------------------------===//
1737 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1738 return new Verifier(action);
1742 // verifyFunction - Create
1743 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1744 Function &F = const_cast<Function&>(f);
1745 assert(!F.isDeclaration() && "Cannot verify external functions");
1747 ExistingModuleProvider MP(F.getParent());
1748 FunctionPassManager FPM(&MP);
1749 Verifier *V = new Verifier(action);
1756 /// verifyModule - Check a module for errors, printing messages on stderr.
1757 /// Return true if the module is corrupt.
1759 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1760 std::string *ErrorInfo) {
1762 Verifier *V = new Verifier(action);
1764 PM.run(const_cast<Module&>(M));
1766 if (ErrorInfo && V->Broken)
1767 *ErrorInfo = V->MessagesStr.str();