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