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/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/Support/Compiler.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/raw_ostream.h"
70 namespace { // Anonymous namespace for class
71 struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
72 static char ID; // Pass ID, replacement for typeid
74 PreVerifier() : FunctionPass(&ID) { }
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80 // Check that the prerequisites for successful DominatorTree construction
82 bool runOnFunction(Function &F) {
85 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
86 if (I->empty() || !I->back().isTerminator()) {
87 errs() << "Basic Block does not have terminator!\n";
88 WriteAsOperand(errs(), I, true);
95 llvm_report_error("Broken module, no Basic Block terminator!");
102 char PreVerifier::ID = 0;
103 static RegisterPass<PreVerifier>
104 PreVer("preverify", "Preliminary module verification");
105 static const PassInfo *const PreVerifyID = &PreVer;
108 struct VISIBILITY_HIDDEN
109 Verifier : public FunctionPass, public InstVisitor<Verifier> {
110 static char ID; // Pass ID, replacement for typeid
111 bool Broken; // Is this module found to be broken?
112 bool RealPass; // Are we not being run by a PassManager?
113 VerifierFailureAction action;
114 // What to do if verification fails.
115 Module *Mod; // Module we are verifying right now
116 DominatorTree *DT; // Dominator Tree, caution can be null!
118 std::string Messages;
119 raw_string_ostream MessagesStr;
121 /// InstInThisBlock - when verifying a basic block, keep track of all of the
122 /// instructions we have seen so far. This allows us to do efficient
123 /// dominance checks for the case when an instruction has an operand that is
124 /// an instruction in the same block.
125 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
129 Broken(false), RealPass(true), action(AbortProcessAction),
130 DT(0), MessagesStr(Messages) {}
131 explicit Verifier(VerifierFailureAction ctn)
133 Broken(false), RealPass(true), action(ctn), DT(0),
134 MessagesStr(Messages) {}
135 explicit Verifier(bool AB)
137 Broken(false), RealPass(true),
138 action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
139 MessagesStr(Messages) {}
140 explicit Verifier(DominatorTree &dt)
142 Broken(false), RealPass(false), action(PrintMessageAction),
143 DT(&dt), MessagesStr(Messages) {}
146 bool doInitialization(Module &M) {
148 verifyTypeSymbolTable(M.getTypeSymbolTable());
150 // If this is a real pass, in a pass manager, we must abort before
151 // returning back to the pass manager, or else the pass manager may try to
152 // run other passes on the broken module.
154 return abortIfBroken();
158 bool runOnFunction(Function &F) {
159 // Get dominator information if we are being run by PassManager
160 if (RealPass) DT = &getAnalysis<DominatorTree>();
165 InstsInThisBlock.clear();
167 // If this is a real pass, in a pass manager, we must abort before
168 // returning back to the pass manager, or else the pass manager may try to
169 // run other passes on the broken module.
171 return abortIfBroken();
176 bool doFinalization(Module &M) {
177 // Scan through, checking all of the external function's linkage now...
178 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
179 visitGlobalValue(*I);
181 // Check to make sure function prototypes are okay.
182 if (I->isDeclaration()) visitFunction(*I);
185 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
187 visitGlobalVariable(*I);
189 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
191 visitGlobalAlias(*I);
193 // If the module is broken, abort at this time.
194 return abortIfBroken();
197 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198 AU.setPreservesAll();
199 AU.addRequiredID(PreVerifyID);
201 AU.addRequired<DominatorTree>();
204 /// abortIfBroken - If the module is broken and we are supposed to abort on
205 /// this condition, do so.
207 bool abortIfBroken() {
208 if (!Broken) return false;
209 MessagesStr << "Broken module found, ";
211 default: llvm_unreachable("Unknown action");
212 case AbortProcessAction:
213 MessagesStr << "compilation aborted!\n";
214 errs() << MessagesStr.str();
215 // Client should choose different reaction if abort is not desired
217 case PrintMessageAction:
218 MessagesStr << "verification continues.\n";
219 errs() << MessagesStr.str();
221 case ReturnStatusAction:
222 MessagesStr << "compilation terminated.\n";
228 // Verification methods...
229 void verifyTypeSymbolTable(TypeSymbolTable &ST);
230 void visitGlobalValue(GlobalValue &GV);
231 void visitGlobalVariable(GlobalVariable &GV);
232 void visitGlobalAlias(GlobalAlias &GA);
233 void visitFunction(Function &F);
234 void visitBasicBlock(BasicBlock &BB);
235 using InstVisitor<Verifier>::visit;
237 void visit(Instruction &I);
239 void visitTruncInst(TruncInst &I);
240 void visitZExtInst(ZExtInst &I);
241 void visitSExtInst(SExtInst &I);
242 void visitFPTruncInst(FPTruncInst &I);
243 void visitFPExtInst(FPExtInst &I);
244 void visitFPToUIInst(FPToUIInst &I);
245 void visitFPToSIInst(FPToSIInst &I);
246 void visitUIToFPInst(UIToFPInst &I);
247 void visitSIToFPInst(SIToFPInst &I);
248 void visitIntToPtrInst(IntToPtrInst &I);
249 void visitPtrToIntInst(PtrToIntInst &I);
250 void visitBitCastInst(BitCastInst &I);
251 void visitPHINode(PHINode &PN);
252 void visitBinaryOperator(BinaryOperator &B);
253 void visitICmpInst(ICmpInst &IC);
254 void visitFCmpInst(FCmpInst &FC);
255 void visitExtractElementInst(ExtractElementInst &EI);
256 void visitInsertElementInst(InsertElementInst &EI);
257 void visitShuffleVectorInst(ShuffleVectorInst &EI);
258 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
259 void visitCallInst(CallInst &CI);
260 void visitInvokeInst(InvokeInst &II);
261 void visitGetElementPtrInst(GetElementPtrInst &GEP);
262 void visitLoadInst(LoadInst &LI);
263 void visitStoreInst(StoreInst &SI);
264 void visitInstruction(Instruction &I);
265 void visitTerminatorInst(TerminatorInst &I);
266 void visitReturnInst(ReturnInst &RI);
267 void visitSwitchInst(SwitchInst &SI);
268 void visitSelectInst(SelectInst &SI);
269 void visitUserOp1(Instruction &I);
270 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
271 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
272 void visitAllocationInst(AllocationInst &AI);
273 void visitExtractValueInst(ExtractValueInst &EVI);
274 void visitInsertValueInst(InsertValueInst &IVI);
276 void VerifyCallSite(CallSite CS);
277 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
278 int VT, unsigned ArgNo, std::string &Suffix);
279 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
280 unsigned RetNum, unsigned ParamNum, ...);
281 void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
282 bool isReturnValue, const Value *V);
283 void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
286 void WriteValue(const Value *V) {
288 if (isa<Instruction>(V)) {
291 WriteAsOperand(MessagesStr, V, true, Mod);
296 void WriteType(const Type *T) {
299 WriteTypeSymbolic(MessagesStr, T, Mod);
303 // CheckFailed - A check failed, so print out the condition and the message
304 // that failed. This provides a nice place to put a breakpoint if you want
305 // to see why something is not correct.
306 void CheckFailed(const Twine &Message,
307 const Value *V1 = 0, const Value *V2 = 0,
308 const Value *V3 = 0, const Value *V4 = 0) {
309 MessagesStr << Message.str() << "\n";
317 void CheckFailed(const Twine &Message, const Value* V1,
318 const Type* T2, const Value* V3 = 0) {
319 MessagesStr << Message.str() << "\n";
326 } // End anonymous namespace
328 char Verifier::ID = 0;
329 static RegisterPass<Verifier> X("verify", "Module Verifier");
331 // Assert - We know that cond should be true, if not print an error message.
332 #define Assert(C, M) \
333 do { if (!(C)) { CheckFailed(M); return; } } while (0)
334 #define Assert1(C, M, V1) \
335 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
336 #define Assert2(C, M, V1, V2) \
337 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
338 #define Assert3(C, M, V1, V2, V3) \
339 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
340 #define Assert4(C, M, V1, V2, V3, V4) \
341 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
343 void Verifier::visit(Instruction &I) {
344 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
345 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
346 InstVisitor<Verifier>::visit(I);
350 void Verifier::visitGlobalValue(GlobalValue &GV) {
351 Assert1(!GV.isDeclaration() ||
352 GV.hasExternalLinkage() ||
353 GV.hasDLLImportLinkage() ||
354 GV.hasExternalWeakLinkage() ||
355 GV.hasGhostLinkage() ||
356 (isa<GlobalAlias>(GV) &&
357 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
358 "Global is external, but doesn't have external or dllimport or weak linkage!",
361 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
362 "Global is marked as dllimport, but not external", &GV);
364 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
365 "Only global variables can have appending linkage!", &GV);
367 if (GV.hasAppendingLinkage()) {
368 GlobalVariable &GVar = cast<GlobalVariable>(GV);
369 Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
370 "Only global arrays can have appending linkage!", &GV);
374 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
375 if (GV.hasInitializer()) {
376 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
377 "Global variable initializer type does not match global "
378 "variable type!", &GV);
380 // If the global has common linkage, it must have a zero initializer and
381 // cannot be constant.
382 if (GV.hasCommonLinkage()) {
383 Assert1(GV.getInitializer()->isNullValue(),
384 "'common' global must have a zero initializer!", &GV);
385 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
389 // Verify that any metadata used in a global initializer points only to
391 if (MDNode *FirstNode = dyn_cast<MDNode>(GV.getInitializer())) {
392 SmallVector<const MDNode *, 4> NodesToAnalyze;
393 NodesToAnalyze.push_back(FirstNode);
394 while (!NodesToAnalyze.empty()) {
395 const MDNode *N = NodesToAnalyze.back();
396 NodesToAnalyze.pop_back();
398 for (MDNode::const_elem_iterator I = N->elem_begin(),
399 E = N->elem_end(); I != E; ++I)
400 if (const Value *V = *I) {
401 if (const MDNode *Next = dyn_cast<MDNode>(V))
402 NodesToAnalyze.push_back(Next);
404 Assert3(isa<Constant>(V),
405 "reference to instruction from global metadata node",
411 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
412 GV.hasExternalWeakLinkage(),
413 "invalid linkage type for global declaration", &GV);
416 visitGlobalValue(GV);
419 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
420 Assert1(!GA.getName().empty(),
421 "Alias name cannot be empty!", &GA);
422 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
424 "Alias should have external or external weak linkage!", &GA);
425 Assert1(GA.getAliasee(),
426 "Aliasee cannot be NULL!", &GA);
427 Assert1(GA.getType() == GA.getAliasee()->getType(),
428 "Alias and aliasee types should match!", &GA);
430 if (!isa<GlobalValue>(GA.getAliasee())) {
431 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
433 (CE->getOpcode() == Instruction::BitCast ||
434 CE->getOpcode() == Instruction::GetElementPtr) &&
435 isa<GlobalValue>(CE->getOperand(0)),
436 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
440 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
442 "Aliasing chain should end with function or global variable", &GA);
444 visitGlobalValue(GA);
447 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
450 // VerifyParameterAttrs - Check the given attributes for an argument or return
451 // value of the specified type. The value V is printed in error messages.
452 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
453 bool isReturnValue, const Value *V) {
454 if (Attrs == Attribute::None)
457 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
458 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
459 " only applies to the function!", V);
462 Attributes RetI = Attrs & Attribute::ParameterOnly;
463 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
464 " does not apply to return values!", V);
468 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
469 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
470 Assert1(!(MutI & (MutI - 1)), "Attributes " +
471 Attribute::getAsString(MutI) + " are incompatible!", V);
474 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
475 Assert1(!TypeI, "Wrong type for attribute " +
476 Attribute::getAsString(TypeI), V);
478 Attributes ByValI = Attrs & Attribute::ByVal;
479 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
480 Assert1(!ByValI || PTy->getElementType()->isSized(),
481 "Attribute " + Attribute::getAsString(ByValI) +
482 " does not support unsized types!", V);
485 "Attribute " + Attribute::getAsString(ByValI) +
486 " only applies to parameters with pointer type!", V);
490 // VerifyFunctionAttrs - Check parameter attributes against a function type.
491 // The value V is printed in error messages.
492 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
493 const AttrListPtr &Attrs,
498 bool SawNest = false;
500 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
501 const AttributeWithIndex &Attr = Attrs.getSlot(i);
505 Ty = FT->getReturnType();
506 else if (Attr.Index-1 < FT->getNumParams())
507 Ty = FT->getParamType(Attr.Index-1);
509 break; // VarArgs attributes, verified elsewhere.
511 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
513 if (Attr.Attrs & Attribute::Nest) {
514 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
518 if (Attr.Attrs & Attribute::StructRet)
519 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
522 Attributes FAttrs = Attrs.getFnAttributes();
523 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
524 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
525 " does not apply to the function!", V);
528 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
529 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
530 Assert1(!(MutI & (MutI - 1)), "Attributes " +
531 Attribute::getAsString(MutI) + " are incompatible!", V);
535 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
539 unsigned LastSlot = Attrs.getNumSlots() - 1;
540 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
541 if (LastIndex <= Params
542 || (LastIndex == (unsigned)~0
543 && (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);
627 // verifyBasicBlock - Verify that a basic block is well formed...
629 void Verifier::visitBasicBlock(BasicBlock &BB) {
630 InstsInThisBlock.clear();
632 // Ensure that basic blocks have terminators!
633 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
635 // Check constraints that this basic block imposes on all of the PHI nodes in
637 if (isa<PHINode>(BB.front())) {
638 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
639 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
640 std::sort(Preds.begin(), Preds.end());
642 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
643 // Ensure that PHI nodes have at least one entry!
644 Assert1(PN->getNumIncomingValues() != 0,
645 "PHI nodes must have at least one entry. If the block is dead, "
646 "the PHI should be removed!", PN);
647 Assert1(PN->getNumIncomingValues() == Preds.size(),
648 "PHINode should have one entry for each predecessor of its "
649 "parent basic block!", PN);
651 // Get and sort all incoming values in the PHI node...
653 Values.reserve(PN->getNumIncomingValues());
654 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
655 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
656 PN->getIncomingValue(i)));
657 std::sort(Values.begin(), Values.end());
659 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
660 // Check to make sure that if there is more than one entry for a
661 // particular basic block in this PHI node, that the incoming values are
664 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
665 Values[i].second == Values[i-1].second,
666 "PHI node has multiple entries for the same basic block with "
667 "different incoming values!", PN, Values[i].first,
668 Values[i].second, Values[i-1].second);
670 // Check to make sure that the predecessors and PHI node entries are
672 Assert3(Values[i].first == Preds[i],
673 "PHI node entries do not match predecessors!", PN,
674 Values[i].first, Preds[i]);
680 void Verifier::visitTerminatorInst(TerminatorInst &I) {
681 // Ensure that terminators only exist at the end of the basic block.
682 Assert1(&I == I.getParent()->getTerminator(),
683 "Terminator found in the middle of a basic block!", I.getParent());
687 void Verifier::visitReturnInst(ReturnInst &RI) {
688 Function *F = RI.getParent()->getParent();
689 unsigned N = RI.getNumOperands();
690 if (F->getReturnType() == Type::getVoidTy(RI.getContext()))
692 "Found return instr that returns non-void in Function of void "
693 "return type!", &RI, F->getReturnType());
694 else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
695 // Exactly one return value and it matches the return type. Good.
696 } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
697 // The return type is a struct; check for multiple return values.
698 Assert2(STy->getNumElements() == N,
699 "Incorrect number of return values in ret instruction!",
700 &RI, F->getReturnType());
701 for (unsigned i = 0; i != N; ++i)
702 Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
703 "Function return type does not match operand "
704 "type of return inst!", &RI, F->getReturnType());
705 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
706 // The return type is an array; check for multiple return values.
707 Assert2(ATy->getNumElements() == N,
708 "Incorrect number of return values in ret instruction!",
709 &RI, F->getReturnType());
710 for (unsigned i = 0; i != N; ++i)
711 Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
712 "Function return type does not match operand "
713 "type of return inst!", &RI, F->getReturnType());
715 CheckFailed("Function return type does not match operand "
716 "type of return inst!", &RI, F->getReturnType());
719 // Check to make sure that the return value has necessary properties for
721 visitTerminatorInst(RI);
724 void Verifier::visitSwitchInst(SwitchInst &SI) {
725 // Check to make sure that all of the constants in the switch instruction
726 // have the same type as the switched-on value.
727 const Type *SwitchTy = SI.getCondition()->getType();
728 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
729 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
730 "Switch constants must all be same type as switch value!", &SI);
732 visitTerminatorInst(SI);
735 void Verifier::visitSelectInst(SelectInst &SI) {
736 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
738 "Invalid operands for select instruction!", &SI);
740 Assert1(SI.getTrueValue()->getType() == SI.getType(),
741 "Select values must have same type as select instruction!", &SI);
742 visitInstruction(SI);
745 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
746 /// a pass, if any exist, it's an error.
748 void Verifier::visitUserOp1(Instruction &I) {
749 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
752 void Verifier::visitTruncInst(TruncInst &I) {
753 // Get the source and destination types
754 const Type *SrcTy = I.getOperand(0)->getType();
755 const Type *DestTy = I.getType();
757 // Get the size of the types in bits, we'll need this later
758 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
759 unsigned DestBitSize = DestTy->getScalarSizeInBits();
761 Assert1(SrcTy->isIntOrIntVector(), "Trunc only operates on integer", &I);
762 Assert1(DestTy->isIntOrIntVector(), "Trunc only produces integer", &I);
763 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
764 "trunc source and destination must both be a vector or neither", &I);
765 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
770 void Verifier::visitZExtInst(ZExtInst &I) {
771 // Get the source and destination types
772 const Type *SrcTy = I.getOperand(0)->getType();
773 const Type *DestTy = I.getType();
775 // Get the size of the types in bits, we'll need this later
776 Assert1(SrcTy->isIntOrIntVector(), "ZExt only operates on integer", &I);
777 Assert1(DestTy->isIntOrIntVector(), "ZExt only produces an integer", &I);
778 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
779 "zext source and destination must both be a vector or neither", &I);
780 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
781 unsigned DestBitSize = DestTy->getScalarSizeInBits();
783 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
788 void Verifier::visitSExtInst(SExtInst &I) {
789 // Get the source and destination types
790 const Type *SrcTy = I.getOperand(0)->getType();
791 const Type *DestTy = I.getType();
793 // Get the size of the types in bits, we'll need this later
794 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
795 unsigned DestBitSize = DestTy->getScalarSizeInBits();
797 Assert1(SrcTy->isIntOrIntVector(), "SExt only operates on integer", &I);
798 Assert1(DestTy->isIntOrIntVector(), "SExt only produces an integer", &I);
799 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
800 "sext source and destination must both be a vector or neither", &I);
801 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
806 void Verifier::visitFPTruncInst(FPTruncInst &I) {
807 // Get the source and destination types
808 const Type *SrcTy = I.getOperand(0)->getType();
809 const Type *DestTy = I.getType();
810 // Get the size of the types in bits, we'll need this later
811 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
812 unsigned DestBitSize = DestTy->getScalarSizeInBits();
814 Assert1(SrcTy->isFPOrFPVector(),"FPTrunc only operates on FP", &I);
815 Assert1(DestTy->isFPOrFPVector(),"FPTrunc only produces an FP", &I);
816 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
817 "fptrunc source and destination must both be a vector or neither",&I);
818 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
823 void Verifier::visitFPExtInst(FPExtInst &I) {
824 // Get the source and destination types
825 const Type *SrcTy = I.getOperand(0)->getType();
826 const Type *DestTy = I.getType();
828 // Get the size of the types in bits, we'll need this later
829 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
830 unsigned DestBitSize = DestTy->getScalarSizeInBits();
832 Assert1(SrcTy->isFPOrFPVector(),"FPExt only operates on FP", &I);
833 Assert1(DestTy->isFPOrFPVector(),"FPExt only produces an FP", &I);
834 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
835 "fpext source and destination must both be a vector or neither", &I);
836 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
841 void Verifier::visitUIToFPInst(UIToFPInst &I) {
842 // Get the source and destination types
843 const Type *SrcTy = I.getOperand(0)->getType();
844 const Type *DestTy = I.getType();
846 bool SrcVec = isa<VectorType>(SrcTy);
847 bool DstVec = isa<VectorType>(DestTy);
849 Assert1(SrcVec == DstVec,
850 "UIToFP source and dest must both be vector or scalar", &I);
851 Assert1(SrcTy->isIntOrIntVector(),
852 "UIToFP source must be integer or integer vector", &I);
853 Assert1(DestTy->isFPOrFPVector(),
854 "UIToFP result must be FP or FP vector", &I);
856 if (SrcVec && DstVec)
857 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
858 cast<VectorType>(DestTy)->getNumElements(),
859 "UIToFP source and dest vector length mismatch", &I);
864 void Verifier::visitSIToFPInst(SIToFPInst &I) {
865 // Get the source and destination types
866 const Type *SrcTy = I.getOperand(0)->getType();
867 const Type *DestTy = I.getType();
869 bool SrcVec = isa<VectorType>(SrcTy);
870 bool DstVec = isa<VectorType>(DestTy);
872 Assert1(SrcVec == DstVec,
873 "SIToFP source and dest must both be vector or scalar", &I);
874 Assert1(SrcTy->isIntOrIntVector(),
875 "SIToFP source must be integer or integer vector", &I);
876 Assert1(DestTy->isFPOrFPVector(),
877 "SIToFP result must be FP or FP vector", &I);
879 if (SrcVec && DstVec)
880 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
881 cast<VectorType>(DestTy)->getNumElements(),
882 "SIToFP source and dest vector length mismatch", &I);
887 void Verifier::visitFPToUIInst(FPToUIInst &I) {
888 // Get the source and destination types
889 const Type *SrcTy = I.getOperand(0)->getType();
890 const Type *DestTy = I.getType();
892 bool SrcVec = isa<VectorType>(SrcTy);
893 bool DstVec = isa<VectorType>(DestTy);
895 Assert1(SrcVec == DstVec,
896 "FPToUI source and dest must both be vector or scalar", &I);
897 Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
898 Assert1(DestTy->isIntOrIntVector(),
899 "FPToUI result must be integer or integer vector", &I);
901 if (SrcVec && DstVec)
902 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
903 cast<VectorType>(DestTy)->getNumElements(),
904 "FPToUI source and dest vector length mismatch", &I);
909 void Verifier::visitFPToSIInst(FPToSIInst &I) {
910 // Get the source and destination types
911 const Type *SrcTy = I.getOperand(0)->getType();
912 const Type *DestTy = I.getType();
914 bool SrcVec = isa<VectorType>(SrcTy);
915 bool DstVec = isa<VectorType>(DestTy);
917 Assert1(SrcVec == DstVec,
918 "FPToSI source and dest must both be vector or scalar", &I);
919 Assert1(SrcTy->isFPOrFPVector(),
920 "FPToSI source must be FP or FP vector", &I);
921 Assert1(DestTy->isIntOrIntVector(),
922 "FPToSI result must be integer or integer vector", &I);
924 if (SrcVec && DstVec)
925 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
926 cast<VectorType>(DestTy)->getNumElements(),
927 "FPToSI source and dest vector length mismatch", &I);
932 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
933 // Get the source and destination types
934 const Type *SrcTy = I.getOperand(0)->getType();
935 const Type *DestTy = I.getType();
937 Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
938 Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
943 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
944 // Get the source and destination types
945 const Type *SrcTy = I.getOperand(0)->getType();
946 const Type *DestTy = I.getType();
948 Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
949 Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
954 void Verifier::visitBitCastInst(BitCastInst &I) {
955 // Get the source and destination types
956 const Type *SrcTy = I.getOperand(0)->getType();
957 const Type *DestTy = I.getType();
959 // Get the size of the types in bits, we'll need this later
960 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
961 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
963 // BitCast implies a no-op cast of type only. No bits change.
964 // However, you can't cast pointers to anything but pointers.
965 Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
966 "Bitcast requires both operands to be pointer or neither", &I);
967 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
969 // Disallow aggregates.
970 Assert1(!SrcTy->isAggregateType(),
971 "Bitcast operand must not be aggregate", &I);
972 Assert1(!DestTy->isAggregateType(),
973 "Bitcast type must not be aggregate", &I);
978 /// visitPHINode - Ensure that a PHI node is well formed.
980 void Verifier::visitPHINode(PHINode &PN) {
981 // Ensure that the PHI nodes are all grouped together at the top of the block.
982 // This can be tested by checking whether the instruction before this is
983 // either nonexistent (because this is begin()) or is a PHI node. If not,
984 // then there is some other instruction before a PHI.
985 Assert2(&PN == &PN.getParent()->front() ||
986 isa<PHINode>(--BasicBlock::iterator(&PN)),
987 "PHI nodes not grouped at top of basic block!",
988 &PN, PN.getParent());
990 // Check that all of the operands of the PHI node have the same type as the
992 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
993 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
994 "PHI node operands are not the same type as the result!", &PN);
996 // All other PHI node constraints are checked in the visitBasicBlock method.
998 visitInstruction(PN);
1001 void Verifier::VerifyCallSite(CallSite CS) {
1002 Instruction *I = CS.getInstruction();
1004 Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
1005 "Called function must be a pointer!", I);
1006 const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1007 Assert1(isa<FunctionType>(FPTy->getElementType()),
1008 "Called function is not pointer to function type!", I);
1010 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1012 // Verify that the correct number of arguments are being passed
1013 if (FTy->isVarArg())
1014 Assert1(CS.arg_size() >= FTy->getNumParams(),
1015 "Called function requires more parameters than were provided!",I);
1017 Assert1(CS.arg_size() == FTy->getNumParams(),
1018 "Incorrect number of arguments passed to called function!", I);
1020 // Verify that all arguments to the call match the function type...
1021 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1022 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1023 "Call parameter type does not match function signature!",
1024 CS.getArgument(i), FTy->getParamType(i), I);
1026 const AttrListPtr &Attrs = CS.getAttributes();
1028 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1029 "Attributes after last parameter!", I);
1031 // Verify call attributes.
1032 VerifyFunctionAttrs(FTy, Attrs, I);
1034 if (FTy->isVarArg())
1035 // Check attributes on the varargs part.
1036 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1037 Attributes Attr = Attrs.getParamAttributes(Idx);
1039 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1041 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1042 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1043 " cannot be used for vararg call arguments!", I);
1046 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1047 if (!CS.getCalledFunction() || CS.getCalledFunction()->getName().size() < 5 ||
1048 CS.getCalledFunction()->getName().substr(0, 5) != "llvm.") {
1049 Assert1(FTy->getReturnType() != Type::getMetadataTy(I->getContext()),
1050 "Only intrinsics may return metadata", I);
1051 for (FunctionType::param_iterator PI = FTy->param_begin(),
1052 PE = FTy->param_end(); PI != PE; ++PI)
1053 Assert1(PI->get() != Type::getMetadataTy(I->getContext()),
1054 "Function has metadata parameter but isn't an intrinsic", I);
1057 visitInstruction(*I);
1060 void Verifier::visitCallInst(CallInst &CI) {
1061 VerifyCallSite(&CI);
1063 if (Function *F = CI.getCalledFunction())
1064 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1065 visitIntrinsicFunctionCall(ID, CI);
1068 void Verifier::visitInvokeInst(InvokeInst &II) {
1069 VerifyCallSite(&II);
1072 /// visitBinaryOperator - Check that both arguments to the binary operator are
1073 /// of the same type!
1075 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1076 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1077 "Both operands to a binary operator are not of the same type!", &B);
1079 switch (B.getOpcode()) {
1080 // Check that integer arithmetic operators are only used with
1081 // integral operands.
1082 case Instruction::Add:
1083 case Instruction::Sub:
1084 case Instruction::Mul:
1085 case Instruction::SDiv:
1086 case Instruction::UDiv:
1087 case Instruction::SRem:
1088 case Instruction::URem:
1089 Assert1(B.getType()->isIntOrIntVector(),
1090 "Integer arithmetic operators only work with integral types!", &B);
1091 Assert1(B.getType() == B.getOperand(0)->getType(),
1092 "Integer arithmetic operators must have same type "
1093 "for operands and result!", &B);
1095 // Check that floating-point arithmetic operators are only used with
1096 // floating-point operands.
1097 case Instruction::FAdd:
1098 case Instruction::FSub:
1099 case Instruction::FMul:
1100 case Instruction::FDiv:
1101 case Instruction::FRem:
1102 Assert1(B.getType()->isFPOrFPVector(),
1103 "Floating-point arithmetic operators only work with "
1104 "floating-point types!", &B);
1105 Assert1(B.getType() == B.getOperand(0)->getType(),
1106 "Floating-point arithmetic operators must have same type "
1107 "for operands and result!", &B);
1109 // Check that logical operators are only used with integral operands.
1110 case Instruction::And:
1111 case Instruction::Or:
1112 case Instruction::Xor:
1113 Assert1(B.getType()->isIntOrIntVector(),
1114 "Logical operators only work with integral types!", &B);
1115 Assert1(B.getType() == B.getOperand(0)->getType(),
1116 "Logical operators must have same type for operands and result!",
1119 case Instruction::Shl:
1120 case Instruction::LShr:
1121 case Instruction::AShr:
1122 Assert1(B.getType()->isIntOrIntVector(),
1123 "Shifts only work with integral types!", &B);
1124 Assert1(B.getType() == B.getOperand(0)->getType(),
1125 "Shift return type must be same as operands!", &B);
1128 llvm_unreachable("Unknown BinaryOperator opcode!");
1131 visitInstruction(B);
1134 void Verifier::visitICmpInst(ICmpInst& IC) {
1135 // Check that the operands are the same type
1136 const Type* Op0Ty = IC.getOperand(0)->getType();
1137 const Type* Op1Ty = IC.getOperand(1)->getType();
1138 Assert1(Op0Ty == Op1Ty,
1139 "Both operands to ICmp instruction are not of the same type!", &IC);
1140 // Check that the operands are the right type
1141 Assert1(Op0Ty->isIntOrIntVector() || isa<PointerType>(Op0Ty),
1142 "Invalid operand types for ICmp instruction", &IC);
1144 visitInstruction(IC);
1147 void Verifier::visitFCmpInst(FCmpInst& FC) {
1148 // Check that the operands are the same type
1149 const Type* Op0Ty = FC.getOperand(0)->getType();
1150 const Type* Op1Ty = FC.getOperand(1)->getType();
1151 Assert1(Op0Ty == Op1Ty,
1152 "Both operands to FCmp instruction are not of the same type!", &FC);
1153 // Check that the operands are the right type
1154 Assert1(Op0Ty->isFPOrFPVector(),
1155 "Invalid operand types for FCmp instruction", &FC);
1156 visitInstruction(FC);
1159 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1160 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1162 "Invalid extractelement operands!", &EI);
1163 visitInstruction(EI);
1166 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1167 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1170 "Invalid insertelement operands!", &IE);
1171 visitInstruction(IE);
1174 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1175 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1177 "Invalid shufflevector operands!", &SV);
1179 const VectorType *VTy = dyn_cast<VectorType>(SV.getOperand(0)->getType());
1180 Assert1(VTy, "Operands are not a vector type", &SV);
1182 // Check to see if Mask is valid.
1183 if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1184 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1185 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1186 Assert1(!CI->uge(VTy->getNumElements()*2),
1187 "Invalid shufflevector shuffle mask!", &SV);
1189 Assert1(isa<UndefValue>(MV->getOperand(i)),
1190 "Invalid shufflevector shuffle mask!", &SV);
1194 Assert1(isa<UndefValue>(SV.getOperand(2)) ||
1195 isa<ConstantAggregateZero>(SV.getOperand(2)),
1196 "Invalid shufflevector shuffle mask!", &SV);
1199 visitInstruction(SV);
1202 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1203 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1205 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1206 Idxs.begin(), Idxs.end());
1207 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1208 Assert2(isa<PointerType>(GEP.getType()) &&
1209 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1210 "GEP is not of right type for indices!", &GEP, ElTy);
1211 visitInstruction(GEP);
1214 void Verifier::visitLoadInst(LoadInst &LI) {
1216 cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
1217 Assert2(ElTy == LI.getType(),
1218 "Load result type does not match pointer operand type!", &LI, ElTy);
1219 Assert1(ElTy != Type::getMetadataTy(LI.getContext()),
1220 "Can't load metadata!", &LI);
1221 visitInstruction(LI);
1224 void Verifier::visitStoreInst(StoreInst &SI) {
1226 cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
1227 Assert2(ElTy == SI.getOperand(0)->getType(),
1228 "Stored value type does not match pointer operand type!", &SI, ElTy);
1229 Assert1(ElTy != Type::getMetadataTy(SI.getContext()),
1230 "Can't store metadata!", &SI);
1231 visitInstruction(SI);
1234 void Verifier::visitAllocationInst(AllocationInst &AI) {
1235 const PointerType *PTy = AI.getType();
1236 Assert1(PTy->getAddressSpace() == 0,
1237 "Allocation instruction pointer not in the generic address space!",
1239 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1241 visitInstruction(AI);
1244 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1245 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1246 EVI.idx_begin(), EVI.idx_end()) ==
1248 "Invalid ExtractValueInst operands!", &EVI);
1250 visitInstruction(EVI);
1253 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1254 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1255 IVI.idx_begin(), IVI.idx_end()) ==
1256 IVI.getOperand(1)->getType(),
1257 "Invalid InsertValueInst operands!", &IVI);
1259 visitInstruction(IVI);
1262 /// verifyInstruction - Verify that an instruction is well formed.
1264 void Verifier::visitInstruction(Instruction &I) {
1265 BasicBlock *BB = I.getParent();
1266 Assert1(BB, "Instruction not embedded in basic block!", &I);
1268 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1269 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1271 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1272 "Only PHI nodes may reference their own value!", &I);
1275 // Verify that if this is a terminator that it is at the end of the block.
1276 if (isa<TerminatorInst>(I))
1277 Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1279 // Check that void typed values don't have names
1280 Assert1(I.getType() != Type::getVoidTy(I.getContext()) || !I.hasName(),
1281 "Instruction has a name, but provides a void value!", &I);
1283 // Check that the return value of the instruction is either void or a legal
1285 Assert1(I.getType() == Type::getVoidTy(I.getContext()) ||
1286 I.getType()->isFirstClassType()
1287 || ((isa<CallInst>(I) || isa<InvokeInst>(I))
1288 && isa<StructType>(I.getType())),
1289 "Instruction returns a non-scalar type!", &I);
1291 // Check that the instruction doesn't produce metadata or metadata*. Calls
1292 // all already checked against the callee type.
1293 Assert1(I.getType() != Type::getMetadataTy(I.getContext()) ||
1294 isa<CallInst>(I) || isa<InvokeInst>(I),
1295 "Invalid use of metadata!", &I);
1297 if (const PointerType *PTy = dyn_cast<PointerType>(I.getType()))
1298 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1299 "Instructions may not produce pointer to metadata.", &I);
1301 // Check that all uses of the instruction, if they are instructions
1302 // themselves, actually have parent basic blocks. If the use is not an
1303 // instruction, it is an error!
1304 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1306 Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
1308 Instruction *Used = cast<Instruction>(*UI);
1309 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1310 " embedded in a basic block!", &I, Used);
1313 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1314 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1316 // Check to make sure that only first-class-values are operands to
1318 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1319 Assert1(0, "Instruction operands must be first-class values!", &I);
1322 if (const PointerType *PTy =
1323 dyn_cast<PointerType>(I.getOperand(i)->getType()))
1324 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1325 "Invalid use of metadata pointer.", &I);
1327 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1328 // Check to make sure that the "address of" an intrinsic function is never
1330 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1331 "Cannot take the address of an intrinsic!", &I);
1332 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1334 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1335 Assert1(OpBB->getParent() == BB->getParent(),
1336 "Referring to a basic block in another function!", &I);
1337 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1338 Assert1(OpArg->getParent() == BB->getParent(),
1339 "Referring to an argument in another function!", &I);
1340 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1341 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1343 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1344 BasicBlock *OpBlock = Op->getParent();
1346 // Check that a definition dominates all of its uses.
1347 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1348 // Invoke results are only usable in the normal destination, not in the
1349 // exceptional destination.
1350 BasicBlock *NormalDest = II->getNormalDest();
1352 Assert2(NormalDest != II->getUnwindDest(),
1353 "No uses of invoke possible due to dominance structure!",
1356 // PHI nodes differ from other nodes because they actually "use" the
1357 // value in the predecessor basic blocks they correspond to.
1358 BasicBlock *UseBlock = BB;
1359 if (isa<PHINode>(I))
1360 UseBlock = cast<BasicBlock>(I.getOperand(i+1));
1362 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1363 // Special case of a phi node in the normal destination or the unwind
1365 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1366 "Invoke result not available in the unwind destination!",
1369 Assert2(DT->dominates(NormalDest, UseBlock) ||
1370 !DT->isReachableFromEntry(UseBlock),
1371 "Invoke result does not dominate all uses!", Op, &I);
1373 // If the normal successor of an invoke instruction has multiple
1374 // predecessors, then the normal edge from the invoke is critical,
1375 // so the invoke value can only be live if the destination block
1376 // dominates all of it's predecessors (other than the invoke).
1377 if (!NormalDest->getSinglePredecessor() &&
1378 DT->isReachableFromEntry(UseBlock))
1379 // If it is used by something non-phi, then the other case is that
1380 // 'NormalDest' dominates all of its predecessors other than the
1381 // invoke. In this case, the invoke value can still be used.
1382 for (pred_iterator PI = pred_begin(NormalDest),
1383 E = pred_end(NormalDest); PI != E; ++PI)
1384 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1385 DT->isReachableFromEntry(*PI)) {
1386 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1390 } else if (isa<PHINode>(I)) {
1391 // PHI nodes are more difficult than other nodes because they actually
1392 // "use" the value in the predecessor basic blocks they correspond to.
1393 BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
1394 Assert2(DT->dominates(OpBlock, PredBB) ||
1395 !DT->isReachableFromEntry(PredBB),
1396 "Instruction does not dominate all uses!", Op, &I);
1398 if (OpBlock == BB) {
1399 // If they are in the same basic block, make sure that the definition
1400 // comes before the use.
1401 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1402 "Instruction does not dominate all uses!", Op, &I);
1405 // Definition must dominate use unless use is unreachable!
1406 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1407 !DT->isReachableFromEntry(BB),
1408 "Instruction does not dominate all uses!", Op, &I);
1410 } else if (isa<InlineAsm>(I.getOperand(i))) {
1411 Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
1412 "Cannot take the address of an inline asm!", &I);
1415 InstsInThisBlock.insert(&I);
1418 // Flags used by TableGen to mark intrinsic parameters with the
1419 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1420 static const unsigned ExtendedElementVectorType = 0x40000000;
1421 static const unsigned TruncatedElementVectorType = 0x20000000;
1423 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1425 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1426 Function *IF = CI.getCalledFunction();
1427 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1430 #define GET_INTRINSIC_VERIFIER
1431 #include "llvm/Intrinsics.gen"
1432 #undef GET_INTRINSIC_VERIFIER
1437 case Intrinsic::dbg_declare: // llvm.dbg.declare
1438 if (Constant *C = dyn_cast<Constant>(CI.getOperand(1)))
1439 Assert1(C && !isa<ConstantPointerNull>(C),
1440 "invalid llvm.dbg.declare intrinsic call", &CI);
1442 case Intrinsic::memcpy:
1443 case Intrinsic::memmove:
1444 case Intrinsic::memset:
1445 Assert1(isa<ConstantInt>(CI.getOperand(4)),
1446 "alignment argument of memory intrinsics must be a constant int",
1449 case Intrinsic::gcroot:
1450 case Intrinsic::gcwrite:
1451 case Intrinsic::gcread:
1452 if (ID == Intrinsic::gcroot) {
1454 dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
1455 Assert1(AI && isa<PointerType>(AI->getType()->getElementType()),
1456 "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
1457 Assert1(isa<Constant>(CI.getOperand(2)),
1458 "llvm.gcroot parameter #2 must be a constant.", &CI);
1461 Assert1(CI.getParent()->getParent()->hasGC(),
1462 "Enclosing function does not use GC.", &CI);
1464 case Intrinsic::init_trampoline:
1465 Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1466 "llvm.init_trampoline parameter #2 must resolve to a function.",
1469 case Intrinsic::prefetch:
1470 Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
1471 isa<ConstantInt>(CI.getOperand(3)) &&
1472 cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
1473 cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
1474 "invalid arguments to llvm.prefetch",
1477 case Intrinsic::stackprotector:
1478 Assert1(isa<AllocaInst>(CI.getOperand(2)->stripPointerCasts()),
1479 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1485 /// Produce a string to identify an intrinsic parameter or return value.
1486 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1487 /// parameters beginning with NumRets.
1489 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1490 if (ArgNo < NumRets) {
1492 return "Intrinsic result type";
1494 return "Intrinsic result type #" + utostr(ArgNo);
1496 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1499 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1500 int VT, unsigned ArgNo, std::string &Suffix) {
1501 const FunctionType *FTy = F->getFunctionType();
1503 unsigned NumElts = 0;
1504 const Type *EltTy = Ty;
1505 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1507 EltTy = VTy->getElementType();
1508 NumElts = VTy->getNumElements();
1511 const Type *RetTy = FTy->getReturnType();
1512 const StructType *ST = dyn_cast<StructType>(RetTy);
1513 unsigned NumRets = 1;
1515 NumRets = ST->getNumElements();
1520 // Check flags that indicate a type that is an integral vector type with
1521 // elements that are larger or smaller than the elements of the matched
1523 if ((Match & (ExtendedElementVectorType |
1524 TruncatedElementVectorType)) != 0) {
1525 const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1526 if (!VTy || !IEltTy) {
1527 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1528 "an integral vector type.", F);
1531 // Adjust the current Ty (in the opposite direction) rather than
1532 // the type being matched against.
1533 if ((Match & ExtendedElementVectorType) != 0) {
1534 if ((IEltTy->getBitWidth() & 1) != 0) {
1535 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " vector "
1536 "element bit-width is odd.", F);
1539 Ty = VectorType::getTruncatedElementVectorType(VTy);
1541 Ty = VectorType::getExtendedElementVectorType(VTy);
1542 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1545 if (Match <= static_cast<int>(NumRets - 1)) {
1547 RetTy = ST->getElementType(Match);
1550 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1551 "match return type.", F);
1555 if (Ty != FTy->getParamType(Match - NumRets)) {
1556 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1557 "match parameter %" + utostr(Match - NumRets) + ".", F);
1561 } else if (VT == MVT::iAny) {
1562 if (!EltTy->isInteger()) {
1563 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1564 "an integer type.", F);
1568 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1572 Suffix += "v" + utostr(NumElts);
1574 Suffix += "i" + utostr(GotBits);
1576 // Check some constraints on various intrinsics.
1578 default: break; // Not everything needs to be checked.
1579 case Intrinsic::bswap:
1580 if (GotBits < 16 || GotBits % 16 != 0) {
1581 CheckFailed("Intrinsic requires even byte width argument", F);
1586 } else if (VT == MVT::fAny) {
1587 if (!EltTy->isFloatingPoint()) {
1588 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1589 "a floating-point type.", F);
1596 Suffix += "v" + utostr(NumElts);
1598 Suffix += EVT::getEVT(EltTy).getEVTString();
1599 } else if (VT == MVT::vAny) {
1601 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a vector type.", F);
1604 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1605 } else if (VT == MVT::iPTR) {
1606 if (!isa<PointerType>(Ty)) {
1607 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1608 "pointer and a pointer is required.", F);
1611 } else if (VT == MVT::iPTRAny) {
1612 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1613 // and iPTR. In the verifier, we can not distinguish which case we have so
1614 // allow either case to be legal.
1615 if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1616 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1617 EVT::getEVT(PTyp->getElementType()).getEVTString();
1619 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1620 "pointer and a pointer is required.", F);
1623 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1624 EVT VVT = EVT((MVT::SimpleValueType)VT);
1626 // If this is a vector argument, verify the number and type of elements.
1627 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1628 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1632 if (VVT.getVectorNumElements() != NumElts) {
1633 CheckFailed("Intrinsic prototype has incorrect number of "
1634 "vector elements!", F);
1637 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1639 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is wrong!", F);
1641 } else if (EltTy != Ty) {
1642 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is a vector "
1643 "and a scalar is required.", F);
1650 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1651 /// Intrinsics.gen. This implements a little state machine that verifies the
1652 /// prototype of intrinsics.
1653 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1655 unsigned ParamNum, ...) {
1657 va_start(VA, ParamNum);
1658 const FunctionType *FTy = F->getFunctionType();
1660 // For overloaded intrinsics, the Suffix of the function name must match the
1661 // types of the arguments. This variable keeps track of the expected
1662 // suffix, to be checked at the end.
1665 if (FTy->getNumParams() + FTy->isVarArg() != ParamNum) {
1666 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1670 const Type *Ty = FTy->getReturnType();
1671 const StructType *ST = dyn_cast<StructType>(Ty);
1673 // Verify the return types.
1674 if (ST && ST->getNumElements() != RetNum) {
1675 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1679 for (unsigned ArgNo = 0; ArgNo < RetNum; ++ArgNo) {
1680 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1682 if (ST) Ty = ST->getElementType(ArgNo);
1684 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1688 // Verify the parameter types.
1689 for (unsigned ArgNo = 0; ArgNo < ParamNum; ++ArgNo) {
1690 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1692 if (VT == MVT::isVoid && ArgNo > 0) {
1693 if (!FTy->isVarArg())
1694 CheckFailed("Intrinsic prototype has no '...'!", F);
1698 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT, ArgNo + RetNum,
1705 // For intrinsics without pointer arguments, if we computed a Suffix then the
1706 // intrinsic is overloaded and we need to make sure that the name of the
1707 // function is correct. We add the suffix to the name of the intrinsic and
1708 // compare against the given function name. If they are not the same, the
1709 // function name is invalid. This ensures that overloading of intrinsics
1710 // uses a sane and consistent naming convention. Note that intrinsics with
1711 // pointer argument may or may not be overloaded so we will check assuming it
1712 // has a suffix and not.
1713 if (!Suffix.empty()) {
1714 std::string Name(Intrinsic::getName(ID));
1715 if (Name + Suffix != F->getName()) {
1716 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1717 F->getName().substr(Name.length()) + "'. It should be '" +
1722 // Check parameter attributes.
1723 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1724 "Intrinsic has wrong parameter attributes!", F);
1728 //===----------------------------------------------------------------------===//
1729 // Implement the public interfaces to this file...
1730 //===----------------------------------------------------------------------===//
1732 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1733 return new Verifier(action);
1737 // verifyFunction - Create
1738 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1739 Function &F = const_cast<Function&>(f);
1740 assert(!F.isDeclaration() && "Cannot verify external functions");
1742 ExistingModuleProvider MP(F.getParent());
1743 FunctionPassManager FPM(&MP);
1744 Verifier *V = new Verifier(action);
1751 /// verifyModule - Check a module for errors, printing messages on stderr.
1752 /// Return true if the module is corrupt.
1754 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1755 std::string *ErrorInfo) {
1757 Verifier *V = new Verifier(action);
1759 PM.run(const_cast<Module&>(M));
1761 if (ErrorInfo && V->Broken)
1762 *ErrorInfo = V->MessagesStr.str();