1//===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the function verifier interface, that can be used for some
11// sanity checking of input to the system.
12//
13// Note that this does not provide full `Java style' security and verifications,
14// instead it just tries to ensure that code is well-formed.
15//
16//  * Both of a binary operator's parameters are of the same type
17//  * Verify that the indices of mem access instructions match other operands
18//  * Verify that arithmetic and other things are only performed on first-class
19//    types.  Verify that shifts & logicals only happen on integrals f.e.
20//  * All of the constants in a switch statement are of the correct type
21//  * The code is in valid SSA form
22//  * It should be illegal to put a label into any other type (like a structure)
23//    or to return one. [except constant arrays!]
24//  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25//  * PHI nodes must have an entry for each predecessor, with no extras.
26//  * PHI nodes must be the first thing in a basic block, all grouped together
27//  * PHI nodes must have at least one entry
28//  * All basic blocks should only end with terminator insts, not contain them
29//  * The entry node to a function must not have predecessors
30//  * All Instructions must be embedded into a basic block
31//  * Functions cannot take a void-typed parameter
32//  * Verify that a function's argument list agrees with it's declared type.
33//  * It is illegal to specify a name for a void value.
34//  * It is illegal to have a internal global value with no initializer
35//  * It is illegal to have a ret instruction that returns a value that does not
36//    agree with the function return value type.
37//  * Function call argument types match the function prototype
38//  * A landing pad is defined by a landingpad instruction, and can be jumped to
39//    only by the unwind edge of an invoke instruction.
40//  * A landingpad instruction must be the first non-PHI instruction in the
41//    block.
42//  * All landingpad instructions must use the same personality function with
43//    the same function.
44//  * All other things that are tested by asserts spread about the code...
45//
46//===----------------------------------------------------------------------===//
47
48#include "llvm/Analysis/Verifier.h"
49#include "llvm/CallingConv.h"
50#include "llvm/Constants.h"
51#include "llvm/DerivedTypes.h"
52#include "llvm/InlineAsm.h"
53#include "llvm/IntrinsicInst.h"
54#include "llvm/Metadata.h"
55#include "llvm/Module.h"
56#include "llvm/Pass.h"
57#include "llvm/PassManager.h"
58#include "llvm/Analysis/Dominators.h"
59#include "llvm/Assembly/Writer.h"
60#include "llvm/CodeGen/ValueTypes.h"
61#include "llvm/Support/CallSite.h"
62#include "llvm/Support/CFG.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/InstVisitor.h"
65#include "llvm/ADT/SetVector.h"
66#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/SmallVector.h"
68#include "llvm/ADT/StringExtras.h"
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/Support/ErrorHandling.h"
71#include "llvm/Support/raw_ostream.h"
72#include <algorithm>
73#include <cstdarg>
74using namespace llvm;
75
76namespace {  // Anonymous namespace for class
77  struct PreVerifier : public FunctionPass {
78    static char ID; // Pass ID, replacement for typeid
79
80    PreVerifier() : FunctionPass(ID) {
81      initializePreVerifierPass(*PassRegistry::getPassRegistry());
82    }
83
84    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85      AU.setPreservesAll();
86    }
87
88    // Check that the prerequisites for successful DominatorTree construction
89    // are satisfied.
90    bool runOnFunction(Function &F) {
91      bool Broken = false;
92
93      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
94        if (I->empty() || !I->back().isTerminator()) {
95          dbgs() << "Basic Block in function '" << F.getName()
96                 << "' does not have terminator!\n";
97          WriteAsOperand(dbgs(), I, true);
98          dbgs() << "\n";
99          Broken = true;
100        }
101      }
102
103      if (Broken)
104        report_fatal_error("Broken module, no Basic Block terminator!");
105
106      return false;
107    }
108  };
109}
110
111char PreVerifier::ID = 0;
112INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
113                false, false)
114static char &PreVerifyID = PreVerifier::ID;
115
116namespace {
117  struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
118    static char ID; // Pass ID, replacement for typeid
119    bool Broken;          // Is this module found to be broken?
120    bool RealPass;        // Are we not being run by a PassManager?
121    VerifierFailureAction action;
122                          // What to do if verification fails.
123    Module *Mod;          // Module we are verifying right now
124    LLVMContext *Context; // Context within which we are verifying
125    DominatorTree *DT;    // Dominator Tree, caution can be null!
126
127    std::string Messages;
128    raw_string_ostream MessagesStr;
129
130    /// InstInThisBlock - when verifying a basic block, keep track of all of the
131    /// instructions we have seen so far.  This allows us to do efficient
132    /// dominance checks for the case when an instruction has an operand that is
133    /// an instruction in the same block.
134    SmallPtrSet<Instruction*, 16> InstsInThisBlock;
135
136    /// MDNodes - keep track of the metadata nodes that have been checked
137    /// already.
138    SmallPtrSet<MDNode *, 32> MDNodes;
139
140    /// PersonalityFn - The personality function referenced by the
141    /// LandingPadInsts. All LandingPadInsts within the same function must use
142    /// the same personality function.
143    const Value *PersonalityFn;
144
145    Verifier()
146      : FunctionPass(ID), Broken(false), RealPass(true),
147        action(AbortProcessAction), Mod(0), Context(0), DT(0),
148        MessagesStr(Messages), PersonalityFn(0) {
149      initializeVerifierPass(*PassRegistry::getPassRegistry());
150    }
151    explicit Verifier(VerifierFailureAction ctn)
152      : FunctionPass(ID), Broken(false), RealPass(true), action(ctn), Mod(0),
153        Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
154      initializeVerifierPass(*PassRegistry::getPassRegistry());
155    }
156
157    bool doInitialization(Module &M) {
158      Mod = &M;
159      Context = &M.getContext();
160
161      // If this is a real pass, in a pass manager, we must abort before
162      // returning back to the pass manager, or else the pass manager may try to
163      // run other passes on the broken module.
164      if (RealPass)
165        return abortIfBroken();
166      return false;
167    }
168
169    bool runOnFunction(Function &F) {
170      // Get dominator information if we are being run by PassManager
171      if (RealPass) DT = &getAnalysis<DominatorTree>();
172
173      Mod = F.getParent();
174      if (!Context) Context = &F.getContext();
175
176      visit(F);
177      InstsInThisBlock.clear();
178      PersonalityFn = 0;
179
180      // If this is a real pass, in a pass manager, we must abort before
181      // returning back to the pass manager, or else the pass manager may try to
182      // run other passes on the broken module.
183      if (RealPass)
184        return abortIfBroken();
185
186      return false;
187    }
188
189    bool doFinalization(Module &M) {
190      // Scan through, checking all of the external function's linkage now...
191      for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
192        visitGlobalValue(*I);
193
194        // Check to make sure function prototypes are okay.
195        if (I->isDeclaration()) visitFunction(*I);
196      }
197
198      for (Module::global_iterator I = M.global_begin(), E = M.global_end();
199           I != E; ++I)
200        visitGlobalVariable(*I);
201
202      for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
203           I != E; ++I)
204        visitGlobalAlias(*I);
205
206      for (Module::named_metadata_iterator I = M.named_metadata_begin(),
207           E = M.named_metadata_end(); I != E; ++I)
208        visitNamedMDNode(*I);
209
210      // If the module is broken, abort at this time.
211      return abortIfBroken();
212    }
213
214    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
215      AU.setPreservesAll();
216      AU.addRequiredID(PreVerifyID);
217      if (RealPass)
218        AU.addRequired<DominatorTree>();
219    }
220
221    /// abortIfBroken - If the module is broken and we are supposed to abort on
222    /// this condition, do so.
223    ///
224    bool abortIfBroken() {
225      if (!Broken) return false;
226      MessagesStr << "Broken module found, ";
227      switch (action) {
228      default: llvm_unreachable("Unknown action");
229      case AbortProcessAction:
230        MessagesStr << "compilation aborted!\n";
231        dbgs() << MessagesStr.str();
232        // Client should choose different reaction if abort is not desired
233        abort();
234      case PrintMessageAction:
235        MessagesStr << "verification continues.\n";
236        dbgs() << MessagesStr.str();
237        return false;
238      case ReturnStatusAction:
239        MessagesStr << "compilation terminated.\n";
240        return true;
241      }
242    }
243
244
245    // Verification methods...
246    void visitGlobalValue(GlobalValue &GV);
247    void visitGlobalVariable(GlobalVariable &GV);
248    void visitGlobalAlias(GlobalAlias &GA);
249    void visitNamedMDNode(NamedMDNode &NMD);
250    void visitMDNode(MDNode &MD, Function *F);
251    void visitFunction(Function &F);
252    void visitBasicBlock(BasicBlock &BB);
253    using InstVisitor<Verifier>::visit;
254
255    void visit(Instruction &I);
256
257    void visitTruncInst(TruncInst &I);
258    void visitZExtInst(ZExtInst &I);
259    void visitSExtInst(SExtInst &I);
260    void visitFPTruncInst(FPTruncInst &I);
261    void visitFPExtInst(FPExtInst &I);
262    void visitFPToUIInst(FPToUIInst &I);
263    void visitFPToSIInst(FPToSIInst &I);
264    void visitUIToFPInst(UIToFPInst &I);
265    void visitSIToFPInst(SIToFPInst &I);
266    void visitIntToPtrInst(IntToPtrInst &I);
267    void visitPtrToIntInst(PtrToIntInst &I);
268    void visitBitCastInst(BitCastInst &I);
269    void visitPHINode(PHINode &PN);
270    void visitBinaryOperator(BinaryOperator &B);
271    void visitICmpInst(ICmpInst &IC);
272    void visitFCmpInst(FCmpInst &FC);
273    void visitExtractElementInst(ExtractElementInst &EI);
274    void visitInsertElementInst(InsertElementInst &EI);
275    void visitShuffleVectorInst(ShuffleVectorInst &EI);
276    void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
277    void visitCallInst(CallInst &CI);
278    void visitInvokeInst(InvokeInst &II);
279    void visitGetElementPtrInst(GetElementPtrInst &GEP);
280    void visitLoadInst(LoadInst &LI);
281    void visitStoreInst(StoreInst &SI);
282    void visitInstruction(Instruction &I);
283    void visitTerminatorInst(TerminatorInst &I);
284    void visitBranchInst(BranchInst &BI);
285    void visitReturnInst(ReturnInst &RI);
286    void visitSwitchInst(SwitchInst &SI);
287    void visitIndirectBrInst(IndirectBrInst &BI);
288    void visitSelectInst(SelectInst &SI);
289    void visitUserOp1(Instruction &I);
290    void visitUserOp2(Instruction &I) { visitUserOp1(I); }
291    void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
292    void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
293    void visitAtomicRMWInst(AtomicRMWInst &RMWI);
294    void visitFenceInst(FenceInst &FI);
295    void visitAllocaInst(AllocaInst &AI);
296    void visitExtractValueInst(ExtractValueInst &EVI);
297    void visitInsertValueInst(InsertValueInst &IVI);
298    void visitLandingPadInst(LandingPadInst &LPI);
299
300    void VerifyCallSite(CallSite CS);
301    bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
302                          int VT, unsigned ArgNo, std::string &Suffix);
303    void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
304                                  unsigned RetNum, unsigned ParamNum, ...);
305    void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
306                              bool isReturnValue, const Value *V);
307    void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
308                             const Value *V);
309
310    void WriteValue(const Value *V) {
311      if (!V) return;
312      if (isa<Instruction>(V)) {
313        MessagesStr << *V << '\n';
314      } else {
315        WriteAsOperand(MessagesStr, V, true, Mod);
316        MessagesStr << '\n';
317      }
318    }
319
320    void WriteType(Type *T) {
321      if (!T) return;
322      MessagesStr << ' ' << *T;
323    }
324
325
326    // CheckFailed - A check failed, so print out the condition and the message
327    // that failed.  This provides a nice place to put a breakpoint if you want
328    // to see why something is not correct.
329    void CheckFailed(const Twine &Message,
330                     const Value *V1 = 0, const Value *V2 = 0,
331                     const Value *V3 = 0, const Value *V4 = 0) {
332      MessagesStr << Message.str() << "\n";
333      WriteValue(V1);
334      WriteValue(V2);
335      WriteValue(V3);
336      WriteValue(V4);
337      Broken = true;
338    }
339
340    void CheckFailed(const Twine &Message, const Value *V1,
341                     Type *T2, const Value *V3 = 0) {
342      MessagesStr << Message.str() << "\n";
343      WriteValue(V1);
344      WriteType(T2);
345      WriteValue(V3);
346      Broken = true;
347    }
348
349    void CheckFailed(const Twine &Message, Type *T1,
350                     Type *T2 = 0, Type *T3 = 0) {
351      MessagesStr << Message.str() << "\n";
352      WriteType(T1);
353      WriteType(T2);
354      WriteType(T3);
355      Broken = true;
356    }
357  };
358} // End anonymous namespace
359
360char Verifier::ID = 0;
361INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
362INITIALIZE_PASS_DEPENDENCY(PreVerifier)
363INITIALIZE_PASS_DEPENDENCY(DominatorTree)
364INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
365
366// Assert - We know that cond should be true, if not print an error message.
367#define Assert(C, M) \
368  do { if (!(C)) { CheckFailed(M); return; } } while (0)
369#define Assert1(C, M, V1) \
370  do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
371#define Assert2(C, M, V1, V2) \
372  do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
373#define Assert3(C, M, V1, V2, V3) \
374  do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
375#define Assert4(C, M, V1, V2, V3, V4) \
376  do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
377
378void Verifier::visit(Instruction &I) {
379  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
380    Assert1(I.getOperand(i) != 0, "Operand is null", &I);
381  InstVisitor<Verifier>::visit(I);
382}
383
384
385void Verifier::visitGlobalValue(GlobalValue &GV) {
386  Assert1(!GV.isDeclaration() ||
387          GV.isMaterializable() ||
388          GV.hasExternalLinkage() ||
389          GV.hasDLLImportLinkage() ||
390          GV.hasExternalWeakLinkage() ||
391          (isa<GlobalAlias>(GV) &&
392           (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
393  "Global is external, but doesn't have external or dllimport or weak linkage!",
394          &GV);
395
396  Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
397          "Global is marked as dllimport, but not external", &GV);
398
399  Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
400          "Only global variables can have appending linkage!", &GV);
401
402  if (GV.hasAppendingLinkage()) {
403    GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
404    Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
405            "Only global arrays can have appending linkage!", GVar);
406  }
407
408  Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
409          "linker_private_weak_def_auto can only have default visibility!",
410          &GV);
411}
412
413void Verifier::visitGlobalVariable(GlobalVariable &GV) {
414  if (GV.hasInitializer()) {
415    Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
416            "Global variable initializer type does not match global "
417            "variable type!", &GV);
418
419    // If the global has common linkage, it must have a zero initializer and
420    // cannot be constant.
421    if (GV.hasCommonLinkage()) {
422      Assert1(GV.getInitializer()->isNullValue(),
423              "'common' global must have a zero initializer!", &GV);
424      Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
425              &GV);
426    }
427  } else {
428    Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
429            GV.hasExternalWeakLinkage(),
430            "invalid linkage type for global declaration", &GV);
431  }
432
433  if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
434                       GV.getName() == "llvm.global_dtors")) {
435    Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
436            "invalid linkage for intrinsic global variable", &GV);
437    // Don't worry about emitting an error for it not being an array,
438    // visitGlobalValue will complain on appending non-array.
439    if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
440      StructType *STy = dyn_cast<StructType>(ATy->getElementType());
441      PointerType *FuncPtrTy =
442          FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
443      Assert1(STy && STy->getNumElements() == 2 &&
444              STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
445              STy->getTypeAtIndex(1) == FuncPtrTy,
446              "wrong type for intrinsic global variable", &GV);
447    }
448  }
449
450  visitGlobalValue(GV);
451}
452
453void Verifier::visitGlobalAlias(GlobalAlias &GA) {
454  Assert1(!GA.getName().empty(),
455          "Alias name cannot be empty!", &GA);
456  Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
457          GA.hasWeakLinkage(),
458          "Alias should have external or external weak linkage!", &GA);
459  Assert1(GA.getAliasee(),
460          "Aliasee cannot be NULL!", &GA);
461  Assert1(GA.getType() == GA.getAliasee()->getType(),
462          "Alias and aliasee types should match!", &GA);
463  Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
464
465  if (!isa<GlobalValue>(GA.getAliasee())) {
466    const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
467    Assert1(CE &&
468            (CE->getOpcode() == Instruction::BitCast ||
469             CE->getOpcode() == Instruction::GetElementPtr) &&
470            isa<GlobalValue>(CE->getOperand(0)),
471            "Aliasee should be either GlobalValue or bitcast of GlobalValue",
472            &GA);
473  }
474
475  const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
476  Assert1(Aliasee,
477          "Aliasing chain should end with function or global variable", &GA);
478
479  visitGlobalValue(GA);
480}
481
482void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
483  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
484    MDNode *MD = NMD.getOperand(i);
485    if (!MD)
486      continue;
487
488    Assert1(!MD->isFunctionLocal(),
489            "Named metadata operand cannot be function local!", MD);
490    visitMDNode(*MD, 0);
491  }
492}
493
494void Verifier::visitMDNode(MDNode &MD, Function *F) {
495  // Only visit each node once.  Metadata can be mutually recursive, so this
496  // avoids infinite recursion here, as well as being an optimization.
497  if (!MDNodes.insert(&MD))
498    return;
499
500  for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
501    Value *Op = MD.getOperand(i);
502    if (!Op)
503      continue;
504    if (isa<Constant>(Op) || isa<MDString>(Op))
505      continue;
506    if (MDNode *N = dyn_cast<MDNode>(Op)) {
507      Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
508              "Global metadata operand cannot be function local!", &MD, N);
509      visitMDNode(*N, F);
510      continue;
511    }
512    Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
513
514    // If this was an instruction, bb, or argument, verify that it is in the
515    // function that we expect.
516    Function *ActualF = 0;
517    if (Instruction *I = dyn_cast<Instruction>(Op))
518      ActualF = I->getParent()->getParent();
519    else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
520      ActualF = BB->getParent();
521    else if (Argument *A = dyn_cast<Argument>(Op))
522      ActualF = A->getParent();
523    assert(ActualF && "Unimplemented function local metadata case!");
524
525    Assert2(ActualF == F, "function-local metadata used in wrong function",
526            &MD, Op);
527  }
528}
529
530// VerifyParameterAttrs - Check the given attributes for an argument or return
531// value of the specified type.  The value V is printed in error messages.
532void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
533                                    bool isReturnValue, const Value *V) {
534  if (Attrs == Attribute::None)
535    return;
536
537  Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
538  Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
539          " only applies to the function!", V);
540
541  if (isReturnValue) {
542    Attributes RetI = Attrs & Attribute::ParameterOnly;
543    Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
544            " does not apply to return values!", V);
545  }
546
547  for (unsigned i = 0;
548       i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
549    Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
550    Assert1(!(MutI & (MutI - 1)), "Attributes " +
551            Attribute::getAsString(MutI) + " are incompatible!", V);
552  }
553
554  Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
555  Assert1(!TypeI, "Wrong type for attribute " +
556          Attribute::getAsString(TypeI), V);
557
558  Attributes ByValI = Attrs & Attribute::ByVal;
559  if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
560    Assert1(!ByValI || PTy->getElementType()->isSized(),
561            "Attribute " + Attribute::getAsString(ByValI) +
562            " does not support unsized types!", V);
563  } else {
564    Assert1(!ByValI,
565            "Attribute " + Attribute::getAsString(ByValI) +
566            " only applies to parameters with pointer type!", V);
567  }
568}
569
570// VerifyFunctionAttrs - Check parameter attributes against a function type.
571// The value V is printed in error messages.
572void Verifier::VerifyFunctionAttrs(FunctionType *FT,
573                                   const AttrListPtr &Attrs,
574                                   const Value *V) {
575  if (Attrs.isEmpty())
576    return;
577
578  bool SawNest = false;
579
580  for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
581    const AttributeWithIndex &Attr = Attrs.getSlot(i);
582
583    Type *Ty;
584    if (Attr.Index == 0)
585      Ty = FT->getReturnType();
586    else if (Attr.Index-1 < FT->getNumParams())
587      Ty = FT->getParamType(Attr.Index-1);
588    else
589      break;  // VarArgs attributes, verified elsewhere.
590
591    VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
592
593    if (Attr.Attrs & Attribute::Nest) {
594      Assert1(!SawNest, "More than one parameter has attribute nest!", V);
595      SawNest = true;
596    }
597
598    if (Attr.Attrs & Attribute::StructRet)
599      Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
600  }
601
602  Attributes FAttrs = Attrs.getFnAttributes();
603  Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
604  Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
605          " does not apply to the function!", V);
606
607  for (unsigned i = 0;
608       i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
609    Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
610    Assert1(!(MutI & (MutI - 1)), "Attributes " +
611            Attribute::getAsString(MutI) + " are incompatible!", V);
612  }
613}
614
615static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
616  if (Attrs.isEmpty())
617    return true;
618
619  unsigned LastSlot = Attrs.getNumSlots() - 1;
620  unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
621  if (LastIndex <= Params
622      || (LastIndex == (unsigned)~0
623          && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
624    return true;
625
626  return false;
627}
628
629// visitFunction - Verify that a function is ok.
630//
631void Verifier::visitFunction(Function &F) {
632  // Check function arguments.
633  FunctionType *FT = F.getFunctionType();
634  unsigned NumArgs = F.arg_size();
635
636  Assert1(Context == &F.getContext(),
637          "Function context does not match Module context!", &F);
638
639  Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
640  Assert2(FT->getNumParams() == NumArgs,
641          "# formal arguments must match # of arguments for function type!",
642          &F, FT);
643  Assert1(F.getReturnType()->isFirstClassType() ||
644          F.getReturnType()->isVoidTy() ||
645          F.getReturnType()->isStructTy(),
646          "Functions cannot return aggregate values!", &F);
647
648  Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
649          "Invalid struct return type!", &F);
650
651  const AttrListPtr &Attrs = F.getAttributes();
652
653  Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
654          "Attributes after last parameter!", &F);
655
656  // Check function attributes.
657  VerifyFunctionAttrs(FT, Attrs, &F);
658
659  // Check that this function meets the restrictions on this calling convention.
660  switch (F.getCallingConv()) {
661  default:
662    break;
663  case CallingConv::C:
664    break;
665  case CallingConv::Fast:
666  case CallingConv::Cold:
667  case CallingConv::X86_FastCall:
668  case CallingConv::X86_ThisCall:
669  case CallingConv::PTX_Kernel:
670  case CallingConv::PTX_Device:
671    Assert1(!F.isVarArg(),
672            "Varargs functions must have C calling conventions!", &F);
673    break;
674  }
675
676  bool isLLVMdotName = F.getName().size() >= 5 &&
677                       F.getName().substr(0, 5) == "llvm.";
678
679  // Check that the argument values match the function type for this function...
680  unsigned i = 0;
681  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
682       I != E; ++I, ++i) {
683    Assert2(I->getType() == FT->getParamType(i),
684            "Argument value does not match function argument type!",
685            I, FT->getParamType(i));
686    Assert1(I->getType()->isFirstClassType(),
687            "Function arguments must have first-class types!", I);
688    if (!isLLVMdotName)
689      Assert2(!I->getType()->isMetadataTy(),
690              "Function takes metadata but isn't an intrinsic", I, &F);
691  }
692
693  if (F.isMaterializable()) {
694    // Function has a body somewhere we can't see.
695  } else if (F.isDeclaration()) {
696    Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
697            F.hasExternalWeakLinkage(),
698            "invalid linkage type for function declaration", &F);
699  } else {
700    // Verify that this function (which has a body) is not named "llvm.*".  It
701    // is not legal to define intrinsics.
702    Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
703
704    // Check the entry node
705    BasicBlock *Entry = &F.getEntryBlock();
706    Assert1(pred_begin(Entry) == pred_end(Entry),
707            "Entry block to function must not have predecessors!", Entry);
708
709    // The address of the entry block cannot be taken, unless it is dead.
710    if (Entry->hasAddressTaken()) {
711      Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
712              "blockaddress may not be used with the entry block!", Entry);
713    }
714  }
715
716  // If this function is actually an intrinsic, verify that it is only used in
717  // direct call/invokes, never having its "address taken".
718  if (F.getIntrinsicID()) {
719    const User *U;
720    if (F.hasAddressTaken(&U))
721      Assert1(0, "Invalid user of intrinsic instruction!", U);
722  }
723}
724
725// verifyBasicBlock - Verify that a basic block is well formed...
726//
727void Verifier::visitBasicBlock(BasicBlock &BB) {
728  InstsInThisBlock.clear();
729
730  // Ensure that basic blocks have terminators!
731  Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
732
733  // Check constraints that this basic block imposes on all of the PHI nodes in
734  // it.
735  if (isa<PHINode>(BB.front())) {
736    SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
737    SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
738    std::sort(Preds.begin(), Preds.end());
739    PHINode *PN;
740    for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
741      // Ensure that PHI nodes have at least one entry!
742      Assert1(PN->getNumIncomingValues() != 0,
743              "PHI nodes must have at least one entry.  If the block is dead, "
744              "the PHI should be removed!", PN);
745      Assert1(PN->getNumIncomingValues() == Preds.size(),
746              "PHINode should have one entry for each predecessor of its "
747              "parent basic block!", PN);
748
749      // Get and sort all incoming values in the PHI node...
750      Values.clear();
751      Values.reserve(PN->getNumIncomingValues());
752      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
753        Values.push_back(std::make_pair(PN->getIncomingBlock(i),
754                                        PN->getIncomingValue(i)));
755      std::sort(Values.begin(), Values.end());
756
757      for (unsigned i = 0, e = Values.size(); i != e; ++i) {
758        // Check to make sure that if there is more than one entry for a
759        // particular basic block in this PHI node, that the incoming values are
760        // all identical.
761        //
762        Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
763                Values[i].second == Values[i-1].second,
764                "PHI node has multiple entries for the same basic block with "
765                "different incoming values!", PN, Values[i].first,
766                Values[i].second, Values[i-1].second);
767
768        // Check to make sure that the predecessors and PHI node entries are
769        // matched up.
770        Assert3(Values[i].first == Preds[i],
771                "PHI node entries do not match predecessors!", PN,
772                Values[i].first, Preds[i]);
773      }
774    }
775  }
776}
777
778void Verifier::visitTerminatorInst(TerminatorInst &I) {
779  // Ensure that terminators only exist at the end of the basic block.
780  Assert1(&I == I.getParent()->getTerminator(),
781          "Terminator found in the middle of a basic block!", I.getParent());
782  visitInstruction(I);
783}
784
785void Verifier::visitBranchInst(BranchInst &BI) {
786  if (BI.isConditional()) {
787    Assert2(BI.getCondition()->getType()->isIntegerTy(1),
788            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
789  }
790  visitTerminatorInst(BI);
791}
792
793void Verifier::visitReturnInst(ReturnInst &RI) {
794  Function *F = RI.getParent()->getParent();
795  unsigned N = RI.getNumOperands();
796  if (F->getReturnType()->isVoidTy())
797    Assert2(N == 0,
798            "Found return instr that returns non-void in Function of void "
799            "return type!", &RI, F->getReturnType());
800  else
801    Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
802            "Function return type does not match operand "
803            "type of return inst!", &RI, F->getReturnType());
804
805  // Check to make sure that the return value has necessary properties for
806  // terminators...
807  visitTerminatorInst(RI);
808}
809
810void Verifier::visitSwitchInst(SwitchInst &SI) {
811  // Check to make sure that all of the constants in the switch instruction
812  // have the same type as the switched-on value.
813  Type *SwitchTy = SI.getCondition()->getType();
814  SmallPtrSet<ConstantInt*, 32> Constants;
815  for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
816    Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
817            "Switch constants must all be same type as switch value!", &SI);
818    Assert2(Constants.insert(SI.getCaseValue(i)),
819            "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
820  }
821
822  visitTerminatorInst(SI);
823}
824
825void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
826  Assert1(BI.getAddress()->getType()->isPointerTy(),
827          "Indirectbr operand must have pointer type!", &BI);
828  for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
829    Assert1(BI.getDestination(i)->getType()->isLabelTy(),
830            "Indirectbr destinations must all have pointer type!", &BI);
831
832  visitTerminatorInst(BI);
833}
834
835void Verifier::visitSelectInst(SelectInst &SI) {
836  Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
837                                          SI.getOperand(2)),
838          "Invalid operands for select instruction!", &SI);
839
840  Assert1(SI.getTrueValue()->getType() == SI.getType(),
841          "Select values must have same type as select instruction!", &SI);
842  visitInstruction(SI);
843}
844
845/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
846/// a pass, if any exist, it's an error.
847///
848void Verifier::visitUserOp1(Instruction &I) {
849  Assert1(0, "User-defined operators should not live outside of a pass!", &I);
850}
851
852void Verifier::visitTruncInst(TruncInst &I) {
853  // Get the source and destination types
854  Type *SrcTy = I.getOperand(0)->getType();
855  Type *DestTy = I.getType();
856
857  // Get the size of the types in bits, we'll need this later
858  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
859  unsigned DestBitSize = DestTy->getScalarSizeInBits();
860
861  Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
862  Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
863  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
864          "trunc source and destination must both be a vector or neither", &I);
865  Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
866
867  visitInstruction(I);
868}
869
870void Verifier::visitZExtInst(ZExtInst &I) {
871  // Get the source and destination types
872  Type *SrcTy = I.getOperand(0)->getType();
873  Type *DestTy = I.getType();
874
875  // Get the size of the types in bits, we'll need this later
876  Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
877  Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
878  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
879          "zext source and destination must both be a vector or neither", &I);
880  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
881  unsigned DestBitSize = DestTy->getScalarSizeInBits();
882
883  Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
884
885  visitInstruction(I);
886}
887
888void Verifier::visitSExtInst(SExtInst &I) {
889  // Get the source and destination types
890  Type *SrcTy = I.getOperand(0)->getType();
891  Type *DestTy = I.getType();
892
893  // Get the size of the types in bits, we'll need this later
894  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
895  unsigned DestBitSize = DestTy->getScalarSizeInBits();
896
897  Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
898  Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
899  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
900          "sext source and destination must both be a vector or neither", &I);
901  Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
902
903  visitInstruction(I);
904}
905
906void Verifier::visitFPTruncInst(FPTruncInst &I) {
907  // Get the source and destination types
908  Type *SrcTy = I.getOperand(0)->getType();
909  Type *DestTy = I.getType();
910  // Get the size of the types in bits, we'll need this later
911  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
912  unsigned DestBitSize = DestTy->getScalarSizeInBits();
913
914  Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
915  Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
916  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
917          "fptrunc source and destination must both be a vector or neither",&I);
918  Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
919
920  visitInstruction(I);
921}
922
923void Verifier::visitFPExtInst(FPExtInst &I) {
924  // Get the source and destination types
925  Type *SrcTy = I.getOperand(0)->getType();
926  Type *DestTy = I.getType();
927
928  // Get the size of the types in bits, we'll need this later
929  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
930  unsigned DestBitSize = DestTy->getScalarSizeInBits();
931
932  Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
933  Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
934  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
935          "fpext source and destination must both be a vector or neither", &I);
936  Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
937
938  visitInstruction(I);
939}
940
941void Verifier::visitUIToFPInst(UIToFPInst &I) {
942  // Get the source and destination types
943  Type *SrcTy = I.getOperand(0)->getType();
944  Type *DestTy = I.getType();
945
946  bool SrcVec = SrcTy->isVectorTy();
947  bool DstVec = DestTy->isVectorTy();
948
949  Assert1(SrcVec == DstVec,
950          "UIToFP source and dest must both be vector or scalar", &I);
951  Assert1(SrcTy->isIntOrIntVectorTy(),
952          "UIToFP source must be integer or integer vector", &I);
953  Assert1(DestTy->isFPOrFPVectorTy(),
954          "UIToFP result must be FP or FP vector", &I);
955
956  if (SrcVec && DstVec)
957    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
958            cast<VectorType>(DestTy)->getNumElements(),
959            "UIToFP source and dest vector length mismatch", &I);
960
961  visitInstruction(I);
962}
963
964void Verifier::visitSIToFPInst(SIToFPInst &I) {
965  // Get the source and destination types
966  Type *SrcTy = I.getOperand(0)->getType();
967  Type *DestTy = I.getType();
968
969  bool SrcVec = SrcTy->isVectorTy();
970  bool DstVec = DestTy->isVectorTy();
971
972  Assert1(SrcVec == DstVec,
973          "SIToFP source and dest must both be vector or scalar", &I);
974  Assert1(SrcTy->isIntOrIntVectorTy(),
975          "SIToFP source must be integer or integer vector", &I);
976  Assert1(DestTy->isFPOrFPVectorTy(),
977          "SIToFP result must be FP or FP vector", &I);
978
979  if (SrcVec && DstVec)
980    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
981            cast<VectorType>(DestTy)->getNumElements(),
982            "SIToFP source and dest vector length mismatch", &I);
983
984  visitInstruction(I);
985}
986
987void Verifier::visitFPToUIInst(FPToUIInst &I) {
988  // Get the source and destination types
989  Type *SrcTy = I.getOperand(0)->getType();
990  Type *DestTy = I.getType();
991
992  bool SrcVec = SrcTy->isVectorTy();
993  bool DstVec = DestTy->isVectorTy();
994
995  Assert1(SrcVec == DstVec,
996          "FPToUI source and dest must both be vector or scalar", &I);
997  Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
998          &I);
999  Assert1(DestTy->isIntOrIntVectorTy(),
1000          "FPToUI result must be integer or integer vector", &I);
1001
1002  if (SrcVec && DstVec)
1003    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1004            cast<VectorType>(DestTy)->getNumElements(),
1005            "FPToUI source and dest vector length mismatch", &I);
1006
1007  visitInstruction(I);
1008}
1009
1010void Verifier::visitFPToSIInst(FPToSIInst &I) {
1011  // Get the source and destination types
1012  Type *SrcTy = I.getOperand(0)->getType();
1013  Type *DestTy = I.getType();
1014
1015  bool SrcVec = SrcTy->isVectorTy();
1016  bool DstVec = DestTy->isVectorTy();
1017
1018  Assert1(SrcVec == DstVec,
1019          "FPToSI source and dest must both be vector or scalar", &I);
1020  Assert1(SrcTy->isFPOrFPVectorTy(),
1021          "FPToSI source must be FP or FP vector", &I);
1022  Assert1(DestTy->isIntOrIntVectorTy(),
1023          "FPToSI result must be integer or integer vector", &I);
1024
1025  if (SrcVec && DstVec)
1026    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1027            cast<VectorType>(DestTy)->getNumElements(),
1028            "FPToSI source and dest vector length mismatch", &I);
1029
1030  visitInstruction(I);
1031}
1032
1033void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1034  // Get the source and destination types
1035  Type *SrcTy = I.getOperand(0)->getType();
1036  Type *DestTy = I.getType();
1037
1038  Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1039  Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1040
1041  visitInstruction(I);
1042}
1043
1044void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1045  // Get the source and destination types
1046  Type *SrcTy = I.getOperand(0)->getType();
1047  Type *DestTy = I.getType();
1048
1049  Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1050  Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1051
1052  visitInstruction(I);
1053}
1054
1055void Verifier::visitBitCastInst(BitCastInst &I) {
1056  // Get the source and destination types
1057  Type *SrcTy = I.getOperand(0)->getType();
1058  Type *DestTy = I.getType();
1059
1060  // Get the size of the types in bits, we'll need this later
1061  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1062  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1063
1064  // BitCast implies a no-op cast of type only. No bits change.
1065  // However, you can't cast pointers to anything but pointers.
1066  Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1067          "Bitcast requires both operands to be pointer or neither", &I);
1068  Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1069
1070  // Disallow aggregates.
1071  Assert1(!SrcTy->isAggregateType(),
1072          "Bitcast operand must not be aggregate", &I);
1073  Assert1(!DestTy->isAggregateType(),
1074          "Bitcast type must not be aggregate", &I);
1075
1076  visitInstruction(I);
1077}
1078
1079/// visitPHINode - Ensure that a PHI node is well formed.
1080///
1081void Verifier::visitPHINode(PHINode &PN) {
1082  // Ensure that the PHI nodes are all grouped together at the top of the block.
1083  // This can be tested by checking whether the instruction before this is
1084  // either nonexistent (because this is begin()) or is a PHI node.  If not,
1085  // then there is some other instruction before a PHI.
1086  Assert2(&PN == &PN.getParent()->front() ||
1087          isa<PHINode>(--BasicBlock::iterator(&PN)),
1088          "PHI nodes not grouped at top of basic block!",
1089          &PN, PN.getParent());
1090
1091  // Check that all of the values of the PHI node have the same type as the
1092  // result, and that the incoming blocks are really basic blocks.
1093  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1094    Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1095            "PHI node operands are not the same type as the result!", &PN);
1096  }
1097
1098  // All other PHI node constraints are checked in the visitBasicBlock method.
1099
1100  visitInstruction(PN);
1101}
1102
1103void Verifier::VerifyCallSite(CallSite CS) {
1104  Instruction *I = CS.getInstruction();
1105
1106  Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1107          "Called function must be a pointer!", I);
1108  PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1109
1110  Assert1(FPTy->getElementType()->isFunctionTy(),
1111          "Called function is not pointer to function type!", I);
1112  FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1113
1114  // Verify that the correct number of arguments are being passed
1115  if (FTy->isVarArg())
1116    Assert1(CS.arg_size() >= FTy->getNumParams(),
1117            "Called function requires more parameters than were provided!",I);
1118  else
1119    Assert1(CS.arg_size() == FTy->getNumParams(),
1120            "Incorrect number of arguments passed to called function!", I);
1121
1122  // Verify that all arguments to the call match the function type.
1123  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1124    Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1125            "Call parameter type does not match function signature!",
1126            CS.getArgument(i), FTy->getParamType(i), I);
1127
1128  const AttrListPtr &Attrs = CS.getAttributes();
1129
1130  Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1131          "Attributes after last parameter!", I);
1132
1133  // Verify call attributes.
1134  VerifyFunctionAttrs(FTy, Attrs, I);
1135
1136  if (FTy->isVarArg())
1137    // Check attributes on the varargs part.
1138    for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1139      Attributes Attr = Attrs.getParamAttributes(Idx);
1140
1141      VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1142
1143      Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1144      Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1145              " cannot be used for vararg call arguments!", I);
1146    }
1147
1148  // Verify that there's no metadata unless it's a direct call to an intrinsic.
1149  if (CS.getCalledFunction() == 0 ||
1150      !CS.getCalledFunction()->getName().startswith("llvm.")) {
1151    for (FunctionType::param_iterator PI = FTy->param_begin(),
1152           PE = FTy->param_end(); PI != PE; ++PI)
1153      Assert1(!(*PI)->isMetadataTy(),
1154              "Function has metadata parameter but isn't an intrinsic", I);
1155  }
1156
1157  visitInstruction(*I);
1158}
1159
1160void Verifier::visitCallInst(CallInst &CI) {
1161  VerifyCallSite(&CI);
1162
1163  if (Function *F = CI.getCalledFunction())
1164    if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1165      visitIntrinsicFunctionCall(ID, CI);
1166}
1167
1168void Verifier::visitInvokeInst(InvokeInst &II) {
1169  VerifyCallSite(&II);
1170
1171  // Verify that there is a landingpad instruction as the first non-PHI
1172  // instruction of the 'unwind' destination.
1173  Assert1(II.getUnwindDest()->isLandingPad(),
1174          "The unwind destination does not have a landingpad instruction!",&II);
1175
1176  visitTerminatorInst(II);
1177}
1178
1179/// visitBinaryOperator - Check that both arguments to the binary operator are
1180/// of the same type!
1181///
1182void Verifier::visitBinaryOperator(BinaryOperator &B) {
1183  Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1184          "Both operands to a binary operator are not of the same type!", &B);
1185
1186  switch (B.getOpcode()) {
1187  // Check that integer arithmetic operators are only used with
1188  // integral operands.
1189  case Instruction::Add:
1190  case Instruction::Sub:
1191  case Instruction::Mul:
1192  case Instruction::SDiv:
1193  case Instruction::UDiv:
1194  case Instruction::SRem:
1195  case Instruction::URem:
1196    Assert1(B.getType()->isIntOrIntVectorTy(),
1197            "Integer arithmetic operators only work with integral types!", &B);
1198    Assert1(B.getType() == B.getOperand(0)->getType(),
1199            "Integer arithmetic operators must have same type "
1200            "for operands and result!", &B);
1201    break;
1202  // Check that floating-point arithmetic operators are only used with
1203  // floating-point operands.
1204  case Instruction::FAdd:
1205  case Instruction::FSub:
1206  case Instruction::FMul:
1207  case Instruction::FDiv:
1208  case Instruction::FRem:
1209    Assert1(B.getType()->isFPOrFPVectorTy(),
1210            "Floating-point arithmetic operators only work with "
1211            "floating-point types!", &B);
1212    Assert1(B.getType() == B.getOperand(0)->getType(),
1213            "Floating-point arithmetic operators must have same type "
1214            "for operands and result!", &B);
1215    break;
1216  // Check that logical operators are only used with integral operands.
1217  case Instruction::And:
1218  case Instruction::Or:
1219  case Instruction::Xor:
1220    Assert1(B.getType()->isIntOrIntVectorTy(),
1221            "Logical operators only work with integral types!", &B);
1222    Assert1(B.getType() == B.getOperand(0)->getType(),
1223            "Logical operators must have same type for operands and result!",
1224            &B);
1225    break;
1226  case Instruction::Shl:
1227  case Instruction::LShr:
1228  case Instruction::AShr:
1229    Assert1(B.getType()->isIntOrIntVectorTy(),
1230            "Shifts only work with integral types!", &B);
1231    Assert1(B.getType() == B.getOperand(0)->getType(),
1232            "Shift return type must be same as operands!", &B);
1233    break;
1234  default:
1235    llvm_unreachable("Unknown BinaryOperator opcode!");
1236  }
1237
1238  visitInstruction(B);
1239}
1240
1241void Verifier::visitICmpInst(ICmpInst &IC) {
1242  // Check that the operands are the same type
1243  Type *Op0Ty = IC.getOperand(0)->getType();
1244  Type *Op1Ty = IC.getOperand(1)->getType();
1245  Assert1(Op0Ty == Op1Ty,
1246          "Both operands to ICmp instruction are not of the same type!", &IC);
1247  // Check that the operands are the right type
1248  Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1249          "Invalid operand types for ICmp instruction", &IC);
1250  // Check that the predicate is valid.
1251  Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1252          IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1253          "Invalid predicate in ICmp instruction!", &IC);
1254
1255  visitInstruction(IC);
1256}
1257
1258void Verifier::visitFCmpInst(FCmpInst &FC) {
1259  // Check that the operands are the same type
1260  Type *Op0Ty = FC.getOperand(0)->getType();
1261  Type *Op1Ty = FC.getOperand(1)->getType();
1262  Assert1(Op0Ty == Op1Ty,
1263          "Both operands to FCmp instruction are not of the same type!", &FC);
1264  // Check that the operands are the right type
1265  Assert1(Op0Ty->isFPOrFPVectorTy(),
1266          "Invalid operand types for FCmp instruction", &FC);
1267  // Check that the predicate is valid.
1268  Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1269          FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1270          "Invalid predicate in FCmp instruction!", &FC);
1271
1272  visitInstruction(FC);
1273}
1274
1275void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1276  Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1277                                              EI.getOperand(1)),
1278          "Invalid extractelement operands!", &EI);
1279  visitInstruction(EI);
1280}
1281
1282void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1283  Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1284                                             IE.getOperand(1),
1285                                             IE.getOperand(2)),
1286          "Invalid insertelement operands!", &IE);
1287  visitInstruction(IE);
1288}
1289
1290void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1291  Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1292                                             SV.getOperand(2)),
1293          "Invalid shufflevector operands!", &SV);
1294  visitInstruction(SV);
1295}
1296
1297void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1298  Assert1(cast<PointerType>(GEP.getOperand(0)->getType())
1299            ->getElementType()->isSized(),
1300          "GEP into unsized type!", &GEP);
1301
1302  SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1303  Type *ElTy =
1304    GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(), Idxs);
1305  Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1306  Assert2(GEP.getType()->isPointerTy() &&
1307          cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1308          "GEP is not of right type for indices!", &GEP, ElTy);
1309  visitInstruction(GEP);
1310}
1311
1312void Verifier::visitLoadInst(LoadInst &LI) {
1313  PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1314  Assert1(PTy, "Load operand must be a pointer.", &LI);
1315  Type *ElTy = PTy->getElementType();
1316  Assert2(ElTy == LI.getType(),
1317          "Load result type does not match pointer operand type!", &LI, ElTy);
1318  if (LI.isAtomic()) {
1319    Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1320            "Load cannot have Release ordering", &LI);
1321    Assert1(LI.getAlignment() != 0,
1322            "Atomic load must specify explicit alignment", &LI);
1323  } else {
1324    Assert1(LI.getSynchScope() == CrossThread,
1325            "Non-atomic load cannot have SynchronizationScope specified", &LI);
1326  }
1327  visitInstruction(LI);
1328}
1329
1330void Verifier::visitStoreInst(StoreInst &SI) {
1331  PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1332  Assert1(PTy, "Store operand must be a pointer.", &SI);
1333  Type *ElTy = PTy->getElementType();
1334  Assert2(ElTy == SI.getOperand(0)->getType(),
1335          "Stored value type does not match pointer operand type!",
1336          &SI, ElTy);
1337  if (SI.isAtomic()) {
1338    Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1339            "Store cannot have Acquire ordering", &SI);
1340    Assert1(SI.getAlignment() != 0,
1341            "Atomic store must specify explicit alignment", &SI);
1342  } else {
1343    Assert1(SI.getSynchScope() == CrossThread,
1344            "Non-atomic store cannot have SynchronizationScope specified", &SI);
1345  }
1346  visitInstruction(SI);
1347}
1348
1349void Verifier::visitAllocaInst(AllocaInst &AI) {
1350  PointerType *PTy = AI.getType();
1351  Assert1(PTy->getAddressSpace() == 0,
1352          "Allocation instruction pointer not in the generic address space!",
1353          &AI);
1354  Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1355          &AI);
1356  Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1357          "Alloca array size must have integer type", &AI);
1358  visitInstruction(AI);
1359}
1360
1361void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1362  Assert1(CXI.getOrdering() != NotAtomic,
1363          "cmpxchg instructions must be atomic.", &CXI);
1364  Assert1(CXI.getOrdering() != Unordered,
1365          "cmpxchg instructions cannot be unordered.", &CXI);
1366  PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1367  Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1368  Type *ElTy = PTy->getElementType();
1369  Assert2(ElTy == CXI.getOperand(1)->getType(),
1370          "Expected value type does not match pointer operand type!",
1371          &CXI, ElTy);
1372  Assert2(ElTy == CXI.getOperand(2)->getType(),
1373          "Stored value type does not match pointer operand type!",
1374          &CXI, ElTy);
1375  visitInstruction(CXI);
1376}
1377
1378void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1379  Assert1(RMWI.getOrdering() != NotAtomic,
1380          "atomicrmw instructions must be atomic.", &RMWI);
1381  Assert1(RMWI.getOrdering() != Unordered,
1382          "atomicrmw instructions cannot be unordered.", &RMWI);
1383  PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1384  Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1385  Type *ElTy = PTy->getElementType();
1386  Assert2(ElTy == RMWI.getOperand(1)->getType(),
1387          "Argument value type does not match pointer operand type!",
1388          &RMWI, ElTy);
1389  Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1390          RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1391          "Invalid binary operation!", &RMWI);
1392  visitInstruction(RMWI);
1393}
1394
1395void Verifier::visitFenceInst(FenceInst &FI) {
1396  const AtomicOrdering Ordering = FI.getOrdering();
1397  Assert1(Ordering == Acquire || Ordering == Release ||
1398          Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1399          "fence instructions may only have "
1400          "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1401  visitInstruction(FI);
1402}
1403
1404void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1405  Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1406                                           EVI.getIndices()) ==
1407          EVI.getType(),
1408          "Invalid ExtractValueInst operands!", &EVI);
1409
1410  visitInstruction(EVI);
1411}
1412
1413void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1414  Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1415                                           IVI.getIndices()) ==
1416          IVI.getOperand(1)->getType(),
1417          "Invalid InsertValueInst operands!", &IVI);
1418
1419  visitInstruction(IVI);
1420}
1421
1422void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1423  BasicBlock *BB = LPI.getParent();
1424
1425  // The landingpad instruction is ill-formed if it doesn't have any clauses and
1426  // isn't a cleanup.
1427  Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1428          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1429
1430  // The landingpad instruction defines its parent as a landing pad block. The
1431  // landing pad block may be branched to only by the unwind edge of an invoke.
1432  for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1433    const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1434    Assert1(II && II->getUnwindDest() == BB,
1435            "Block containing LandingPadInst must be jumped to "
1436            "only by the unwind edge of an invoke.", &LPI);
1437  }
1438
1439  // The landingpad instruction must be the first non-PHI instruction in the
1440  // block.
1441  Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1442          "LandingPadInst not the first non-PHI instruction in the block.",
1443          &LPI);
1444
1445  // The personality functions for all landingpad instructions within the same
1446  // function should match.
1447  if (PersonalityFn)
1448    Assert1(LPI.getPersonalityFn() == PersonalityFn,
1449            "Personality function doesn't match others in function", &LPI);
1450  PersonalityFn = LPI.getPersonalityFn();
1451
1452  // All operands must be constants.
1453  Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1454          &LPI);
1455  for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1456    Value *Clause = LPI.getClause(i);
1457    Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1458    if (LPI.isCatch(i)) {
1459      Assert1(isa<PointerType>(Clause->getType()),
1460              "Catch operand does not have pointer type!", &LPI);
1461    } else {
1462      Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1463      Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1464              "Filter operand is not an array of constants!", &LPI);
1465    }
1466  }
1467
1468  visitInstruction(LPI);
1469}
1470
1471/// verifyInstruction - Verify that an instruction is well formed.
1472///
1473void Verifier::visitInstruction(Instruction &I) {
1474  BasicBlock *BB = I.getParent();
1475  Assert1(BB, "Instruction not embedded in basic block!", &I);
1476
1477  if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1478    for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1479         UI != UE; ++UI)
1480      Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1481              "Only PHI nodes may reference their own value!", &I);
1482  }
1483
1484  // Check that void typed values don't have names
1485  Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1486          "Instruction has a name, but provides a void value!", &I);
1487
1488  // Check that the return value of the instruction is either void or a legal
1489  // value type.
1490  Assert1(I.getType()->isVoidTy() ||
1491          I.getType()->isFirstClassType(),
1492          "Instruction returns a non-scalar type!", &I);
1493
1494  // Check that the instruction doesn't produce metadata. Calls are already
1495  // checked against the callee type.
1496  Assert1(!I.getType()->isMetadataTy() ||
1497          isa<CallInst>(I) || isa<InvokeInst>(I),
1498          "Invalid use of metadata!", &I);
1499
1500  // Check that all uses of the instruction, if they are instructions
1501  // themselves, actually have parent basic blocks.  If the use is not an
1502  // instruction, it is an error!
1503  for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1504       UI != UE; ++UI) {
1505    if (Instruction *Used = dyn_cast<Instruction>(*UI))
1506      Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1507              " embedded in a basic block!", &I, Used);
1508    else {
1509      CheckFailed("Use of instruction is not an instruction!", *UI);
1510      return;
1511    }
1512  }
1513
1514  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1515    Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1516
1517    // Check to make sure that only first-class-values are operands to
1518    // instructions.
1519    if (!I.getOperand(i)->getType()->isFirstClassType()) {
1520      Assert1(0, "Instruction operands must be first-class values!", &I);
1521    }
1522
1523    if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1524      // Check to make sure that the "address of" an intrinsic function is never
1525      // taken.
1526      Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1527              "Cannot take the address of an intrinsic!", &I);
1528      Assert1(F->getParent() == Mod, "Referencing function in another module!",
1529              &I);
1530    } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1531      Assert1(OpBB->getParent() == BB->getParent(),
1532              "Referring to a basic block in another function!", &I);
1533    } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1534      Assert1(OpArg->getParent() == BB->getParent(),
1535              "Referring to an argument in another function!", &I);
1536    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1537      Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1538              &I);
1539    } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1540      BasicBlock *OpBlock = Op->getParent();
1541
1542      // Check that a definition dominates all of its uses.
1543      if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1544        // Invoke results are only usable in the normal destination, not in the
1545        // exceptional destination.
1546        BasicBlock *NormalDest = II->getNormalDest();
1547
1548        Assert2(NormalDest != II->getUnwindDest(),
1549                "No uses of invoke possible due to dominance structure!",
1550                Op, &I);
1551
1552        // PHI nodes differ from other nodes because they actually "use" the
1553        // value in the predecessor basic blocks they correspond to.
1554        BasicBlock *UseBlock = BB;
1555        if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1556          unsigned j = PHINode::getIncomingValueNumForOperand(i);
1557          UseBlock = PN->getIncomingBlock(j);
1558        }
1559        Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1560                Op, &I);
1561
1562        if (isa<PHINode>(I) && UseBlock == OpBlock) {
1563          // Special case of a phi node in the normal destination or the unwind
1564          // destination.
1565          Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1566                  "Invoke result not available in the unwind destination!",
1567                  Op, &I);
1568        } else {
1569          Assert2(DT->dominates(NormalDest, UseBlock) ||
1570                  !DT->isReachableFromEntry(UseBlock),
1571                  "Invoke result does not dominate all uses!", Op, &I);
1572
1573          // If the normal successor of an invoke instruction has multiple
1574          // predecessors, then the normal edge from the invoke is critical,
1575          // so the invoke value can only be live if the destination block
1576          // dominates all of it's predecessors (other than the invoke).
1577          if (!NormalDest->getSinglePredecessor() &&
1578              DT->isReachableFromEntry(UseBlock))
1579            // If it is used by something non-phi, then the other case is that
1580            // 'NormalDest' dominates all of its predecessors other than the
1581            // invoke.  In this case, the invoke value can still be used.
1582            for (pred_iterator PI = pred_begin(NormalDest),
1583                 E = pred_end(NormalDest); PI != E; ++PI)
1584              if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1585                  DT->isReachableFromEntry(*PI)) {
1586                CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1587                return;
1588              }
1589        }
1590      } else if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1591        // PHI nodes are more difficult than other nodes because they actually
1592        // "use" the value in the predecessor basic blocks they correspond to.
1593        unsigned j = PHINode::getIncomingValueNumForOperand(i);
1594        BasicBlock *PredBB = PN->getIncomingBlock(j);
1595        Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1596                           !DT->isReachableFromEntry(PredBB)),
1597                "Instruction does not dominate all uses!", Op, &I);
1598      } else {
1599        if (OpBlock == BB) {
1600          // If they are in the same basic block, make sure that the definition
1601          // comes before the use.
1602          Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1603                  "Instruction does not dominate all uses!", Op, &I);
1604        }
1605
1606        // Definition must dominate use unless use is unreachable!
1607        Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1608                !DT->isReachableFromEntry(BB),
1609                "Instruction does not dominate all uses!", Op, &I);
1610      }
1611    } else if (isa<InlineAsm>(I.getOperand(i))) {
1612      Assert1((i + 1 == e && isa<CallInst>(I)) ||
1613              (i + 3 == e && isa<InvokeInst>(I)),
1614              "Cannot take the address of an inline asm!", &I);
1615    }
1616  }
1617  InstsInThisBlock.insert(&I);
1618}
1619
1620// Flags used by TableGen to mark intrinsic parameters with the
1621// LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1622static const unsigned ExtendedElementVectorType = 0x40000000;
1623static const unsigned TruncatedElementVectorType = 0x20000000;
1624
1625/// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1626///
1627void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1628  Function *IF = CI.getCalledFunction();
1629  Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1630          IF);
1631
1632#define GET_INTRINSIC_VERIFIER
1633#include "llvm/Intrinsics.gen"
1634#undef GET_INTRINSIC_VERIFIER
1635
1636  // If the intrinsic takes MDNode arguments, verify that they are either global
1637  // or are local to *this* function.
1638  for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1639    if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1640      visitMDNode(*MD, CI.getParent()->getParent());
1641
1642  switch (ID) {
1643  default:
1644    break;
1645  case Intrinsic::dbg_declare: {  // llvm.dbg.declare
1646    Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1647                "invalid llvm.dbg.declare intrinsic call 1", &CI);
1648    MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1649    Assert1(MD->getNumOperands() == 1,
1650                "invalid llvm.dbg.declare intrinsic call 2", &CI);
1651  } break;
1652  case Intrinsic::memcpy:
1653  case Intrinsic::memmove:
1654  case Intrinsic::memset:
1655    Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1656            "alignment argument of memory intrinsics must be a constant int",
1657            &CI);
1658    Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1659            "isvolatile argument of memory intrinsics must be a constant int",
1660            &CI);
1661    break;
1662  case Intrinsic::gcroot:
1663  case Intrinsic::gcwrite:
1664  case Intrinsic::gcread:
1665    if (ID == Intrinsic::gcroot) {
1666      AllocaInst *AI =
1667        dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1668      Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1669      Assert1(isa<Constant>(CI.getArgOperand(1)),
1670              "llvm.gcroot parameter #2 must be a constant.", &CI);
1671      if (!AI->getType()->getElementType()->isPointerTy()) {
1672        Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1673                "llvm.gcroot parameter #1 must either be a pointer alloca, "
1674                "or argument #2 must be a non-null constant.", &CI);
1675      }
1676    }
1677
1678    Assert1(CI.getParent()->getParent()->hasGC(),
1679            "Enclosing function does not use GC.", &CI);
1680    break;
1681  case Intrinsic::init_trampoline:
1682    Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1683            "llvm.init_trampoline parameter #2 must resolve to a function.",
1684            &CI);
1685    break;
1686  case Intrinsic::prefetch:
1687    Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1688            isa<ConstantInt>(CI.getArgOperand(2)) &&
1689            cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1690            cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1691            "invalid arguments to llvm.prefetch",
1692            &CI);
1693    break;
1694  case Intrinsic::stackprotector:
1695    Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1696            "llvm.stackprotector parameter #2 must resolve to an alloca.",
1697            &CI);
1698    break;
1699  case Intrinsic::lifetime_start:
1700  case Intrinsic::lifetime_end:
1701  case Intrinsic::invariant_start:
1702    Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1703            "size argument of memory use markers must be a constant integer",
1704            &CI);
1705    break;
1706  case Intrinsic::invariant_end:
1707    Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1708            "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1709    break;
1710  }
1711}
1712
1713/// Produce a string to identify an intrinsic parameter or return value.
1714/// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1715/// parameters beginning with NumRets.
1716///
1717static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1718  if (ArgNo >= NumRets)
1719    return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1720  if (NumRets == 1)
1721    return "Intrinsic result type";
1722  return "Intrinsic result type #" + utostr(ArgNo);
1723}
1724
1725bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
1726                                int VT, unsigned ArgNo, std::string &Suffix) {
1727  FunctionType *FTy = F->getFunctionType();
1728
1729  unsigned NumElts = 0;
1730  Type *EltTy = Ty;
1731  VectorType *VTy = dyn_cast<VectorType>(Ty);
1732  if (VTy) {
1733    EltTy = VTy->getElementType();
1734    NumElts = VTy->getNumElements();
1735  }
1736
1737  Type *RetTy = FTy->getReturnType();
1738  StructType *ST = dyn_cast<StructType>(RetTy);
1739  unsigned NumRetVals;
1740  if (RetTy->isVoidTy())
1741    NumRetVals = 0;
1742  else if (ST)
1743    NumRetVals = ST->getNumElements();
1744  else
1745    NumRetVals = 1;
1746
1747  if (VT < 0) {
1748    int Match = ~VT;
1749
1750    // Check flags that indicate a type that is an integral vector type with
1751    // elements that are larger or smaller than the elements of the matched
1752    // type.
1753    if ((Match & (ExtendedElementVectorType |
1754                  TruncatedElementVectorType)) != 0) {
1755      IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1756      if (!VTy || !IEltTy) {
1757        CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1758                    "an integral vector type.", F);
1759        return false;
1760      }
1761      // Adjust the current Ty (in the opposite direction) rather than
1762      // the type being matched against.
1763      if ((Match & ExtendedElementVectorType) != 0) {
1764        if ((IEltTy->getBitWidth() & 1) != 0) {
1765          CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1766                      "element bit-width is odd.", F);
1767          return false;
1768        }
1769        Ty = VectorType::getTruncatedElementVectorType(VTy);
1770      } else
1771        Ty = VectorType::getExtendedElementVectorType(VTy);
1772      Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1773    }
1774
1775    if (Match <= static_cast<int>(NumRetVals - 1)) {
1776      if (ST)
1777        RetTy = ST->getElementType(Match);
1778
1779      if (Ty != RetTy) {
1780        CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1781                    "match return type.", F);
1782        return false;
1783      }
1784    } else {
1785      if (Ty != FTy->getParamType(Match - NumRetVals)) {
1786        CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1787                    "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1788        return false;
1789      }
1790    }
1791  } else if (VT == MVT::iAny) {
1792    if (!EltTy->isIntegerTy()) {
1793      CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1794                  "an integer type.", F);
1795      return false;
1796    }
1797
1798    unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1799    Suffix += ".";
1800
1801    if (EltTy != Ty)
1802      Suffix += "v" + utostr(NumElts);
1803
1804    Suffix += "i" + utostr(GotBits);
1805
1806    // Check some constraints on various intrinsics.
1807    switch (ID) {
1808    default: break; // Not everything needs to be checked.
1809    case Intrinsic::bswap:
1810      if (GotBits < 16 || GotBits % 16 != 0) {
1811        CheckFailed("Intrinsic requires even byte width argument", F);
1812        return false;
1813      }
1814      break;
1815    }
1816  } else if (VT == MVT::fAny) {
1817    if (!EltTy->isFloatingPointTy()) {
1818      CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1819                  "a floating-point type.", F);
1820      return false;
1821    }
1822
1823    Suffix += ".";
1824
1825    if (EltTy != Ty)
1826      Suffix += "v" + utostr(NumElts);
1827
1828    Suffix += EVT::getEVT(EltTy).getEVTString();
1829  } else if (VT == MVT::vAny) {
1830    if (!VTy) {
1831      CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1832                  F);
1833      return false;
1834    }
1835    Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1836  } else if (VT == MVT::iPTR) {
1837    if (!Ty->isPointerTy()) {
1838      CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1839                  "pointer and a pointer is required.", F);
1840      return false;
1841    }
1842  } else if (VT == MVT::iPTRAny) {
1843    // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1844    // and iPTR. In the verifier, we can not distinguish which case we have so
1845    // allow either case to be legal.
1846    if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1847      EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1848      if (PointeeVT == MVT::Other) {
1849        CheckFailed("Intrinsic has pointer to complex type.");
1850        return false;
1851      }
1852      Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1853        PointeeVT.getEVTString();
1854    } else {
1855      CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1856                  "pointer and a pointer is required.", F);
1857      return false;
1858    }
1859  } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1860    EVT VVT = EVT((MVT::SimpleValueType)VT);
1861
1862    // If this is a vector argument, verify the number and type of elements.
1863    if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1864      CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1865      return false;
1866    }
1867
1868    if (VVT.getVectorNumElements() != NumElts) {
1869      CheckFailed("Intrinsic prototype has incorrect number of "
1870                  "vector elements!", F);
1871      return false;
1872    }
1873  } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1874             EltTy) {
1875    CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1876    return false;
1877  } else if (EltTy != Ty) {
1878    CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1879                "and a scalar is required.", F);
1880    return false;
1881  }
1882
1883  return true;
1884}
1885
1886/// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1887/// Intrinsics.gen.  This implements a little state machine that verifies the
1888/// prototype of intrinsics.
1889void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1890                                        unsigned NumRetVals,
1891                                        unsigned NumParams, ...) {
1892  va_list VA;
1893  va_start(VA, NumParams);
1894  FunctionType *FTy = F->getFunctionType();
1895
1896  // For overloaded intrinsics, the Suffix of the function name must match the
1897  // types of the arguments. This variable keeps track of the expected
1898  // suffix, to be checked at the end.
1899  std::string Suffix;
1900
1901  if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1902    CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1903    return;
1904  }
1905
1906  Type *Ty = FTy->getReturnType();
1907  StructType *ST = dyn_cast<StructType>(Ty);
1908
1909  if (NumRetVals == 0 && !Ty->isVoidTy()) {
1910    CheckFailed("Intrinsic should return void", F);
1911    return;
1912  }
1913
1914  // Verify the return types.
1915  if (ST && ST->getNumElements() != NumRetVals) {
1916    CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1917    return;
1918  }
1919
1920  for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1921    int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1922
1923    if (ST) Ty = ST->getElementType(ArgNo);
1924    if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1925      break;
1926  }
1927
1928  // Verify the parameter types.
1929  for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1930    int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1931
1932    if (VT == MVT::isVoid && ArgNo > 0) {
1933      if (!FTy->isVarArg())
1934        CheckFailed("Intrinsic prototype has no '...'!", F);
1935      break;
1936    }
1937
1938    if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1939                          ArgNo + NumRetVals, Suffix))
1940      break;
1941  }
1942
1943  va_end(VA);
1944
1945  // For intrinsics without pointer arguments, if we computed a Suffix then the
1946  // intrinsic is overloaded and we need to make sure that the name of the
1947  // function is correct. We add the suffix to the name of the intrinsic and
1948  // compare against the given function name. If they are not the same, the
1949  // function name is invalid. This ensures that overloading of intrinsics
1950  // uses a sane and consistent naming convention.  Note that intrinsics with
1951  // pointer argument may or may not be overloaded so we will check assuming it
1952  // has a suffix and not.
1953  if (!Suffix.empty()) {
1954    std::string Name(Intrinsic::getName(ID));
1955    if (Name + Suffix != F->getName()) {
1956      CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1957                  F->getName().substr(Name.length()) + "'. It should be '" +
1958                  Suffix + "'", F);
1959    }
1960  }
1961
1962  // Check parameter attributes.
1963  Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1964          "Intrinsic has wrong parameter attributes!", F);
1965}
1966
1967
1968//===----------------------------------------------------------------------===//
1969//  Implement the public interfaces to this file...
1970//===----------------------------------------------------------------------===//
1971
1972FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1973  return new Verifier(action);
1974}
1975
1976
1977/// verifyFunction - Check a function for errors, printing messages on stderr.
1978/// Return true if the function is corrupt.
1979///
1980bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1981  Function &F = const_cast<Function&>(f);
1982  assert(!F.isDeclaration() && "Cannot verify external functions");
1983
1984  FunctionPassManager FPM(F.getParent());
1985  Verifier *V = new Verifier(action);
1986  FPM.add(V);
1987  FPM.run(F);
1988  return V->Broken;
1989}
1990
1991/// verifyModule - Check a module for errors, printing messages on stderr.
1992/// Return true if the module is corrupt.
1993///
1994bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1995                        std::string *ErrorInfo) {
1996  PassManager PM;
1997  Verifier *V = new Verifier(action);
1998  PM.add(V);
1999  PM.run(const_cast<Module&>(M));
2000
2001  if (ErrorInfo && V->Broken)
2002    *ErrorInfo = V->MessagesStr.str();
2003  return V->Broken;
2004}
2005