Debug Info Finder|Verifier: handle DbgLoc attached to instructions.
[oota-llvm.git] / lib / IR / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
12 //
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.
15 //
16 //  * Both of a binary operator's parameters are of the same type
17 //  * Verify that the indices of mem access instructions match other operands
18 //  * Verify that arithmetic and other things are only performed on first-class
19 //    types.  Verify that shifts & logicals only happen on integrals f.e.
20 //  * All of the constants in a switch statement are of the correct type
21 //  * The code is in valid SSA form
22 //  * It should be illegal to put a label into any other type (like a structure)
23 //    or to return one. [except constant arrays!]
24 //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 //  * PHI nodes must have an entry for each predecessor, with no extras.
26 //  * PHI nodes must be the first thing in a basic block, all grouped together
27 //  * PHI nodes must have at least one entry
28 //  * All basic blocks should only end with terminator insts, not contain them
29 //  * The entry node to a function must not have predecessors
30 //  * All Instructions must be embedded into a basic block
31 //  * Functions cannot take a void-typed parameter
32 //  * Verify that a function's argument list agrees with it's declared type.
33 //  * It is illegal to specify a name for a void value.
34 //  * It is illegal to have a internal global value with no initializer
35 //  * It is illegal to have a ret instruction that returns a value that does not
36 //    agree with the function return value type.
37 //  * Function call argument types match the function prototype
38 //  * A landing pad is defined by a landingpad instruction, and can be jumped to
39 //    only by the unwind edge of an invoke instruction.
40 //  * A landingpad instruction must be the first non-PHI instruction in the
41 //    block.
42 //  * All landingpad instructions must use the same personality function with
43 //    the same function.
44 //  * All other things that are tested by asserts spread about the code...
45 //
46 //===----------------------------------------------------------------------===//
47
48 #include "llvm/Analysis/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Assembly/Writer.h"
56 #include "llvm/DebugInfo.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/InlineAsm.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/Metadata.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/InstVisitor.h"
67 #include "llvm/Pass.h"
68 #include "llvm/PassManager.h"
69 #include "llvm/Support/CFG.h"
70 #include "llvm/Support/CallSite.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
81                                               cl::init(false));
82
83 namespace {  // Anonymous namespace for class
84   struct PreVerifier : public FunctionPass {
85     static char ID; // Pass ID, replacement for typeid
86
87     PreVerifier() : FunctionPass(ID) {
88       initializePreVerifierPass(*PassRegistry::getPassRegistry());
89     }
90
91     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92       AU.setPreservesAll();
93     }
94
95     // Check that the prerequisites for successful DominatorTree construction
96     // are satisfied.
97     bool runOnFunction(Function &F) {
98       bool Broken = false;
99
100       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
101         if (I->empty() || !I->back().isTerminator()) {
102           dbgs() << "Basic Block in function '" << F.getName()
103                  << "' does not have terminator!\n";
104           WriteAsOperand(dbgs(), I, true);
105           dbgs() << "\n";
106           Broken = true;
107         }
108       }
109
110       if (Broken)
111         report_fatal_error("Broken module, no Basic Block terminator!");
112
113       return false;
114     }
115   };
116 }
117
118 char PreVerifier::ID = 0;
119 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
120                 false, false)
121 static char &PreVerifyID = PreVerifier::ID;
122
123 namespace {
124   struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
125     static char ID; // Pass ID, replacement for typeid
126     bool Broken;          // Is this module found to be broken?
127     VerifierFailureAction action;
128                           // What to do if verification fails.
129     Module *Mod;          // Module we are verifying right now
130     LLVMContext *Context; // Context within which we are verifying
131     DominatorTree *DT;    // Dominator Tree, caution can be null!
132     const DataLayout *DL;
133
134     std::string Messages;
135     raw_string_ostream MessagesStr;
136
137     /// InstInThisBlock - when verifying a basic block, keep track of all of the
138     /// instructions we have seen so far.  This allows us to do efficient
139     /// dominance checks for the case when an instruction has an operand that is
140     /// an instruction in the same block.
141     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
142
143     /// MDNodes - keep track of the metadata nodes that have been checked
144     /// already.
145     SmallPtrSet<MDNode *, 32> MDNodes;
146
147     /// PersonalityFn - The personality function referenced by the
148     /// LandingPadInsts. All LandingPadInsts within the same function must use
149     /// the same personality function.
150     const Value *PersonalityFn;
151
152     /// Finder keeps track of all debug info MDNodes in a Module.
153     DebugInfoFinder Finder;
154
155     Verifier()
156       : FunctionPass(ID), Broken(false),
157         action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0),
158         MessagesStr(Messages), PersonalityFn(0) {
159       initializeVerifierPass(*PassRegistry::getPassRegistry());
160     }
161     explicit Verifier(VerifierFailureAction ctn)
162       : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
163         Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) {
164       initializeVerifierPass(*PassRegistry::getPassRegistry());
165     }
166
167     bool doInitialization(Module &M) {
168       Mod = &M;
169       Context = &M.getContext();
170       Finder.reset();
171
172       DL = getAnalysisIfAvailable<DataLayout>();
173
174       // We must abort before returning back to the pass manager, or else the
175       // pass manager may try to run other passes on the broken module.
176       return abortIfBroken();
177     }
178
179     bool runOnFunction(Function &F) {
180       // Get dominator information if we are being run by PassManager
181       DT = &getAnalysis<DominatorTree>();
182
183       Mod = F.getParent();
184       if (!Context) Context = &F.getContext();
185
186       visit(F);
187       InstsInThisBlock.clear();
188       PersonalityFn = 0;
189
190       // We must abort before returning back to the pass manager, or else the
191       // pass manager may try to run other passes on the broken module.
192       return abortIfBroken();
193     }
194
195     bool doFinalization(Module &M) {
196       // Scan through, checking all of the external function's linkage now...
197       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
198         visitGlobalValue(*I);
199
200         // Check to make sure function prototypes are okay.
201         if (I->isDeclaration()) visitFunction(*I);
202       }
203
204       for (Module::global_iterator I = M.global_begin(), E = M.global_end();
205            I != E; ++I)
206         visitGlobalVariable(*I);
207
208       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
209            I != E; ++I)
210         visitGlobalAlias(*I);
211
212       for (Module::named_metadata_iterator I = M.named_metadata_begin(),
213            E = M.named_metadata_end(); I != E; ++I)
214         visitNamedMDNode(*I);
215
216       visitModuleFlags(M);
217
218       // Verify Debug Info.
219       verifyDebugInfo(M);
220
221       // If the module is broken, abort at this time.
222       return abortIfBroken();
223     }
224
225     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
226       AU.setPreservesAll();
227       AU.addRequiredID(PreVerifyID);
228       AU.addRequired<DominatorTree>();
229     }
230
231     /// abortIfBroken - If the module is broken and we are supposed to abort on
232     /// this condition, do so.
233     ///
234     bool abortIfBroken() {
235       if (!Broken) return false;
236       MessagesStr << "Broken module found, ";
237       switch (action) {
238       case AbortProcessAction:
239         MessagesStr << "compilation aborted!\n";
240         dbgs() << MessagesStr.str();
241         // Client should choose different reaction if abort is not desired
242         abort();
243       case PrintMessageAction:
244         MessagesStr << "verification continues.\n";
245         dbgs() << MessagesStr.str();
246         return false;
247       case ReturnStatusAction:
248         MessagesStr << "compilation terminated.\n";
249         return true;
250       }
251       llvm_unreachable("Invalid action");
252     }
253
254
255     // Verification methods...
256     void visitGlobalValue(GlobalValue &GV);
257     void visitGlobalVariable(GlobalVariable &GV);
258     void visitGlobalAlias(GlobalAlias &GA);
259     void visitNamedMDNode(NamedMDNode &NMD);
260     void visitMDNode(MDNode &MD, Function *F);
261     void visitModuleFlags(Module &M);
262     void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
263                          SmallVectorImpl<MDNode*> &Requirements);
264     void visitFunction(Function &F);
265     void visitBasicBlock(BasicBlock &BB);
266     using InstVisitor<Verifier>::visit;
267
268     void visit(Instruction &I);
269
270     void visitTruncInst(TruncInst &I);
271     void visitZExtInst(ZExtInst &I);
272     void visitSExtInst(SExtInst &I);
273     void visitFPTruncInst(FPTruncInst &I);
274     void visitFPExtInst(FPExtInst &I);
275     void visitFPToUIInst(FPToUIInst &I);
276     void visitFPToSIInst(FPToSIInst &I);
277     void visitUIToFPInst(UIToFPInst &I);
278     void visitSIToFPInst(SIToFPInst &I);
279     void visitIntToPtrInst(IntToPtrInst &I);
280     void visitPtrToIntInst(PtrToIntInst &I);
281     void visitBitCastInst(BitCastInst &I);
282     void visitPHINode(PHINode &PN);
283     void visitBinaryOperator(BinaryOperator &B);
284     void visitICmpInst(ICmpInst &IC);
285     void visitFCmpInst(FCmpInst &FC);
286     void visitExtractElementInst(ExtractElementInst &EI);
287     void visitInsertElementInst(InsertElementInst &EI);
288     void visitShuffleVectorInst(ShuffleVectorInst &EI);
289     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
290     void visitCallInst(CallInst &CI);
291     void visitInvokeInst(InvokeInst &II);
292     void visitGetElementPtrInst(GetElementPtrInst &GEP);
293     void visitLoadInst(LoadInst &LI);
294     void visitStoreInst(StoreInst &SI);
295     void verifyDominatesUse(Instruction &I, unsigned i);
296     void visitInstruction(Instruction &I);
297     void visitTerminatorInst(TerminatorInst &I);
298     void visitBranchInst(BranchInst &BI);
299     void visitReturnInst(ReturnInst &RI);
300     void visitSwitchInst(SwitchInst &SI);
301     void visitIndirectBrInst(IndirectBrInst &BI);
302     void visitSelectInst(SelectInst &SI);
303     void visitUserOp1(Instruction &I);
304     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
305     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
306     void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
307     void visitAtomicRMWInst(AtomicRMWInst &RMWI);
308     void visitFenceInst(FenceInst &FI);
309     void visitAllocaInst(AllocaInst &AI);
310     void visitExtractValueInst(ExtractValueInst &EVI);
311     void visitInsertValueInst(InsertValueInst &IVI);
312     void visitLandingPadInst(LandingPadInst &LPI);
313
314     void VerifyCallSite(CallSite CS);
315     bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
316                           int VT, unsigned ArgNo, std::string &Suffix);
317     bool VerifyIntrinsicType(Type *Ty,
318                              ArrayRef<Intrinsic::IITDescriptor> &Infos,
319                              SmallVectorImpl<Type*> &ArgTys);
320     bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
321     void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
322                               bool isFunction, const Value *V);
323     void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
324                               bool isReturnValue, const Value *V);
325     void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
326                              const Value *V);
327
328     void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
329     void VerifyConstantExprBitcastType(const ConstantExpr *CE);
330
331     void verifyDebugInfo(Module &M);
332
333     void WriteValue(const Value *V) {
334       if (!V) return;
335       if (isa<Instruction>(V)) {
336         MessagesStr << *V << '\n';
337       } else {
338         WriteAsOperand(MessagesStr, V, true, Mod);
339         MessagesStr << '\n';
340       }
341     }
342
343     void WriteType(Type *T) {
344       if (!T) return;
345       MessagesStr << ' ' << *T;
346     }
347
348
349     // CheckFailed - A check failed, so print out the condition and the message
350     // that failed.  This provides a nice place to put a breakpoint if you want
351     // to see why something is not correct.
352     void CheckFailed(const Twine &Message,
353                      const Value *V1 = 0, const Value *V2 = 0,
354                      const Value *V3 = 0, const Value *V4 = 0) {
355       MessagesStr << Message.str() << "\n";
356       WriteValue(V1);
357       WriteValue(V2);
358       WriteValue(V3);
359       WriteValue(V4);
360       Broken = true;
361     }
362
363     void CheckFailed(const Twine &Message, const Value *V1,
364                      Type *T2, const Value *V3 = 0) {
365       MessagesStr << Message.str() << "\n";
366       WriteValue(V1);
367       WriteType(T2);
368       WriteValue(V3);
369       Broken = true;
370     }
371
372     void CheckFailed(const Twine &Message, Type *T1,
373                      Type *T2 = 0, Type *T3 = 0) {
374       MessagesStr << Message.str() << "\n";
375       WriteType(T1);
376       WriteType(T2);
377       WriteType(T3);
378       Broken = true;
379     }
380   };
381 } // End anonymous namespace
382
383 char Verifier::ID = 0;
384 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
385 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
386 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
387 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
388
389 // Assert - We know that cond should be true, if not print an error message.
390 #define Assert(C, M) \
391   do { if (!(C)) { CheckFailed(M); return; } } while (0)
392 #define Assert1(C, M, V1) \
393   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
394 #define Assert2(C, M, V1, V2) \
395   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
396 #define Assert3(C, M, V1, V2, V3) \
397   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
398 #define Assert4(C, M, V1, V2, V3, V4) \
399   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
400
401 void Verifier::visit(Instruction &I) {
402   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
403     Assert1(I.getOperand(i) != 0, "Operand is null", &I);
404   InstVisitor<Verifier>::visit(I);
405 }
406
407
408 void Verifier::visitGlobalValue(GlobalValue &GV) {
409   Assert1(!GV.isDeclaration() ||
410           GV.isMaterializable() ||
411           GV.hasExternalLinkage() ||
412           GV.hasDLLImportLinkage() ||
413           GV.hasExternalWeakLinkage() ||
414           (isa<GlobalAlias>(GV) &&
415            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
416   "Global is external, but doesn't have external or dllimport or weak linkage!",
417           &GV);
418
419   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
420           "Global is marked as dllimport, but not external", &GV);
421
422   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
423           "Only global variables can have appending linkage!", &GV);
424
425   if (GV.hasAppendingLinkage()) {
426     GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
427     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
428             "Only global arrays can have appending linkage!", GVar);
429   }
430
431   Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
432           "linkonce_odr_auto_hide can only have default visibility!",
433           &GV);
434 }
435
436 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
437   if (GV.hasInitializer()) {
438     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
439             "Global variable initializer type does not match global "
440             "variable type!", &GV);
441
442     // If the global has common linkage, it must have a zero initializer and
443     // cannot be constant.
444     if (GV.hasCommonLinkage()) {
445       Assert1(GV.getInitializer()->isNullValue(),
446               "'common' global must have a zero initializer!", &GV);
447       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
448               &GV);
449     }
450   } else {
451     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
452             GV.hasExternalWeakLinkage(),
453             "invalid linkage type for global declaration", &GV);
454   }
455
456   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
457                        GV.getName() == "llvm.global_dtors")) {
458     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
459             "invalid linkage for intrinsic global variable", &GV);
460     // Don't worry about emitting an error for it not being an array,
461     // visitGlobalValue will complain on appending non-array.
462     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
463       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
464       PointerType *FuncPtrTy =
465           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
466       Assert1(STy && STy->getNumElements() == 2 &&
467               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
468               STy->getTypeAtIndex(1) == FuncPtrTy,
469               "wrong type for intrinsic global variable", &GV);
470     }
471   }
472
473   if (GV.hasName() && (GV.getName() == "llvm.used" ||
474                        GV.getName() == "llvm.compiler.used")) {
475     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
476             "invalid linkage for intrinsic global variable", &GV);
477     Type *GVType = GV.getType()->getElementType();
478     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
479       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
480       Assert1(PTy, "wrong type for intrinsic global variable", &GV);
481       if (GV.hasInitializer()) {
482         Constant *Init = GV.getInitializer();
483         ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
484         Assert1(InitArray, "wrong initalizer for intrinsic global variable",
485                 Init);
486         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
487           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
488           Assert1(
489               isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
490               "invalid llvm.used member", V);
491           Assert1(V->hasName(), "members of llvm.used must be named", V);
492         }
493       }
494     }
495   }
496
497   if (!GV.hasInitializer()) {
498     visitGlobalValue(GV);
499     return;
500   }
501
502   // Walk any aggregate initializers looking for bitcasts between address spaces
503   SmallPtrSet<const Value *, 4> Visited;
504   SmallVector<const Value *, 4> WorkStack;
505   WorkStack.push_back(cast<Value>(GV.getInitializer()));
506
507   while (!WorkStack.empty()) {
508     const Value *V = WorkStack.pop_back_val();
509     if (!Visited.insert(V))
510       continue;
511
512     if (const User *U = dyn_cast<User>(V)) {
513       for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
514         WorkStack.push_back(U->getOperand(I));
515     }
516
517     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
518       VerifyConstantExprBitcastType(CE);
519       if (Broken)
520         return;
521     }
522   }
523
524   visitGlobalValue(GV);
525 }
526
527 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
528   Assert1(!GA.getName().empty(),
529           "Alias name cannot be empty!", &GA);
530   Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
531           GA.hasWeakLinkage(),
532           "Alias should have external or external weak linkage!", &GA);
533   Assert1(GA.getAliasee(),
534           "Aliasee cannot be NULL!", &GA);
535   Assert1(GA.getType() == GA.getAliasee()->getType(),
536           "Alias and aliasee types should match!", &GA);
537   Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
538
539   Constant *Aliasee = GA.getAliasee();
540
541   if (!isa<GlobalValue>(Aliasee)) {
542     ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
543     Assert1(CE &&
544             (CE->getOpcode() == Instruction::BitCast ||
545              CE->getOpcode() == Instruction::GetElementPtr) &&
546             isa<GlobalValue>(CE->getOperand(0)),
547             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
548             &GA);
549
550     if (CE->getOpcode() == Instruction::BitCast) {
551       unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
552       unsigned DstAS = CE->getType()->getPointerAddressSpace();
553
554       Assert1(SrcAS == DstAS,
555               "Alias bitcasts cannot be between different address spaces",
556               &GA);
557     }
558   }
559
560   const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
561   Assert1(Resolved,
562           "Aliasing chain should end with function or global variable", &GA);
563
564   visitGlobalValue(GA);
565 }
566
567 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
568   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
569     MDNode *MD = NMD.getOperand(i);
570     if (!MD)
571       continue;
572
573     Assert1(!MD->isFunctionLocal(),
574             "Named metadata operand cannot be function local!", MD);
575     visitMDNode(*MD, 0);
576   }
577 }
578
579 void Verifier::visitMDNode(MDNode &MD, Function *F) {
580   // Only visit each node once.  Metadata can be mutually recursive, so this
581   // avoids infinite recursion here, as well as being an optimization.
582   if (!MDNodes.insert(&MD))
583     return;
584
585   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
586     Value *Op = MD.getOperand(i);
587     if (!Op)
588       continue;
589     if (isa<Constant>(Op) || isa<MDString>(Op))
590       continue;
591     if (MDNode *N = dyn_cast<MDNode>(Op)) {
592       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
593               "Global metadata operand cannot be function local!", &MD, N);
594       visitMDNode(*N, F);
595       continue;
596     }
597     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
598
599     // If this was an instruction, bb, or argument, verify that it is in the
600     // function that we expect.
601     Function *ActualF = 0;
602     if (Instruction *I = dyn_cast<Instruction>(Op))
603       ActualF = I->getParent()->getParent();
604     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
605       ActualF = BB->getParent();
606     else if (Argument *A = dyn_cast<Argument>(Op))
607       ActualF = A->getParent();
608     assert(ActualF && "Unimplemented function local metadata case!");
609
610     Assert2(ActualF == F, "function-local metadata used in wrong function",
611             &MD, Op);
612   }
613 }
614
615 void Verifier::visitModuleFlags(Module &M) {
616   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
617   if (!Flags) return;
618
619   // Scan each flag, and track the flags and requirements.
620   DenseMap<MDString*, MDNode*> SeenIDs;
621   SmallVector<MDNode*, 16> Requirements;
622   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
623     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
624   }
625
626   // Validate that the requirements in the module are valid.
627   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
628     MDNode *Requirement = Requirements[I];
629     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
630     Value *ReqValue = Requirement->getOperand(1);
631
632     MDNode *Op = SeenIDs.lookup(Flag);
633     if (!Op) {
634       CheckFailed("invalid requirement on flag, flag is not present in module",
635                   Flag);
636       continue;
637     }
638
639     if (Op->getOperand(2) != ReqValue) {
640       CheckFailed(("invalid requirement on flag, "
641                    "flag does not have the required value"),
642                   Flag);
643       continue;
644     }
645   }
646 }
647
648 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
649                                SmallVectorImpl<MDNode*> &Requirements) {
650   // Each module flag should have three arguments, the merge behavior (a
651   // constant int), the flag ID (an MDString), and the value.
652   Assert1(Op->getNumOperands() == 3,
653           "incorrect number of operands in module flag", Op);
654   ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
655   MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
656   Assert1(Behavior,
657           "invalid behavior operand in module flag (expected constant integer)",
658           Op->getOperand(0));
659   unsigned BehaviorValue = Behavior->getZExtValue();
660   Assert1(ID,
661           "invalid ID operand in module flag (expected metadata string)",
662           Op->getOperand(1));
663
664   // Sanity check the values for behaviors with additional requirements.
665   switch (BehaviorValue) {
666   default:
667     Assert1(false,
668             "invalid behavior operand in module flag (unexpected constant)",
669             Op->getOperand(0));
670     break;
671
672   case Module::Error:
673   case Module::Warning:
674   case Module::Override:
675     // These behavior types accept any value.
676     break;
677
678   case Module::Require: {
679     // The value should itself be an MDNode with two operands, a flag ID (an
680     // MDString), and a value.
681     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
682     Assert1(Value && Value->getNumOperands() == 2,
683             "invalid value for 'require' module flag (expected metadata pair)",
684             Op->getOperand(2));
685     Assert1(isa<MDString>(Value->getOperand(0)),
686             ("invalid value for 'require' module flag "
687              "(first value operand should be a string)"),
688             Value->getOperand(0));
689
690     // Append it to the list of requirements, to check once all module flags are
691     // scanned.
692     Requirements.push_back(Value);
693     break;
694   }
695
696   case Module::Append:
697   case Module::AppendUnique: {
698     // These behavior types require the operand be an MDNode.
699     Assert1(isa<MDNode>(Op->getOperand(2)),
700             "invalid value for 'append'-type module flag "
701             "(expected a metadata node)", Op->getOperand(2));
702     break;
703   }
704   }
705
706   // Unless this is a "requires" flag, check the ID is unique.
707   if (BehaviorValue != Module::Require) {
708     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
709     Assert1(Inserted,
710             "module flag identifiers must be unique (or of 'require' type)",
711             ID);
712   }
713 }
714
715 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
716                                     bool isFunction, const Value *V) {
717   unsigned Slot = ~0U;
718   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
719     if (Attrs.getSlotIndex(I) == Idx) {
720       Slot = I;
721       break;
722     }
723
724   assert(Slot != ~0U && "Attribute set inconsistency!");
725
726   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
727          I != E; ++I) {
728     if (I->isStringAttribute())
729       continue;
730
731     if (I->getKindAsEnum() == Attribute::NoReturn ||
732         I->getKindAsEnum() == Attribute::NoUnwind ||
733         I->getKindAsEnum() == Attribute::NoInline ||
734         I->getKindAsEnum() == Attribute::AlwaysInline ||
735         I->getKindAsEnum() == Attribute::OptimizeForSize ||
736         I->getKindAsEnum() == Attribute::StackProtect ||
737         I->getKindAsEnum() == Attribute::StackProtectReq ||
738         I->getKindAsEnum() == Attribute::StackProtectStrong ||
739         I->getKindAsEnum() == Attribute::NoRedZone ||
740         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
741         I->getKindAsEnum() == Attribute::Naked ||
742         I->getKindAsEnum() == Attribute::InlineHint ||
743         I->getKindAsEnum() == Attribute::StackAlignment ||
744         I->getKindAsEnum() == Attribute::UWTable ||
745         I->getKindAsEnum() == Attribute::NonLazyBind ||
746         I->getKindAsEnum() == Attribute::ReturnsTwice ||
747         I->getKindAsEnum() == Attribute::SanitizeAddress ||
748         I->getKindAsEnum() == Attribute::SanitizeThread ||
749         I->getKindAsEnum() == Attribute::SanitizeMemory ||
750         I->getKindAsEnum() == Attribute::MinSize ||
751         I->getKindAsEnum() == Attribute::NoDuplicate ||
752         I->getKindAsEnum() == Attribute::Builtin ||
753         I->getKindAsEnum() == Attribute::NoBuiltin ||
754         I->getKindAsEnum() == Attribute::Cold) {
755       if (!isFunction) {
756         CheckFailed("Attribute '" + I->getAsString() +
757                     "' only applies to functions!", V);
758         return;
759       }
760     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
761                I->getKindAsEnum() == Attribute::ReadNone) {
762       if (Idx == 0) {
763         CheckFailed("Attribute '" + I->getAsString() +
764                     "' does not apply to function returns");
765         return;
766       }
767     } else if (isFunction) {
768       CheckFailed("Attribute '" + I->getAsString() +
769                   "' does not apply to functions!", V);
770       return;
771     }
772   }
773 }
774
775 // VerifyParameterAttrs - Check the given attributes for an argument or return
776 // value of the specified type.  The value V is printed in error messages.
777 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
778                                     bool isReturnValue, const Value *V) {
779   if (!Attrs.hasAttributes(Idx))
780     return;
781
782   VerifyAttributeTypes(Attrs, Idx, false, V);
783
784   if (isReturnValue)
785     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
786             !Attrs.hasAttribute(Idx, Attribute::Nest) &&
787             !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
788             !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
789             !Attrs.hasAttribute(Idx, Attribute::Returned),
790             "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
791             "do not apply to return values!", V);
792
793   // Check for mutually incompatible attributes.
794   Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
795              Attrs.hasAttribute(Idx, Attribute::Nest)) ||
796             (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
797              Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
798             (Attrs.hasAttribute(Idx, Attribute::Nest) &&
799              Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
800           "'byval, nest, and sret' are incompatible!", V);
801
802   Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
803              Attrs.hasAttribute(Idx, Attribute::Nest)) ||
804             (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
805              Attrs.hasAttribute(Idx, Attribute::InReg)) ||
806             (Attrs.hasAttribute(Idx, Attribute::Nest) &&
807              Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
808           "'byval, nest, and inreg' are incompatible!", V);
809
810   Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
811             Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
812           "'sret and returned' are incompatible!", V);
813
814   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
815             Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
816           "'zeroext and signext' are incompatible!", V);
817
818   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
819             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
820           "'readnone and readonly' are incompatible!", V);
821
822   Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
823             Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
824           "'noinline and alwaysinline' are incompatible!", V);
825
826   Assert1(!AttrBuilder(Attrs, Idx).
827             hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
828           "Wrong types for attribute: " +
829           AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
830
831   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
832     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
833             PTy->getElementType()->isSized(),
834             "Attribute 'byval' does not support unsized types!", V);
835   else
836     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
837             "Attribute 'byval' only applies to parameters with pointer type!",
838             V);
839 }
840
841 // VerifyFunctionAttrs - Check parameter attributes against a function type.
842 // The value V is printed in error messages.
843 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
844                                    const Value *V) {
845   if (Attrs.isEmpty())
846     return;
847
848   bool SawNest = false;
849   bool SawReturned = false;
850
851   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
852     unsigned Idx = Attrs.getSlotIndex(i);
853
854     Type *Ty;
855     if (Idx == 0)
856       Ty = FT->getReturnType();
857     else if (Idx-1 < FT->getNumParams())
858       Ty = FT->getParamType(Idx-1);
859     else
860       break;  // VarArgs attributes, verified elsewhere.
861
862     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
863
864     if (Idx == 0)
865       continue;
866
867     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
868       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
869       SawNest = true;
870     }
871
872     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
873       Assert1(!SawReturned, "More than one parameter has attribute returned!",
874               V);
875       Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
876               "argument and return types for 'returned' attribute", V);
877       SawReturned = true;
878     }
879
880     if (Attrs.hasAttribute(Idx, Attribute::StructRet))
881       Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
882   }
883
884   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
885     return;
886
887   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
888
889   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
890                                Attribute::ReadNone) &&
891             Attrs.hasAttribute(AttributeSet::FunctionIndex,
892                                Attribute::ReadOnly)),
893           "Attributes 'readnone and readonly' are incompatible!", V);
894
895   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
896                                Attribute::NoInline) &&
897             Attrs.hasAttribute(AttributeSet::FunctionIndex,
898                                Attribute::AlwaysInline)),
899           "Attributes 'noinline and alwaysinline' are incompatible!", V);
900 }
901
902 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
903   // Get the size of the types in bits, we'll need this later
904   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
905   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
906
907   // BitCast implies a no-op cast of type only. No bits change.
908   // However, you can't cast pointers to anything but pointers.
909   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
910           "Bitcast requires both operands to be pointer or neither", V);
911   Assert1(SrcBitSize == DestBitSize,
912           "Bitcast requires types of same width", V);
913
914   // Disallow aggregates.
915   Assert1(!SrcTy->isAggregateType(),
916           "Bitcast operand must not be aggregate", V);
917   Assert1(!DestTy->isAggregateType(),
918           "Bitcast type must not be aggregate", V);
919
920   // Without datalayout, assume all address spaces are the same size.
921   // Don't check if both types are not pointers.
922   // Skip casts between scalars and vectors.
923   if (!DL ||
924       !SrcTy->isPtrOrPtrVectorTy() ||
925       !DestTy->isPtrOrPtrVectorTy() ||
926       SrcTy->isVectorTy() != DestTy->isVectorTy()) {
927     return;
928   }
929
930   unsigned SrcAS = SrcTy->getPointerAddressSpace();
931   unsigned DstAS = DestTy->getPointerAddressSpace();
932
933   unsigned SrcASSize = DL->getPointerSizeInBits(SrcAS);
934   unsigned DstASSize = DL->getPointerSizeInBits(DstAS);
935   Assert1(SrcASSize == DstASSize,
936           "Bitcasts between pointers of different address spaces must have "
937           "the same size pointers, otherwise use PtrToInt/IntToPtr.", V);
938 }
939
940 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
941   if (CE->getOpcode() == Instruction::BitCast) {
942     Type *SrcTy = CE->getOperand(0)->getType();
943     Type *DstTy = CE->getType();
944     VerifyBitcastType(CE, DstTy, SrcTy);
945   }
946 }
947
948 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
949   if (Attrs.getNumSlots() == 0)
950     return true;
951
952   unsigned LastSlot = Attrs.getNumSlots() - 1;
953   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
954   if (LastIndex <= Params
955       || (LastIndex == AttributeSet::FunctionIndex
956           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
957     return true;
958
959   return false;
960 }
961
962 // visitFunction - Verify that a function is ok.
963 //
964 void Verifier::visitFunction(Function &F) {
965   // Check function arguments.
966   FunctionType *FT = F.getFunctionType();
967   unsigned NumArgs = F.arg_size();
968
969   Assert1(Context == &F.getContext(),
970           "Function context does not match Module context!", &F);
971
972   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
973   Assert2(FT->getNumParams() == NumArgs,
974           "# formal arguments must match # of arguments for function type!",
975           &F, FT);
976   Assert1(F.getReturnType()->isFirstClassType() ||
977           F.getReturnType()->isVoidTy() ||
978           F.getReturnType()->isStructTy(),
979           "Functions cannot return aggregate values!", &F);
980
981   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
982           "Invalid struct return type!", &F);
983
984   AttributeSet Attrs = F.getAttributes();
985
986   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
987           "Attribute after last parameter!", &F);
988
989   // Check function attributes.
990   VerifyFunctionAttrs(FT, Attrs, &F);
991
992   // On function declarations/definitions, we do not support the builtin
993   // attribute. We do not check this in VerifyFunctionAttrs since that is
994   // checking for Attributes that can/can not ever be on functions.
995   Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
996                               Attribute::Builtin),
997           "Attribute 'builtin' can only be applied to a callsite.", &F);
998
999   // Check that this function meets the restrictions on this calling convention.
1000   switch (F.getCallingConv()) {
1001   default:
1002     break;
1003   case CallingConv::C:
1004     break;
1005   case CallingConv::Fast:
1006   case CallingConv::Cold:
1007   case CallingConv::X86_FastCall:
1008   case CallingConv::X86_ThisCall:
1009   case CallingConv::Intel_OCL_BI:
1010   case CallingConv::PTX_Kernel:
1011   case CallingConv::PTX_Device:
1012     Assert1(!F.isVarArg(),
1013             "Varargs functions must have C calling conventions!", &F);
1014     break;
1015   }
1016
1017   bool isLLVMdotName = F.getName().size() >= 5 &&
1018                        F.getName().substr(0, 5) == "llvm.";
1019
1020   // Check that the argument values match the function type for this function...
1021   unsigned i = 0;
1022   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1023        I != E; ++I, ++i) {
1024     Assert2(I->getType() == FT->getParamType(i),
1025             "Argument value does not match function argument type!",
1026             I, FT->getParamType(i));
1027     Assert1(I->getType()->isFirstClassType(),
1028             "Function arguments must have first-class types!", I);
1029     if (!isLLVMdotName)
1030       Assert2(!I->getType()->isMetadataTy(),
1031               "Function takes metadata but isn't an intrinsic", I, &F);
1032   }
1033
1034   if (F.isMaterializable()) {
1035     // Function has a body somewhere we can't see.
1036   } else if (F.isDeclaration()) {
1037     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
1038             F.hasExternalWeakLinkage(),
1039             "invalid linkage type for function declaration", &F);
1040   } else {
1041     // Verify that this function (which has a body) is not named "llvm.*".  It
1042     // is not legal to define intrinsics.
1043     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1044
1045     // Check the entry node
1046     BasicBlock *Entry = &F.getEntryBlock();
1047     Assert1(pred_begin(Entry) == pred_end(Entry),
1048             "Entry block to function must not have predecessors!", Entry);
1049
1050     // The address of the entry block cannot be taken, unless it is dead.
1051     if (Entry->hasAddressTaken()) {
1052       Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
1053               "blockaddress may not be used with the entry block!", Entry);
1054     }
1055   }
1056
1057   // If this function is actually an intrinsic, verify that it is only used in
1058   // direct call/invokes, never having its "address taken".
1059   if (F.getIntrinsicID()) {
1060     const User *U;
1061     if (F.hasAddressTaken(&U))
1062       Assert1(0, "Invalid user of intrinsic instruction!", U);
1063   }
1064 }
1065
1066 // verifyBasicBlock - Verify that a basic block is well formed...
1067 //
1068 void Verifier::visitBasicBlock(BasicBlock &BB) {
1069   InstsInThisBlock.clear();
1070
1071   // Ensure that basic blocks have terminators!
1072   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1073
1074   // Check constraints that this basic block imposes on all of the PHI nodes in
1075   // it.
1076   if (isa<PHINode>(BB.front())) {
1077     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1078     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1079     std::sort(Preds.begin(), Preds.end());
1080     PHINode *PN;
1081     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1082       // Ensure that PHI nodes have at least one entry!
1083       Assert1(PN->getNumIncomingValues() != 0,
1084               "PHI nodes must have at least one entry.  If the block is dead, "
1085               "the PHI should be removed!", PN);
1086       Assert1(PN->getNumIncomingValues() == Preds.size(),
1087               "PHINode should have one entry for each predecessor of its "
1088               "parent basic block!", PN);
1089
1090       // Get and sort all incoming values in the PHI node...
1091       Values.clear();
1092       Values.reserve(PN->getNumIncomingValues());
1093       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1094         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1095                                         PN->getIncomingValue(i)));
1096       std::sort(Values.begin(), Values.end());
1097
1098       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1099         // Check to make sure that if there is more than one entry for a
1100         // particular basic block in this PHI node, that the incoming values are
1101         // all identical.
1102         //
1103         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
1104                 Values[i].second == Values[i-1].second,
1105                 "PHI node has multiple entries for the same basic block with "
1106                 "different incoming values!", PN, Values[i].first,
1107                 Values[i].second, Values[i-1].second);
1108
1109         // Check to make sure that the predecessors and PHI node entries are
1110         // matched up.
1111         Assert3(Values[i].first == Preds[i],
1112                 "PHI node entries do not match predecessors!", PN,
1113                 Values[i].first, Preds[i]);
1114       }
1115     }
1116   }
1117 }
1118
1119 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1120   // Ensure that terminators only exist at the end of the basic block.
1121   Assert1(&I == I.getParent()->getTerminator(),
1122           "Terminator found in the middle of a basic block!", I.getParent());
1123   visitInstruction(I);
1124 }
1125
1126 void Verifier::visitBranchInst(BranchInst &BI) {
1127   if (BI.isConditional()) {
1128     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1129             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1130   }
1131   visitTerminatorInst(BI);
1132 }
1133
1134 void Verifier::visitReturnInst(ReturnInst &RI) {
1135   Function *F = RI.getParent()->getParent();
1136   unsigned N = RI.getNumOperands();
1137   if (F->getReturnType()->isVoidTy())
1138     Assert2(N == 0,
1139             "Found return instr that returns non-void in Function of void "
1140             "return type!", &RI, F->getReturnType());
1141   else
1142     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1143             "Function return type does not match operand "
1144             "type of return inst!", &RI, F->getReturnType());
1145
1146   // Check to make sure that the return value has necessary properties for
1147   // terminators...
1148   visitTerminatorInst(RI);
1149 }
1150
1151 void Verifier::visitSwitchInst(SwitchInst &SI) {
1152   // Check to make sure that all of the constants in the switch instruction
1153   // have the same type as the switched-on value.
1154   Type *SwitchTy = SI.getCondition()->getType();
1155   IntegerType *IntTy = cast<IntegerType>(SwitchTy);
1156   IntegersSubsetToBB Mapping;
1157   std::map<IntegersSubset::Range, unsigned> RangeSetMap;
1158   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1159     IntegersSubset CaseRanges = i.getCaseValueEx();
1160     for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
1161       IntegersSubset::Range r = CaseRanges.getItem(ri);
1162       Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
1163               "Switch constants must all be same type as switch value!", &SI);
1164       Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
1165               "Switch constants must all be same type as switch value!", &SI);
1166       Mapping.add(r);
1167       RangeSetMap[r] = i.getCaseIndex();
1168     }
1169   }
1170
1171   IntegersSubsetToBB::RangeIterator errItem;
1172   if (!Mapping.verify(errItem)) {
1173     unsigned CaseIndex = RangeSetMap[errItem->first];
1174     SwitchInst::CaseIt i(&SI, CaseIndex);
1175     Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
1176   }
1177
1178   visitTerminatorInst(SI);
1179 }
1180
1181 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1182   Assert1(BI.getAddress()->getType()->isPointerTy(),
1183           "Indirectbr operand must have pointer type!", &BI);
1184   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1185     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1186             "Indirectbr destinations must all have pointer type!", &BI);
1187
1188   visitTerminatorInst(BI);
1189 }
1190
1191 void Verifier::visitSelectInst(SelectInst &SI) {
1192   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1193                                           SI.getOperand(2)),
1194           "Invalid operands for select instruction!", &SI);
1195
1196   Assert1(SI.getTrueValue()->getType() == SI.getType(),
1197           "Select values must have same type as select instruction!", &SI);
1198   visitInstruction(SI);
1199 }
1200
1201 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1202 /// a pass, if any exist, it's an error.
1203 ///
1204 void Verifier::visitUserOp1(Instruction &I) {
1205   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1206 }
1207
1208 void Verifier::visitTruncInst(TruncInst &I) {
1209   // Get the source and destination types
1210   Type *SrcTy = I.getOperand(0)->getType();
1211   Type *DestTy = I.getType();
1212
1213   // Get the size of the types in bits, we'll need this later
1214   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1215   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1216
1217   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1218   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1219   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1220           "trunc source and destination must both be a vector or neither", &I);
1221   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1222
1223   visitInstruction(I);
1224 }
1225
1226 void Verifier::visitZExtInst(ZExtInst &I) {
1227   // Get the source and destination types
1228   Type *SrcTy = I.getOperand(0)->getType();
1229   Type *DestTy = I.getType();
1230
1231   // Get the size of the types in bits, we'll need this later
1232   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1233   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1234   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1235           "zext source and destination must both be a vector or neither", &I);
1236   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1237   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1238
1239   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1240
1241   visitInstruction(I);
1242 }
1243
1244 void Verifier::visitSExtInst(SExtInst &I) {
1245   // Get the source and destination types
1246   Type *SrcTy = I.getOperand(0)->getType();
1247   Type *DestTy = I.getType();
1248
1249   // Get the size of the types in bits, we'll need this later
1250   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1251   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1252
1253   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1254   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1255   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1256           "sext source and destination must both be a vector or neither", &I);
1257   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1258
1259   visitInstruction(I);
1260 }
1261
1262 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1263   // Get the source and destination types
1264   Type *SrcTy = I.getOperand(0)->getType();
1265   Type *DestTy = I.getType();
1266   // Get the size of the types in bits, we'll need this later
1267   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1268   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1269
1270   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1271   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1272   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1273           "fptrunc source and destination must both be a vector or neither",&I);
1274   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1275
1276   visitInstruction(I);
1277 }
1278
1279 void Verifier::visitFPExtInst(FPExtInst &I) {
1280   // Get the source and destination types
1281   Type *SrcTy = I.getOperand(0)->getType();
1282   Type *DestTy = I.getType();
1283
1284   // Get the size of the types in bits, we'll need this later
1285   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1286   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1287
1288   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1289   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1290   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1291           "fpext source and destination must both be a vector or neither", &I);
1292   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1293
1294   visitInstruction(I);
1295 }
1296
1297 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1298   // Get the source and destination types
1299   Type *SrcTy = I.getOperand(0)->getType();
1300   Type *DestTy = I.getType();
1301
1302   bool SrcVec = SrcTy->isVectorTy();
1303   bool DstVec = DestTy->isVectorTy();
1304
1305   Assert1(SrcVec == DstVec,
1306           "UIToFP source and dest must both be vector or scalar", &I);
1307   Assert1(SrcTy->isIntOrIntVectorTy(),
1308           "UIToFP source must be integer or integer vector", &I);
1309   Assert1(DestTy->isFPOrFPVectorTy(),
1310           "UIToFP result must be FP or FP vector", &I);
1311
1312   if (SrcVec && DstVec)
1313     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1314             cast<VectorType>(DestTy)->getNumElements(),
1315             "UIToFP source and dest vector length mismatch", &I);
1316
1317   visitInstruction(I);
1318 }
1319
1320 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1321   // Get the source and destination types
1322   Type *SrcTy = I.getOperand(0)->getType();
1323   Type *DestTy = I.getType();
1324
1325   bool SrcVec = SrcTy->isVectorTy();
1326   bool DstVec = DestTy->isVectorTy();
1327
1328   Assert1(SrcVec == DstVec,
1329           "SIToFP source and dest must both be vector or scalar", &I);
1330   Assert1(SrcTy->isIntOrIntVectorTy(),
1331           "SIToFP source must be integer or integer vector", &I);
1332   Assert1(DestTy->isFPOrFPVectorTy(),
1333           "SIToFP result must be FP or FP vector", &I);
1334
1335   if (SrcVec && DstVec)
1336     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1337             cast<VectorType>(DestTy)->getNumElements(),
1338             "SIToFP source and dest vector length mismatch", &I);
1339
1340   visitInstruction(I);
1341 }
1342
1343 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1344   // Get the source and destination types
1345   Type *SrcTy = I.getOperand(0)->getType();
1346   Type *DestTy = I.getType();
1347
1348   bool SrcVec = SrcTy->isVectorTy();
1349   bool DstVec = DestTy->isVectorTy();
1350
1351   Assert1(SrcVec == DstVec,
1352           "FPToUI source and dest must both be vector or scalar", &I);
1353   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1354           &I);
1355   Assert1(DestTy->isIntOrIntVectorTy(),
1356           "FPToUI result must be integer or integer vector", &I);
1357
1358   if (SrcVec && DstVec)
1359     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1360             cast<VectorType>(DestTy)->getNumElements(),
1361             "FPToUI source and dest vector length mismatch", &I);
1362
1363   visitInstruction(I);
1364 }
1365
1366 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1367   // Get the source and destination types
1368   Type *SrcTy = I.getOperand(0)->getType();
1369   Type *DestTy = I.getType();
1370
1371   bool SrcVec = SrcTy->isVectorTy();
1372   bool DstVec = DestTy->isVectorTy();
1373
1374   Assert1(SrcVec == DstVec,
1375           "FPToSI source and dest must both be vector or scalar", &I);
1376   Assert1(SrcTy->isFPOrFPVectorTy(),
1377           "FPToSI source must be FP or FP vector", &I);
1378   Assert1(DestTy->isIntOrIntVectorTy(),
1379           "FPToSI result must be integer or integer vector", &I);
1380
1381   if (SrcVec && DstVec)
1382     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1383             cast<VectorType>(DestTy)->getNumElements(),
1384             "FPToSI source and dest vector length mismatch", &I);
1385
1386   visitInstruction(I);
1387 }
1388
1389 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1390   // Get the source and destination types
1391   Type *SrcTy = I.getOperand(0)->getType();
1392   Type *DestTy = I.getType();
1393
1394   Assert1(SrcTy->getScalarType()->isPointerTy(),
1395           "PtrToInt source must be pointer", &I);
1396   Assert1(DestTy->getScalarType()->isIntegerTy(),
1397           "PtrToInt result must be integral", &I);
1398   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1399           "PtrToInt type mismatch", &I);
1400
1401   if (SrcTy->isVectorTy()) {
1402     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1403     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1404     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1405           "PtrToInt Vector width mismatch", &I);
1406   }
1407
1408   visitInstruction(I);
1409 }
1410
1411 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1412   // Get the source and destination types
1413   Type *SrcTy = I.getOperand(0)->getType();
1414   Type *DestTy = I.getType();
1415
1416   Assert1(SrcTy->getScalarType()->isIntegerTy(),
1417           "IntToPtr source must be an integral", &I);
1418   Assert1(DestTy->getScalarType()->isPointerTy(),
1419           "IntToPtr result must be a pointer",&I);
1420   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1421           "IntToPtr type mismatch", &I);
1422   if (SrcTy->isVectorTy()) {
1423     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1424     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1425     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1426           "IntToPtr Vector width mismatch", &I);
1427   }
1428   visitInstruction(I);
1429 }
1430
1431 void Verifier::visitBitCastInst(BitCastInst &I) {
1432   Type *SrcTy = I.getOperand(0)->getType();
1433   Type *DestTy = I.getType();
1434   VerifyBitcastType(&I, DestTy, SrcTy);
1435   visitInstruction(I);
1436 }
1437
1438 /// visitPHINode - Ensure that a PHI node is well formed.
1439 ///
1440 void Verifier::visitPHINode(PHINode &PN) {
1441   // Ensure that the PHI nodes are all grouped together at the top of the block.
1442   // This can be tested by checking whether the instruction before this is
1443   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1444   // then there is some other instruction before a PHI.
1445   Assert2(&PN == &PN.getParent()->front() ||
1446           isa<PHINode>(--BasicBlock::iterator(&PN)),
1447           "PHI nodes not grouped at top of basic block!",
1448           &PN, PN.getParent());
1449
1450   // Check that all of the values of the PHI node have the same type as the
1451   // result, and that the incoming blocks are really basic blocks.
1452   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1453     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1454             "PHI node operands are not the same type as the result!", &PN);
1455   }
1456
1457   // All other PHI node constraints are checked in the visitBasicBlock method.
1458
1459   visitInstruction(PN);
1460 }
1461
1462 void Verifier::VerifyCallSite(CallSite CS) {
1463   Instruction *I = CS.getInstruction();
1464
1465   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1466           "Called function must be a pointer!", I);
1467   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1468
1469   Assert1(FPTy->getElementType()->isFunctionTy(),
1470           "Called function is not pointer to function type!", I);
1471   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1472
1473   // Verify that the correct number of arguments are being passed
1474   if (FTy->isVarArg())
1475     Assert1(CS.arg_size() >= FTy->getNumParams(),
1476             "Called function requires more parameters than were provided!",I);
1477   else
1478     Assert1(CS.arg_size() == FTy->getNumParams(),
1479             "Incorrect number of arguments passed to called function!", I);
1480
1481   // Verify that all arguments to the call match the function type.
1482   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1483     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1484             "Call parameter type does not match function signature!",
1485             CS.getArgument(i), FTy->getParamType(i), I);
1486
1487   AttributeSet Attrs = CS.getAttributes();
1488
1489   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1490           "Attribute after last parameter!", I);
1491
1492   // Verify call attributes.
1493   VerifyFunctionAttrs(FTy, Attrs, I);
1494
1495   if (FTy->isVarArg()) {
1496     // FIXME? is 'nest' even legal here?
1497     bool SawNest = false;
1498     bool SawReturned = false;
1499
1500     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1501       if (Attrs.hasAttribute(Idx, Attribute::Nest))
1502         SawNest = true;
1503       if (Attrs.hasAttribute(Idx, Attribute::Returned))
1504         SawReturned = true;
1505     }
1506
1507     // Check attributes on the varargs part.
1508     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1509       Type *Ty = CS.getArgument(Idx-1)->getType();
1510       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1511
1512       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1513         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1514         SawNest = true;
1515       }
1516
1517       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1518         Assert1(!SawReturned, "More than one parameter has attribute returned!",
1519                 I);
1520         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1521                 "Incompatible argument and return types for 'returned' "
1522                 "attribute", I);
1523         SawReturned = true;
1524       }
1525
1526       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1527               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1528     }
1529   }
1530
1531   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1532   if (CS.getCalledFunction() == 0 ||
1533       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1534     for (FunctionType::param_iterator PI = FTy->param_begin(),
1535            PE = FTy->param_end(); PI != PE; ++PI)
1536       Assert1(!(*PI)->isMetadataTy(),
1537               "Function has metadata parameter but isn't an intrinsic", I);
1538   }
1539
1540   // If the call site has the 'builtin' attribute, verify that it's applied to a
1541   // direct call to a function with the 'nobuiltin' attribute.
1542   if (CS.hasFnAttr(Attribute::Builtin))
1543     Assert1(CS.getCalledFunction() &&
1544             CS.getCalledFunction()->hasFnAttribute(Attribute::NoBuiltin),
1545             "Attribute 'builtin' can only be used in a call to a function with "
1546             "the 'nobuiltin' attribute.", I);
1547
1548   visitInstruction(*I);
1549 }
1550
1551 void Verifier::visitCallInst(CallInst &CI) {
1552   VerifyCallSite(&CI);
1553
1554   if (Function *F = CI.getCalledFunction())
1555     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1556       visitIntrinsicFunctionCall(ID, CI);
1557 }
1558
1559 void Verifier::visitInvokeInst(InvokeInst &II) {
1560   VerifyCallSite(&II);
1561
1562   // Verify that there is a landingpad instruction as the first non-PHI
1563   // instruction of the 'unwind' destination.
1564   Assert1(II.getUnwindDest()->isLandingPad(),
1565           "The unwind destination does not have a landingpad instruction!",&II);
1566
1567   visitTerminatorInst(II);
1568 }
1569
1570 /// visitBinaryOperator - Check that both arguments to the binary operator are
1571 /// of the same type!
1572 ///
1573 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1574   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1575           "Both operands to a binary operator are not of the same type!", &B);
1576
1577   switch (B.getOpcode()) {
1578   // Check that integer arithmetic operators are only used with
1579   // integral operands.
1580   case Instruction::Add:
1581   case Instruction::Sub:
1582   case Instruction::Mul:
1583   case Instruction::SDiv:
1584   case Instruction::UDiv:
1585   case Instruction::SRem:
1586   case Instruction::URem:
1587     Assert1(B.getType()->isIntOrIntVectorTy(),
1588             "Integer arithmetic operators only work with integral types!", &B);
1589     Assert1(B.getType() == B.getOperand(0)->getType(),
1590             "Integer arithmetic operators must have same type "
1591             "for operands and result!", &B);
1592     break;
1593   // Check that floating-point arithmetic operators are only used with
1594   // floating-point operands.
1595   case Instruction::FAdd:
1596   case Instruction::FSub:
1597   case Instruction::FMul:
1598   case Instruction::FDiv:
1599   case Instruction::FRem:
1600     Assert1(B.getType()->isFPOrFPVectorTy(),
1601             "Floating-point arithmetic operators only work with "
1602             "floating-point types!", &B);
1603     Assert1(B.getType() == B.getOperand(0)->getType(),
1604             "Floating-point arithmetic operators must have same type "
1605             "for operands and result!", &B);
1606     break;
1607   // Check that logical operators are only used with integral operands.
1608   case Instruction::And:
1609   case Instruction::Or:
1610   case Instruction::Xor:
1611     Assert1(B.getType()->isIntOrIntVectorTy(),
1612             "Logical operators only work with integral types!", &B);
1613     Assert1(B.getType() == B.getOperand(0)->getType(),
1614             "Logical operators must have same type for operands and result!",
1615             &B);
1616     break;
1617   case Instruction::Shl:
1618   case Instruction::LShr:
1619   case Instruction::AShr:
1620     Assert1(B.getType()->isIntOrIntVectorTy(),
1621             "Shifts only work with integral types!", &B);
1622     Assert1(B.getType() == B.getOperand(0)->getType(),
1623             "Shift return type must be same as operands!", &B);
1624     break;
1625   default:
1626     llvm_unreachable("Unknown BinaryOperator opcode!");
1627   }
1628
1629   visitInstruction(B);
1630 }
1631
1632 void Verifier::visitICmpInst(ICmpInst &IC) {
1633   // Check that the operands are the same type
1634   Type *Op0Ty = IC.getOperand(0)->getType();
1635   Type *Op1Ty = IC.getOperand(1)->getType();
1636   Assert1(Op0Ty == Op1Ty,
1637           "Both operands to ICmp instruction are not of the same type!", &IC);
1638   // Check that the operands are the right type
1639   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1640           "Invalid operand types for ICmp instruction", &IC);
1641   // Check that the predicate is valid.
1642   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1643           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1644           "Invalid predicate in ICmp instruction!", &IC);
1645
1646   visitInstruction(IC);
1647 }
1648
1649 void Verifier::visitFCmpInst(FCmpInst &FC) {
1650   // Check that the operands are the same type
1651   Type *Op0Ty = FC.getOperand(0)->getType();
1652   Type *Op1Ty = FC.getOperand(1)->getType();
1653   Assert1(Op0Ty == Op1Ty,
1654           "Both operands to FCmp instruction are not of the same type!", &FC);
1655   // Check that the operands are the right type
1656   Assert1(Op0Ty->isFPOrFPVectorTy(),
1657           "Invalid operand types for FCmp instruction", &FC);
1658   // Check that the predicate is valid.
1659   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1660           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1661           "Invalid predicate in FCmp instruction!", &FC);
1662
1663   visitInstruction(FC);
1664 }
1665
1666 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1667   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1668                                               EI.getOperand(1)),
1669           "Invalid extractelement operands!", &EI);
1670   visitInstruction(EI);
1671 }
1672
1673 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1674   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1675                                              IE.getOperand(1),
1676                                              IE.getOperand(2)),
1677           "Invalid insertelement operands!", &IE);
1678   visitInstruction(IE);
1679 }
1680
1681 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1682   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1683                                              SV.getOperand(2)),
1684           "Invalid shufflevector operands!", &SV);
1685   visitInstruction(SV);
1686 }
1687
1688 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1689   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1690
1691   Assert1(isa<PointerType>(TargetTy),
1692     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1693   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1694           "GEP into unsized type!", &GEP);
1695   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1696           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1697           &GEP);
1698
1699   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1700   Type *ElTy =
1701     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1702   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1703
1704   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1705           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1706           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1707
1708   if (GEP.getPointerOperandType()->isVectorTy()) {
1709     // Additional checks for vector GEPs.
1710     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1711     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1712             "Vector GEP result width doesn't match operand's", &GEP);
1713     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1714       Type *IndexTy = Idxs[i]->getType();
1715       Assert1(IndexTy->isVectorTy(),
1716               "Vector GEP must have vector indices!", &GEP);
1717       unsigned IndexWidth = IndexTy->getVectorNumElements();
1718       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1719     }
1720   }
1721   visitInstruction(GEP);
1722 }
1723
1724 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1725   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1726 }
1727
1728 void Verifier::visitLoadInst(LoadInst &LI) {
1729   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1730   Assert1(PTy, "Load operand must be a pointer.", &LI);
1731   Type *ElTy = PTy->getElementType();
1732   Assert2(ElTy == LI.getType(),
1733           "Load result type does not match pointer operand type!", &LI, ElTy);
1734   if (LI.isAtomic()) {
1735     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1736             "Load cannot have Release ordering", &LI);
1737     Assert1(LI.getAlignment() != 0,
1738             "Atomic load must specify explicit alignment", &LI);
1739     if (!ElTy->isPointerTy()) {
1740       Assert2(ElTy->isIntegerTy(),
1741               "atomic store operand must have integer type!",
1742               &LI, ElTy);
1743       unsigned Size = ElTy->getPrimitiveSizeInBits();
1744       Assert2(Size >= 8 && !(Size & (Size - 1)),
1745               "atomic store operand must be power-of-two byte-sized integer",
1746               &LI, ElTy);
1747     }
1748   } else {
1749     Assert1(LI.getSynchScope() == CrossThread,
1750             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1751   }
1752
1753   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1754     unsigned NumOperands = Range->getNumOperands();
1755     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1756     unsigned NumRanges = NumOperands / 2;
1757     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1758
1759     ConstantRange LastRange(1); // Dummy initial value
1760     for (unsigned i = 0; i < NumRanges; ++i) {
1761       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1762       Assert1(Low, "The lower limit must be an integer!", Low);
1763       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1764       Assert1(High, "The upper limit must be an integer!", High);
1765       Assert1(High->getType() == Low->getType() &&
1766               High->getType() == ElTy, "Range types must match load type!",
1767               &LI);
1768
1769       APInt HighV = High->getValue();
1770       APInt LowV = Low->getValue();
1771       ConstantRange CurRange(LowV, HighV);
1772       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1773               "Range must not be empty!", Range);
1774       if (i != 0) {
1775         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1776                 "Intervals are overlapping", Range);
1777         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1778                 Range);
1779         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1780                 Range);
1781       }
1782       LastRange = ConstantRange(LowV, HighV);
1783     }
1784     if (NumRanges > 2) {
1785       APInt FirstLow =
1786         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1787       APInt FirstHigh =
1788         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1789       ConstantRange FirstRange(FirstLow, FirstHigh);
1790       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1791               "Intervals are overlapping", Range);
1792       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1793               Range);
1794     }
1795
1796
1797   }
1798
1799   visitInstruction(LI);
1800 }
1801
1802 void Verifier::visitStoreInst(StoreInst &SI) {
1803   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1804   Assert1(PTy, "Store operand must be a pointer.", &SI);
1805   Type *ElTy = PTy->getElementType();
1806   Assert2(ElTy == SI.getOperand(0)->getType(),
1807           "Stored value type does not match pointer operand type!",
1808           &SI, ElTy);
1809   if (SI.isAtomic()) {
1810     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1811             "Store cannot have Acquire ordering", &SI);
1812     Assert1(SI.getAlignment() != 0,
1813             "Atomic store must specify explicit alignment", &SI);
1814     if (!ElTy->isPointerTy()) {
1815       Assert2(ElTy->isIntegerTy(),
1816               "atomic store operand must have integer type!",
1817               &SI, ElTy);
1818       unsigned Size = ElTy->getPrimitiveSizeInBits();
1819       Assert2(Size >= 8 && !(Size & (Size - 1)),
1820               "atomic store operand must be power-of-two byte-sized integer",
1821               &SI, ElTy);
1822     }
1823   } else {
1824     Assert1(SI.getSynchScope() == CrossThread,
1825             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1826   }
1827   visitInstruction(SI);
1828 }
1829
1830 void Verifier::visitAllocaInst(AllocaInst &AI) {
1831   PointerType *PTy = AI.getType();
1832   Assert1(PTy->getAddressSpace() == 0,
1833           "Allocation instruction pointer not in the generic address space!",
1834           &AI);
1835   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1836           &AI);
1837   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1838           "Alloca array size must have integer type", &AI);
1839   visitInstruction(AI);
1840 }
1841
1842 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1843   Assert1(CXI.getOrdering() != NotAtomic,
1844           "cmpxchg instructions must be atomic.", &CXI);
1845   Assert1(CXI.getOrdering() != Unordered,
1846           "cmpxchg instructions cannot be unordered.", &CXI);
1847   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1848   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1849   Type *ElTy = PTy->getElementType();
1850   Assert2(ElTy->isIntegerTy(),
1851           "cmpxchg operand must have integer type!",
1852           &CXI, ElTy);
1853   unsigned Size = ElTy->getPrimitiveSizeInBits();
1854   Assert2(Size >= 8 && !(Size & (Size - 1)),
1855           "cmpxchg operand must be power-of-two byte-sized integer",
1856           &CXI, ElTy);
1857   Assert2(ElTy == CXI.getOperand(1)->getType(),
1858           "Expected value type does not match pointer operand type!",
1859           &CXI, ElTy);
1860   Assert2(ElTy == CXI.getOperand(2)->getType(),
1861           "Stored value type does not match pointer operand type!",
1862           &CXI, ElTy);
1863   visitInstruction(CXI);
1864 }
1865
1866 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1867   Assert1(RMWI.getOrdering() != NotAtomic,
1868           "atomicrmw instructions must be atomic.", &RMWI);
1869   Assert1(RMWI.getOrdering() != Unordered,
1870           "atomicrmw instructions cannot be unordered.", &RMWI);
1871   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1872   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1873   Type *ElTy = PTy->getElementType();
1874   Assert2(ElTy->isIntegerTy(),
1875           "atomicrmw operand must have integer type!",
1876           &RMWI, ElTy);
1877   unsigned Size = ElTy->getPrimitiveSizeInBits();
1878   Assert2(Size >= 8 && !(Size & (Size - 1)),
1879           "atomicrmw operand must be power-of-two byte-sized integer",
1880           &RMWI, ElTy);
1881   Assert2(ElTy == RMWI.getOperand(1)->getType(),
1882           "Argument value type does not match pointer operand type!",
1883           &RMWI, ElTy);
1884   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1885           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1886           "Invalid binary operation!", &RMWI);
1887   visitInstruction(RMWI);
1888 }
1889
1890 void Verifier::visitFenceInst(FenceInst &FI) {
1891   const AtomicOrdering Ordering = FI.getOrdering();
1892   Assert1(Ordering == Acquire || Ordering == Release ||
1893           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1894           "fence instructions may only have "
1895           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1896   visitInstruction(FI);
1897 }
1898
1899 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1900   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1901                                            EVI.getIndices()) ==
1902           EVI.getType(),
1903           "Invalid ExtractValueInst operands!", &EVI);
1904
1905   visitInstruction(EVI);
1906 }
1907
1908 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1909   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1910                                            IVI.getIndices()) ==
1911           IVI.getOperand(1)->getType(),
1912           "Invalid InsertValueInst operands!", &IVI);
1913
1914   visitInstruction(IVI);
1915 }
1916
1917 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1918   BasicBlock *BB = LPI.getParent();
1919
1920   // The landingpad instruction is ill-formed if it doesn't have any clauses and
1921   // isn't a cleanup.
1922   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1923           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1924
1925   // The landingpad instruction defines its parent as a landing pad block. The
1926   // landing pad block may be branched to only by the unwind edge of an invoke.
1927   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1928     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1929     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1930             "Block containing LandingPadInst must be jumped to "
1931             "only by the unwind edge of an invoke.", &LPI);
1932   }
1933
1934   // The landingpad instruction must be the first non-PHI instruction in the
1935   // block.
1936   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1937           "LandingPadInst not the first non-PHI instruction in the block.",
1938           &LPI);
1939
1940   // The personality functions for all landingpad instructions within the same
1941   // function should match.
1942   if (PersonalityFn)
1943     Assert1(LPI.getPersonalityFn() == PersonalityFn,
1944             "Personality function doesn't match others in function", &LPI);
1945   PersonalityFn = LPI.getPersonalityFn();
1946
1947   // All operands must be constants.
1948   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1949           &LPI);
1950   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1951     Value *Clause = LPI.getClause(i);
1952     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1953     if (LPI.isCatch(i)) {
1954       Assert1(isa<PointerType>(Clause->getType()),
1955               "Catch operand does not have pointer type!", &LPI);
1956     } else {
1957       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1958       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1959               "Filter operand is not an array of constants!", &LPI);
1960     }
1961   }
1962
1963   visitInstruction(LPI);
1964 }
1965
1966 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1967   Instruction *Op = cast<Instruction>(I.getOperand(i));
1968   // If the we have an invalid invoke, don't try to compute the dominance.
1969   // We already reject it in the invoke specific checks and the dominance
1970   // computation doesn't handle multiple edges.
1971   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1972     if (II->getNormalDest() == II->getUnwindDest())
1973       return;
1974   }
1975
1976   const Use &U = I.getOperandUse(i);
1977   Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1978           "Instruction does not dominate all uses!", Op, &I);
1979 }
1980
1981 /// verifyInstruction - Verify that an instruction is well formed.
1982 ///
1983 void Verifier::visitInstruction(Instruction &I) {
1984   BasicBlock *BB = I.getParent();
1985   Assert1(BB, "Instruction not embedded in basic block!", &I);
1986
1987   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1988     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1989          UI != UE; ++UI)
1990       Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1991               "Only PHI nodes may reference their own value!", &I);
1992   }
1993
1994   // Check that void typed values don't have names
1995   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1996           "Instruction has a name, but provides a void value!", &I);
1997
1998   // Check that the return value of the instruction is either void or a legal
1999   // value type.
2000   Assert1(I.getType()->isVoidTy() ||
2001           I.getType()->isFirstClassType(),
2002           "Instruction returns a non-scalar type!", &I);
2003
2004   // Check that the instruction doesn't produce metadata. Calls are already
2005   // checked against the callee type.
2006   Assert1(!I.getType()->isMetadataTy() ||
2007           isa<CallInst>(I) || isa<InvokeInst>(I),
2008           "Invalid use of metadata!", &I);
2009
2010   // Check that all uses of the instruction, if they are instructions
2011   // themselves, actually have parent basic blocks.  If the use is not an
2012   // instruction, it is an error!
2013   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
2014        UI != UE; ++UI) {
2015     if (Instruction *Used = dyn_cast<Instruction>(*UI))
2016       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2017               " embedded in a basic block!", &I, Used);
2018     else {
2019       CheckFailed("Use of instruction is not an instruction!", *UI);
2020       return;
2021     }
2022   }
2023
2024   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2025     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2026
2027     // Check to make sure that only first-class-values are operands to
2028     // instructions.
2029     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2030       Assert1(0, "Instruction operands must be first-class values!", &I);
2031     }
2032
2033     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2034       // Check to make sure that the "address of" an intrinsic function is never
2035       // taken.
2036       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2037               "Cannot take the address of an intrinsic!", &I);
2038       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2039               F->getIntrinsicID() == Intrinsic::donothing,
2040               "Cannot invoke an intrinsinc other than donothing", &I);
2041       Assert1(F->getParent() == Mod, "Referencing function in another module!",
2042               &I);
2043     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2044       Assert1(OpBB->getParent() == BB->getParent(),
2045               "Referring to a basic block in another function!", &I);
2046     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2047       Assert1(OpArg->getParent() == BB->getParent(),
2048               "Referring to an argument in another function!", &I);
2049     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2050       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
2051               &I);
2052     } else if (isa<Instruction>(I.getOperand(i))) {
2053       verifyDominatesUse(I, i);
2054     } else if (isa<InlineAsm>(I.getOperand(i))) {
2055       Assert1((i + 1 == e && isa<CallInst>(I)) ||
2056               (i + 3 == e && isa<InvokeInst>(I)),
2057               "Cannot take the address of an inline asm!", &I);
2058     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2059       if (CE->getType()->isPtrOrPtrVectorTy()) {
2060         // If we have a ConstantExpr pointer, we need to see if it came from an
2061         // illegal bitcast (inttoptr <constant int> )
2062         SmallVector<const ConstantExpr *, 4> Stack;
2063         SmallPtrSet<const ConstantExpr *, 4> Visited;
2064         Stack.push_back(CE);
2065
2066         while (!Stack.empty()) {
2067           const ConstantExpr *V = Stack.pop_back_val();
2068           if (!Visited.insert(V))
2069             continue;
2070
2071           VerifyConstantExprBitcastType(V);
2072
2073           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2074             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2075               Stack.push_back(Op);
2076           }
2077         }
2078       }
2079     }
2080   }
2081
2082   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2083     Assert1(I.getType()->isFPOrFPVectorTy(),
2084             "fpmath requires a floating point result!", &I);
2085     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2086     Value *Op0 = MD->getOperand(0);
2087     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2088       APFloat Accuracy = CFP0->getValueAPF();
2089       Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2090               "fpmath accuracy not a positive number!", &I);
2091     } else {
2092       Assert1(false, "invalid fpmath accuracy!", &I);
2093     }
2094   }
2095
2096   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2097   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2098
2099   if (!DisableDebugInfoVerifier) {
2100     MD = I.getMetadata(LLVMContext::MD_dbg);
2101     Finder.processLocation(DILocation(MD));
2102   }
2103
2104   InstsInThisBlock.insert(&I);
2105 }
2106
2107 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2108 /// intrinsic argument or return value) matches the type constraints specified
2109 /// by the .td file (e.g. an "any integer" argument really is an integer).
2110 ///
2111 /// This return true on error but does not print a message.
2112 bool Verifier::VerifyIntrinsicType(Type *Ty,
2113                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2114                                    SmallVectorImpl<Type*> &ArgTys) {
2115   using namespace Intrinsic;
2116
2117   // If we ran out of descriptors, there are too many arguments.
2118   if (Infos.empty()) return true;
2119   IITDescriptor D = Infos.front();
2120   Infos = Infos.slice(1);
2121
2122   switch (D.Kind) {
2123   case IITDescriptor::Void: return !Ty->isVoidTy();
2124   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2125   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2126   case IITDescriptor::Half: return !Ty->isHalfTy();
2127   case IITDescriptor::Float: return !Ty->isFloatTy();
2128   case IITDescriptor::Double: return !Ty->isDoubleTy();
2129   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2130   case IITDescriptor::Vector: {
2131     VectorType *VT = dyn_cast<VectorType>(Ty);
2132     return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2133            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2134   }
2135   case IITDescriptor::Pointer: {
2136     PointerType *PT = dyn_cast<PointerType>(Ty);
2137     return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2138            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2139   }
2140
2141   case IITDescriptor::Struct: {
2142     StructType *ST = dyn_cast<StructType>(Ty);
2143     if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2144       return true;
2145
2146     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2147       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2148         return true;
2149     return false;
2150   }
2151
2152   case IITDescriptor::Argument:
2153     // Two cases here - If this is the second occurrence of an argument, verify
2154     // that the later instance matches the previous instance.
2155     if (D.getArgumentNumber() < ArgTys.size())
2156       return Ty != ArgTys[D.getArgumentNumber()];
2157
2158     // Otherwise, if this is the first instance of an argument, record it and
2159     // verify the "Any" kind.
2160     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2161     ArgTys.push_back(Ty);
2162
2163     switch (D.getArgumentKind()) {
2164     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2165     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2166     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2167     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2168     }
2169     llvm_unreachable("all argument kinds not covered");
2170
2171   case IITDescriptor::ExtendVecArgument:
2172     // This may only be used when referring to a previous vector argument.
2173     return D.getArgumentNumber() >= ArgTys.size() ||
2174            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2175            VectorType::getExtendedElementVectorType(
2176                        cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2177
2178   case IITDescriptor::TruncVecArgument:
2179     // This may only be used when referring to a previous vector argument.
2180     return D.getArgumentNumber() >= ArgTys.size() ||
2181            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2182            VectorType::getTruncatedElementVectorType(
2183                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2184   }
2185   llvm_unreachable("unhandled");
2186 }
2187
2188 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2189 ///
2190 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2191   Function *IF = CI.getCalledFunction();
2192   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2193           IF);
2194
2195   // Verify that the intrinsic prototype lines up with what the .td files
2196   // describe.
2197   FunctionType *IFTy = IF->getFunctionType();
2198   Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
2199
2200   SmallVector<Intrinsic::IITDescriptor, 8> Table;
2201   getIntrinsicInfoTableEntries(ID, Table);
2202   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2203
2204   SmallVector<Type *, 4> ArgTys;
2205   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2206           "Intrinsic has incorrect return type!", IF);
2207   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2208     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2209             "Intrinsic has incorrect argument type!", IF);
2210   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2211
2212   // Now that we have the intrinsic ID and the actual argument types (and we
2213   // know they are legal for the intrinsic!) get the intrinsic name through the
2214   // usual means.  This allows us to verify the mangling of argument types into
2215   // the name.
2216   Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2217           "Intrinsic name not mangled correctly for type arguments!", IF);
2218
2219   // If the intrinsic takes MDNode arguments, verify that they are either global
2220   // or are local to *this* function.
2221   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2222     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2223       visitMDNode(*MD, CI.getParent()->getParent());
2224
2225   switch (ID) {
2226   default:
2227     break;
2228   case Intrinsic::ctlz:  // llvm.ctlz
2229   case Intrinsic::cttz:  // llvm.cttz
2230     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2231             "is_zero_undef argument of bit counting intrinsics must be a "
2232             "constant int", &CI);
2233     break;
2234   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2235     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2236                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2237     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2238     Assert1(MD->getNumOperands() == 1,
2239                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2240     if (!DisableDebugInfoVerifier)
2241       Finder.processDeclare(cast<DbgDeclareInst>(&CI));
2242   } break;
2243   case Intrinsic::dbg_value: { //llvm.dbg.value
2244     if (!DisableDebugInfoVerifier) {
2245       Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2246               "invalid llvm.dbg.value intrinsic call 1", &CI);
2247       Finder.processValue(cast<DbgValueInst>(&CI));
2248     }
2249     break;
2250   }
2251   case Intrinsic::memcpy:
2252   case Intrinsic::memmove:
2253   case Intrinsic::memset:
2254     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2255             "alignment argument of memory intrinsics must be a constant int",
2256             &CI);
2257     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2258             "isvolatile argument of memory intrinsics must be a constant int",
2259             &CI);
2260     break;
2261   case Intrinsic::gcroot:
2262   case Intrinsic::gcwrite:
2263   case Intrinsic::gcread:
2264     if (ID == Intrinsic::gcroot) {
2265       AllocaInst *AI =
2266         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2267       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2268       Assert1(isa<Constant>(CI.getArgOperand(1)),
2269               "llvm.gcroot parameter #2 must be a constant.", &CI);
2270       if (!AI->getType()->getElementType()->isPointerTy()) {
2271         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2272                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2273                 "or argument #2 must be a non-null constant.", &CI);
2274       }
2275     }
2276
2277     Assert1(CI.getParent()->getParent()->hasGC(),
2278             "Enclosing function does not use GC.", &CI);
2279     break;
2280   case Intrinsic::init_trampoline:
2281     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2282             "llvm.init_trampoline parameter #2 must resolve to a function.",
2283             &CI);
2284     break;
2285   case Intrinsic::prefetch:
2286     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2287             isa<ConstantInt>(CI.getArgOperand(2)) &&
2288             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2289             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2290             "invalid arguments to llvm.prefetch",
2291             &CI);
2292     break;
2293   case Intrinsic::stackprotector:
2294     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2295             "llvm.stackprotector parameter #2 must resolve to an alloca.",
2296             &CI);
2297     break;
2298   case Intrinsic::lifetime_start:
2299   case Intrinsic::lifetime_end:
2300   case Intrinsic::invariant_start:
2301     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2302             "size argument of memory use markers must be a constant integer",
2303             &CI);
2304     break;
2305   case Intrinsic::invariant_end:
2306     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2307             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2308     break;
2309   }
2310 }
2311
2312 void Verifier::verifyDebugInfo(Module &M) {
2313   // Verify Debug Info.
2314   if (!DisableDebugInfoVerifier) {
2315     Finder.processModule(M);
2316
2317     for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2318          E = Finder.compile_unit_end(); I != E; ++I)
2319       Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2320     for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2321          E = Finder.subprogram_end(); I != E; ++I)
2322       Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2323     for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2324          E = Finder.global_variable_end(); I != E; ++I)
2325       Assert1(DIGlobalVariable(*I).Verify(),
2326               "DIGlobalVariable does not Verify!", *I);
2327     for (DebugInfoFinder::iterator I = Finder.type_begin(),
2328          E = Finder.type_end(); I != E; ++I)
2329       Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2330     for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2331          E = Finder.scope_end(); I != E; ++I)
2332       Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2333   }
2334 }
2335
2336 //===----------------------------------------------------------------------===//
2337 //  Implement the public interfaces to this file...
2338 //===----------------------------------------------------------------------===//
2339
2340 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2341   return new Verifier(action);
2342 }
2343
2344
2345 /// verifyFunction - Check a function for errors, printing messages on stderr.
2346 /// Return true if the function is corrupt.
2347 ///
2348 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2349   Function &F = const_cast<Function&>(f);
2350   assert(!F.isDeclaration() && "Cannot verify external functions");
2351
2352   FunctionPassManager FPM(F.getParent());
2353   Verifier *V = new Verifier(action);
2354   FPM.add(V);
2355   FPM.run(F);
2356   return V->Broken;
2357 }
2358
2359 /// verifyModule - Check a module for errors, printing messages on stderr.
2360 /// Return true if the module is corrupt.
2361 ///
2362 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2363                         std::string *ErrorInfo) {
2364   PassManager PM;
2365   Verifier *V = new Verifier(action);
2366   PM.add(V);
2367   PM.run(const_cast<Module&>(M));
2368
2369   if (ErrorInfo && V->Broken)
2370     *ErrorInfo = V->MessagesStr.str();
2371   return V->Broken;
2372 }