1249259Sdim//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2249259Sdim//
3249259Sdim//                     The LLVM Compiler Infrastructure
4249259Sdim//
5249259Sdim// This file is distributed under the University of Illinois Open Source
6249259Sdim// License. See LICENSE.TXT for details.
7249259Sdim//
8249259Sdim//===----------------------------------------------------------------------===//
9249259Sdim//
10249259Sdim// This file defines the function verifier interface, that can be used for some
11249259Sdim// sanity checking of input to the system.
12249259Sdim//
13249259Sdim// Note that this does not provide full `Java style' security and verifications,
14249259Sdim// instead it just tries to ensure that code is well-formed.
15249259Sdim//
16249259Sdim//  * Both of a binary operator's parameters are of the same type
17249259Sdim//  * Verify that the indices of mem access instructions match other operands
18249259Sdim//  * Verify that arithmetic and other things are only performed on first-class
19249259Sdim//    types.  Verify that shifts & logicals only happen on integrals f.e.
20249259Sdim//  * All of the constants in a switch statement are of the correct type
21249259Sdim//  * The code is in valid SSA form
22249259Sdim//  * It should be illegal to put a label into any other type (like a structure)
23249259Sdim//    or to return one. [except constant arrays!]
24249259Sdim//  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25249259Sdim//  * PHI nodes must have an entry for each predecessor, with no extras.
26249259Sdim//  * PHI nodes must be the first thing in a basic block, all grouped together
27249259Sdim//  * PHI nodes must have at least one entry
28249259Sdim//  * All basic blocks should only end with terminator insts, not contain them
29249259Sdim//  * The entry node to a function must not have predecessors
30249259Sdim//  * All Instructions must be embedded into a basic block
31249259Sdim//  * Functions cannot take a void-typed parameter
32249259Sdim//  * Verify that a function's argument list agrees with it's declared type.
33249259Sdim//  * It is illegal to specify a name for a void value.
34249259Sdim//  * It is illegal to have a internal global value with no initializer
35249259Sdim//  * It is illegal to have a ret instruction that returns a value that does not
36249259Sdim//    agree with the function return value type.
37249259Sdim//  * Function call argument types match the function prototype
38249259Sdim//  * A landing pad is defined by a landingpad instruction, and can be jumped to
39249259Sdim//    only by the unwind edge of an invoke instruction.
40249259Sdim//  * A landingpad instruction must be the first non-PHI instruction in the
41249259Sdim//    block.
42249259Sdim//  * All landingpad instructions must use the same personality function with
43249259Sdim//    the same function.
44249259Sdim//  * All other things that are tested by asserts spread about the code...
45249259Sdim//
46249259Sdim//===----------------------------------------------------------------------===//
47249259Sdim
48249259Sdim#include "llvm/Analysis/Verifier.h"
49249259Sdim#include "llvm/ADT/STLExtras.h"
50249259Sdim#include "llvm/ADT/SetVector.h"
51249259Sdim#include "llvm/ADT/SmallPtrSet.h"
52249259Sdim#include "llvm/ADT/SmallVector.h"
53249259Sdim#include "llvm/ADT/StringExtras.h"
54249259Sdim#include "llvm/Analysis/Dominators.h"
55249259Sdim#include "llvm/Assembly/Writer.h"
56263509Sdim#include "llvm/DebugInfo.h"
57249259Sdim#include "llvm/IR/CallingConv.h"
58249259Sdim#include "llvm/IR/Constants.h"
59263509Sdim#include "llvm/IR/DataLayout.h"
60249259Sdim#include "llvm/IR/DerivedTypes.h"
61249259Sdim#include "llvm/IR/InlineAsm.h"
62249259Sdim#include "llvm/IR/IntrinsicInst.h"
63249259Sdim#include "llvm/IR/LLVMContext.h"
64249259Sdim#include "llvm/IR/Metadata.h"
65249259Sdim#include "llvm/IR/Module.h"
66249259Sdim#include "llvm/InstVisitor.h"
67249259Sdim#include "llvm/Pass.h"
68249259Sdim#include "llvm/PassManager.h"
69249259Sdim#include "llvm/Support/CFG.h"
70249259Sdim#include "llvm/Support/CallSite.h"
71263509Sdim#include "llvm/Support/CommandLine.h"
72249259Sdim#include "llvm/Support/ConstantRange.h"
73249259Sdim#include "llvm/Support/Debug.h"
74249259Sdim#include "llvm/Support/ErrorHandling.h"
75249259Sdim#include "llvm/Support/raw_ostream.h"
76249259Sdim#include <algorithm>
77249259Sdim#include <cstdarg>
78249259Sdimusing namespace llvm;
79249259Sdim
80263509Sdimstatic cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
81263509Sdim                                              cl::init(true));
82263509Sdim
83249259Sdimnamespace {  // Anonymous namespace for class
84249259Sdim  struct PreVerifier : public FunctionPass {
85249259Sdim    static char ID; // Pass ID, replacement for typeid
86249259Sdim
87249259Sdim    PreVerifier() : FunctionPass(ID) {
88249259Sdim      initializePreVerifierPass(*PassRegistry::getPassRegistry());
89249259Sdim    }
90249259Sdim
91249259Sdim    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92249259Sdim      AU.setPreservesAll();
93249259Sdim    }
94249259Sdim
95249259Sdim    // Check that the prerequisites for successful DominatorTree construction
96249259Sdim    // are satisfied.
97249259Sdim    bool runOnFunction(Function &F) {
98249259Sdim      bool Broken = false;
99249259Sdim
100249259Sdim      for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
101249259Sdim        if (I->empty() || !I->back().isTerminator()) {
102263509Sdim          dbgs() << "Basic Block in function '" << F.getName()
103249259Sdim                 << "' does not have terminator!\n";
104249259Sdim          WriteAsOperand(dbgs(), I, true);
105249259Sdim          dbgs() << "\n";
106249259Sdim          Broken = true;
107249259Sdim        }
108249259Sdim      }
109249259Sdim
110249259Sdim      if (Broken)
111249259Sdim        report_fatal_error("Broken module, no Basic Block terminator!");
112249259Sdim
113249259Sdim      return false;
114249259Sdim    }
115249259Sdim  };
116249259Sdim}
117249259Sdim
118249259Sdimchar PreVerifier::ID = 0;
119263509SdimINITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
120249259Sdim                false, false)
121249259Sdimstatic char &PreVerifyID = PreVerifier::ID;
122249259Sdim
123249259Sdimnamespace {
124249259Sdim  struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
125249259Sdim    static char ID; // Pass ID, replacement for typeid
126249259Sdim    bool Broken;          // Is this module found to be broken?
127249259Sdim    VerifierFailureAction action;
128249259Sdim                          // What to do if verification fails.
129249259Sdim    Module *Mod;          // Module we are verifying right now
130249259Sdim    LLVMContext *Context; // Context within which we are verifying
131249259Sdim    DominatorTree *DT;    // Dominator Tree, caution can be null!
132263509Sdim    const DataLayout *DL;
133249259Sdim
134249259Sdim    std::string Messages;
135249259Sdim    raw_string_ostream MessagesStr;
136249259Sdim
137249259Sdim    /// InstInThisBlock - when verifying a basic block, keep track of all of the
138249259Sdim    /// instructions we have seen so far.  This allows us to do efficient
139249259Sdim    /// dominance checks for the case when an instruction has an operand that is
140249259Sdim    /// an instruction in the same block.
141249259Sdim    SmallPtrSet<Instruction*, 16> InstsInThisBlock;
142249259Sdim
143249259Sdim    /// MDNodes - keep track of the metadata nodes that have been checked
144249259Sdim    /// already.
145249259Sdim    SmallPtrSet<MDNode *, 32> MDNodes;
146249259Sdim
147249259Sdim    /// PersonalityFn - The personality function referenced by the
148249259Sdim    /// LandingPadInsts. All LandingPadInsts within the same function must use
149249259Sdim    /// the same personality function.
150249259Sdim    const Value *PersonalityFn;
151249259Sdim
152263509Sdim    /// Finder keeps track of all debug info MDNodes in a Module.
153263509Sdim    DebugInfoFinder Finder;
154263509Sdim
155249259Sdim    Verifier()
156249259Sdim      : FunctionPass(ID), Broken(false),
157263509Sdim        action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0),
158249259Sdim        MessagesStr(Messages), PersonalityFn(0) {
159249259Sdim      initializeVerifierPass(*PassRegistry::getPassRegistry());
160249259Sdim    }
161249259Sdim    explicit Verifier(VerifierFailureAction ctn)
162249259Sdim      : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
163263509Sdim        Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) {
164249259Sdim      initializeVerifierPass(*PassRegistry::getPassRegistry());
165249259Sdim    }
166249259Sdim
167249259Sdim    bool doInitialization(Module &M) {
168249259Sdim      Mod = &M;
169249259Sdim      Context = &M.getContext();
170249259Sdim
171263509Sdim      DL = getAnalysisIfAvailable<DataLayout>();
172263509Sdim
173249259Sdim      // We must abort before returning back to the pass manager, or else the
174249259Sdim      // pass manager may try to run other passes on the broken module.
175249259Sdim      return abortIfBroken();
176249259Sdim    }
177249259Sdim
178249259Sdim    bool runOnFunction(Function &F) {
179249259Sdim      // Get dominator information if we are being run by PassManager
180249259Sdim      DT = &getAnalysis<DominatorTree>();
181249259Sdim
182249259Sdim      Mod = F.getParent();
183249259Sdim      if (!Context) Context = &F.getContext();
184249259Sdim
185263509Sdim      Finder.reset();
186249259Sdim      visit(F);
187249259Sdim      InstsInThisBlock.clear();
188249259Sdim      PersonalityFn = 0;
189249259Sdim
190263509Sdim      if (!DisableDebugInfoVerifier)
191263509Sdim        // Verify Debug Info.
192263509Sdim        verifyDebugInfo();
193263509Sdim
194249259Sdim      // We must abort before returning back to the pass manager, or else the
195249259Sdim      // pass manager may try to run other passes on the broken module.
196249259Sdim      return abortIfBroken();
197249259Sdim    }
198249259Sdim
199249259Sdim    bool doFinalization(Module &M) {
200249259Sdim      // Scan through, checking all of the external function's linkage now...
201249259Sdim      for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
202249259Sdim        visitGlobalValue(*I);
203249259Sdim
204249259Sdim        // Check to make sure function prototypes are okay.
205249259Sdim        if (I->isDeclaration()) visitFunction(*I);
206249259Sdim      }
207249259Sdim
208263509Sdim      for (Module::global_iterator I = M.global_begin(), E = M.global_end();
209249259Sdim           I != E; ++I)
210249259Sdim        visitGlobalVariable(*I);
211249259Sdim
212263509Sdim      for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
213249259Sdim           I != E; ++I)
214249259Sdim        visitGlobalAlias(*I);
215249259Sdim
216249259Sdim      for (Module::named_metadata_iterator I = M.named_metadata_begin(),
217249259Sdim           E = M.named_metadata_end(); I != E; ++I)
218249259Sdim        visitNamedMDNode(*I);
219249259Sdim
220249259Sdim      visitModuleFlags(M);
221263509Sdim      visitModuleIdents(M);
222249259Sdim
223263509Sdim      if (!DisableDebugInfoVerifier) {
224263509Sdim        Finder.reset();
225263509Sdim        Finder.processModule(M);
226263509Sdim        // Verify Debug Info.
227263509Sdim        verifyDebugInfo();
228263509Sdim      }
229263509Sdim
230249259Sdim      // If the module is broken, abort at this time.
231249259Sdim      return abortIfBroken();
232249259Sdim    }
233249259Sdim
234249259Sdim    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
235249259Sdim      AU.setPreservesAll();
236249259Sdim      AU.addRequiredID(PreVerifyID);
237249259Sdim      AU.addRequired<DominatorTree>();
238249259Sdim    }
239249259Sdim
240249259Sdim    /// abortIfBroken - If the module is broken and we are supposed to abort on
241249259Sdim    /// this condition, do so.
242249259Sdim    ///
243249259Sdim    bool abortIfBroken() {
244249259Sdim      if (!Broken) return false;
245249259Sdim      MessagesStr << "Broken module found, ";
246249259Sdim      switch (action) {
247249259Sdim      case AbortProcessAction:
248249259Sdim        MessagesStr << "compilation aborted!\n";
249249259Sdim        dbgs() << MessagesStr.str();
250249259Sdim        // Client should choose different reaction if abort is not desired
251249259Sdim        abort();
252249259Sdim      case PrintMessageAction:
253249259Sdim        MessagesStr << "verification continues.\n";
254249259Sdim        dbgs() << MessagesStr.str();
255249259Sdim        return false;
256249259Sdim      case ReturnStatusAction:
257249259Sdim        MessagesStr << "compilation terminated.\n";
258249259Sdim        return true;
259249259Sdim      }
260249259Sdim      llvm_unreachable("Invalid action");
261249259Sdim    }
262249259Sdim
263249259Sdim
264249259Sdim    // Verification methods...
265249259Sdim    void visitGlobalValue(GlobalValue &GV);
266249259Sdim    void visitGlobalVariable(GlobalVariable &GV);
267249259Sdim    void visitGlobalAlias(GlobalAlias &GA);
268249259Sdim    void visitNamedMDNode(NamedMDNode &NMD);
269249259Sdim    void visitMDNode(MDNode &MD, Function *F);
270263509Sdim    void visitModuleIdents(Module &M);
271249259Sdim    void visitModuleFlags(Module &M);
272249259Sdim    void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
273249259Sdim                         SmallVectorImpl<MDNode*> &Requirements);
274249259Sdim    void visitFunction(Function &F);
275249259Sdim    void visitBasicBlock(BasicBlock &BB);
276249259Sdim    using InstVisitor<Verifier>::visit;
277249259Sdim
278249259Sdim    void visit(Instruction &I);
279249259Sdim
280249259Sdim    void visitTruncInst(TruncInst &I);
281249259Sdim    void visitZExtInst(ZExtInst &I);
282249259Sdim    void visitSExtInst(SExtInst &I);
283249259Sdim    void visitFPTruncInst(FPTruncInst &I);
284249259Sdim    void visitFPExtInst(FPExtInst &I);
285249259Sdim    void visitFPToUIInst(FPToUIInst &I);
286249259Sdim    void visitFPToSIInst(FPToSIInst &I);
287249259Sdim    void visitUIToFPInst(UIToFPInst &I);
288249259Sdim    void visitSIToFPInst(SIToFPInst &I);
289249259Sdim    void visitIntToPtrInst(IntToPtrInst &I);
290249259Sdim    void visitPtrToIntInst(PtrToIntInst &I);
291249259Sdim    void visitBitCastInst(BitCastInst &I);
292263509Sdim    void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
293249259Sdim    void visitPHINode(PHINode &PN);
294249259Sdim    void visitBinaryOperator(BinaryOperator &B);
295249259Sdim    void visitICmpInst(ICmpInst &IC);
296249259Sdim    void visitFCmpInst(FCmpInst &FC);
297249259Sdim    void visitExtractElementInst(ExtractElementInst &EI);
298249259Sdim    void visitInsertElementInst(InsertElementInst &EI);
299249259Sdim    void visitShuffleVectorInst(ShuffleVectorInst &EI);
300249259Sdim    void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
301249259Sdim    void visitCallInst(CallInst &CI);
302249259Sdim    void visitInvokeInst(InvokeInst &II);
303249259Sdim    void visitGetElementPtrInst(GetElementPtrInst &GEP);
304249259Sdim    void visitLoadInst(LoadInst &LI);
305249259Sdim    void visitStoreInst(StoreInst &SI);
306249259Sdim    void verifyDominatesUse(Instruction &I, unsigned i);
307249259Sdim    void visitInstruction(Instruction &I);
308249259Sdim    void visitTerminatorInst(TerminatorInst &I);
309249259Sdim    void visitBranchInst(BranchInst &BI);
310249259Sdim    void visitReturnInst(ReturnInst &RI);
311249259Sdim    void visitSwitchInst(SwitchInst &SI);
312249259Sdim    void visitIndirectBrInst(IndirectBrInst &BI);
313249259Sdim    void visitSelectInst(SelectInst &SI);
314249259Sdim    void visitUserOp1(Instruction &I);
315249259Sdim    void visitUserOp2(Instruction &I) { visitUserOp1(I); }
316249259Sdim    void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
317249259Sdim    void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
318249259Sdim    void visitAtomicRMWInst(AtomicRMWInst &RMWI);
319249259Sdim    void visitFenceInst(FenceInst &FI);
320249259Sdim    void visitAllocaInst(AllocaInst &AI);
321249259Sdim    void visitExtractValueInst(ExtractValueInst &EVI);
322249259Sdim    void visitInsertValueInst(InsertValueInst &IVI);
323249259Sdim    void visitLandingPadInst(LandingPadInst &LPI);
324249259Sdim
325249259Sdim    void VerifyCallSite(CallSite CS);
326249259Sdim    bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
327249259Sdim                          int VT, unsigned ArgNo, std::string &Suffix);
328249259Sdim    bool VerifyIntrinsicType(Type *Ty,
329249259Sdim                             ArrayRef<Intrinsic::IITDescriptor> &Infos,
330249259Sdim                             SmallVectorImpl<Type*> &ArgTys);
331263509Sdim    bool VerifyIntrinsicIsVarArg(bool isVarArg,
332263509Sdim                                 ArrayRef<Intrinsic::IITDescriptor> &Infos);
333252723Sdim    bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
334252723Sdim    void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
335252723Sdim                              bool isFunction, const Value *V);
336252723Sdim    void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
337249259Sdim                              bool isReturnValue, const Value *V);
338252723Sdim    void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
339249259Sdim                             const Value *V);
340249259Sdim
341263509Sdim    void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
342263509Sdim    void VerifyConstantExprBitcastType(const ConstantExpr *CE);
343263509Sdim
344263509Sdim    void verifyDebugInfo();
345263509Sdim
346249259Sdim    void WriteValue(const Value *V) {
347249259Sdim      if (!V) return;
348249259Sdim      if (isa<Instruction>(V)) {
349249259Sdim        MessagesStr << *V << '\n';
350249259Sdim      } else {
351249259Sdim        WriteAsOperand(MessagesStr, V, true, Mod);
352249259Sdim        MessagesStr << '\n';
353249259Sdim      }
354249259Sdim    }
355249259Sdim
356249259Sdim    void WriteType(Type *T) {
357249259Sdim      if (!T) return;
358249259Sdim      MessagesStr << ' ' << *T;
359249259Sdim    }
360249259Sdim
361249259Sdim
362249259Sdim    // CheckFailed - A check failed, so print out the condition and the message
363249259Sdim    // that failed.  This provides a nice place to put a breakpoint if you want
364249259Sdim    // to see why something is not correct.
365249259Sdim    void CheckFailed(const Twine &Message,
366249259Sdim                     const Value *V1 = 0, const Value *V2 = 0,
367249259Sdim                     const Value *V3 = 0, const Value *V4 = 0) {
368249259Sdim      MessagesStr << Message.str() << "\n";
369249259Sdim      WriteValue(V1);
370249259Sdim      WriteValue(V2);
371249259Sdim      WriteValue(V3);
372249259Sdim      WriteValue(V4);
373249259Sdim      Broken = true;
374249259Sdim    }
375249259Sdim
376249259Sdim    void CheckFailed(const Twine &Message, const Value *V1,
377249259Sdim                     Type *T2, const Value *V3 = 0) {
378249259Sdim      MessagesStr << Message.str() << "\n";
379249259Sdim      WriteValue(V1);
380249259Sdim      WriteType(T2);
381249259Sdim      WriteValue(V3);
382249259Sdim      Broken = true;
383249259Sdim    }
384249259Sdim
385249259Sdim    void CheckFailed(const Twine &Message, Type *T1,
386249259Sdim                     Type *T2 = 0, Type *T3 = 0) {
387249259Sdim      MessagesStr << Message.str() << "\n";
388249259Sdim      WriteType(T1);
389249259Sdim      WriteType(T2);
390249259Sdim      WriteType(T3);
391249259Sdim      Broken = true;
392249259Sdim    }
393249259Sdim  };
394249259Sdim} // End anonymous namespace
395249259Sdim
396249259Sdimchar Verifier::ID = 0;
397249259SdimINITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
398249259SdimINITIALIZE_PASS_DEPENDENCY(PreVerifier)
399249259SdimINITIALIZE_PASS_DEPENDENCY(DominatorTree)
400249259SdimINITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
401249259Sdim
402249259Sdim// Assert - We know that cond should be true, if not print an error message.
403249259Sdim#define Assert(C, M) \
404249259Sdim  do { if (!(C)) { CheckFailed(M); return; } } while (0)
405249259Sdim#define Assert1(C, M, V1) \
406249259Sdim  do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
407249259Sdim#define Assert2(C, M, V1, V2) \
408249259Sdim  do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
409249259Sdim#define Assert3(C, M, V1, V2, V3) \
410249259Sdim  do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
411249259Sdim#define Assert4(C, M, V1, V2, V3, V4) \
412249259Sdim  do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
413249259Sdim
414249259Sdimvoid Verifier::visit(Instruction &I) {
415249259Sdim  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
416249259Sdim    Assert1(I.getOperand(i) != 0, "Operand is null", &I);
417249259Sdim  InstVisitor<Verifier>::visit(I);
418249259Sdim}
419249259Sdim
420249259Sdim
421249259Sdimvoid Verifier::visitGlobalValue(GlobalValue &GV) {
422249259Sdim  Assert1(!GV.isDeclaration() ||
423249259Sdim          GV.isMaterializable() ||
424249259Sdim          GV.hasExternalLinkage() ||
425249259Sdim          GV.hasDLLImportLinkage() ||
426249259Sdim          GV.hasExternalWeakLinkage() ||
427249259Sdim          (isa<GlobalAlias>(GV) &&
428249259Sdim           (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
429249259Sdim  "Global is external, but doesn't have external or dllimport or weak linkage!",
430249259Sdim          &GV);
431249259Sdim
432249259Sdim  Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
433249259Sdim          "Global is marked as dllimport, but not external", &GV);
434249259Sdim
435249259Sdim  Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
436249259Sdim          "Only global variables can have appending linkage!", &GV);
437249259Sdim
438249259Sdim  if (GV.hasAppendingLinkage()) {
439249259Sdim    GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
440249259Sdim    Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
441249259Sdim            "Only global arrays can have appending linkage!", GVar);
442249259Sdim  }
443249259Sdim}
444249259Sdim
445249259Sdimvoid Verifier::visitGlobalVariable(GlobalVariable &GV) {
446249259Sdim  if (GV.hasInitializer()) {
447249259Sdim    Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
448249259Sdim            "Global variable initializer type does not match global "
449249259Sdim            "variable type!", &GV);
450249259Sdim
451249259Sdim    // If the global has common linkage, it must have a zero initializer and
452249259Sdim    // cannot be constant.
453249259Sdim    if (GV.hasCommonLinkage()) {
454249259Sdim      Assert1(GV.getInitializer()->isNullValue(),
455249259Sdim              "'common' global must have a zero initializer!", &GV);
456249259Sdim      Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
457249259Sdim              &GV);
458249259Sdim    }
459249259Sdim  } else {
460249259Sdim    Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
461249259Sdim            GV.hasExternalWeakLinkage(),
462249259Sdim            "invalid linkage type for global declaration", &GV);
463249259Sdim  }
464249259Sdim
465249259Sdim  if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
466249259Sdim                       GV.getName() == "llvm.global_dtors")) {
467249259Sdim    Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
468249259Sdim            "invalid linkage for intrinsic global variable", &GV);
469249259Sdim    // Don't worry about emitting an error for it not being an array,
470249259Sdim    // visitGlobalValue will complain on appending non-array.
471249259Sdim    if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
472249259Sdim      StructType *STy = dyn_cast<StructType>(ATy->getElementType());
473249259Sdim      PointerType *FuncPtrTy =
474249259Sdim          FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
475249259Sdim      Assert1(STy && STy->getNumElements() == 2 &&
476249259Sdim              STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
477249259Sdim              STy->getTypeAtIndex(1) == FuncPtrTy,
478249259Sdim              "wrong type for intrinsic global variable", &GV);
479249259Sdim    }
480249259Sdim  }
481249259Sdim
482252723Sdim  if (GV.hasName() && (GV.getName() == "llvm.used" ||
483263509Sdim                       GV.getName() == "llvm.compiler.used")) {
484252723Sdim    Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
485252723Sdim            "invalid linkage for intrinsic global variable", &GV);
486252723Sdim    Type *GVType = GV.getType()->getElementType();
487252723Sdim    if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
488252723Sdim      PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
489252723Sdim      Assert1(PTy, "wrong type for intrinsic global variable", &GV);
490252723Sdim      if (GV.hasInitializer()) {
491252723Sdim        Constant *Init = GV.getInitializer();
492252723Sdim        ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
493252723Sdim        Assert1(InitArray, "wrong initalizer for intrinsic global variable",
494252723Sdim                Init);
495252723Sdim        for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
496263509Sdim          Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
497263509Sdim          Assert1(
498263509Sdim              isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
499263509Sdim              "invalid llvm.used member", V);
500263509Sdim          Assert1(V->hasName(), "members of llvm.used must be named", V);
501252723Sdim        }
502252723Sdim      }
503252723Sdim    }
504252723Sdim  }
505252723Sdim
506263509Sdim  if (!GV.hasInitializer()) {
507263509Sdim    visitGlobalValue(GV);
508263509Sdim    return;
509263509Sdim  }
510263509Sdim
511263509Sdim  // Walk any aggregate initializers looking for bitcasts between address spaces
512263509Sdim  SmallPtrSet<const Value *, 4> Visited;
513263509Sdim  SmallVector<const Value *, 4> WorkStack;
514263509Sdim  WorkStack.push_back(cast<Value>(GV.getInitializer()));
515263509Sdim
516263509Sdim  while (!WorkStack.empty()) {
517263509Sdim    const Value *V = WorkStack.pop_back_val();
518263509Sdim    if (!Visited.insert(V))
519263509Sdim      continue;
520263509Sdim
521263509Sdim    if (const User *U = dyn_cast<User>(V)) {
522263509Sdim      for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
523263509Sdim        WorkStack.push_back(U->getOperand(I));
524263509Sdim    }
525263509Sdim
526263509Sdim    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
527263509Sdim      VerifyConstantExprBitcastType(CE);
528263509Sdim      if (Broken)
529263509Sdim        return;
530263509Sdim    }
531263509Sdim  }
532263509Sdim
533249259Sdim  visitGlobalValue(GV);
534249259Sdim}
535249259Sdim
536249259Sdimvoid Verifier::visitGlobalAlias(GlobalAlias &GA) {
537249259Sdim  Assert1(!GA.getName().empty(),
538249259Sdim          "Alias name cannot be empty!", &GA);
539263509Sdim  Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
540249259Sdim          "Alias should have external or external weak linkage!", &GA);
541249259Sdim  Assert1(GA.getAliasee(),
542249259Sdim          "Aliasee cannot be NULL!", &GA);
543249259Sdim  Assert1(GA.getType() == GA.getAliasee()->getType(),
544249259Sdim          "Alias and aliasee types should match!", &GA);
545249259Sdim  Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
546249259Sdim
547263509Sdim  Constant *Aliasee = GA.getAliasee();
548263509Sdim
549263509Sdim  if (!isa<GlobalValue>(Aliasee)) {
550263509Sdim    ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
551263509Sdim    Assert1(CE &&
552249259Sdim            (CE->getOpcode() == Instruction::BitCast ||
553249259Sdim             CE->getOpcode() == Instruction::GetElementPtr) &&
554249259Sdim            isa<GlobalValue>(CE->getOperand(0)),
555249259Sdim            "Aliasee should be either GlobalValue or bitcast of GlobalValue",
556249259Sdim            &GA);
557263509Sdim
558263509Sdim    if (CE->getOpcode() == Instruction::BitCast) {
559263509Sdim      unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
560263509Sdim      unsigned DstAS = CE->getType()->getPointerAddressSpace();
561263509Sdim
562263509Sdim      Assert1(SrcAS == DstAS,
563263509Sdim              "Alias bitcasts cannot be between different address spaces",
564263509Sdim              &GA);
565263509Sdim    }
566249259Sdim  }
567249259Sdim
568263509Sdim  const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
569263509Sdim  Assert1(Resolved,
570249259Sdim          "Aliasing chain should end with function or global variable", &GA);
571249259Sdim
572249259Sdim  visitGlobalValue(GA);
573249259Sdim}
574249259Sdim
575249259Sdimvoid Verifier::visitNamedMDNode(NamedMDNode &NMD) {
576249259Sdim  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
577249259Sdim    MDNode *MD = NMD.getOperand(i);
578249259Sdim    if (!MD)
579249259Sdim      continue;
580249259Sdim
581249259Sdim    Assert1(!MD->isFunctionLocal(),
582249259Sdim            "Named metadata operand cannot be function local!", MD);
583249259Sdim    visitMDNode(*MD, 0);
584249259Sdim  }
585249259Sdim}
586249259Sdim
587249259Sdimvoid Verifier::visitMDNode(MDNode &MD, Function *F) {
588249259Sdim  // Only visit each node once.  Metadata can be mutually recursive, so this
589249259Sdim  // avoids infinite recursion here, as well as being an optimization.
590249259Sdim  if (!MDNodes.insert(&MD))
591249259Sdim    return;
592249259Sdim
593249259Sdim  for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
594249259Sdim    Value *Op = MD.getOperand(i);
595249259Sdim    if (!Op)
596249259Sdim      continue;
597249259Sdim    if (isa<Constant>(Op) || isa<MDString>(Op))
598249259Sdim      continue;
599249259Sdim    if (MDNode *N = dyn_cast<MDNode>(Op)) {
600249259Sdim      Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
601249259Sdim              "Global metadata operand cannot be function local!", &MD, N);
602249259Sdim      visitMDNode(*N, F);
603249259Sdim      continue;
604249259Sdim    }
605249259Sdim    Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
606249259Sdim
607249259Sdim    // If this was an instruction, bb, or argument, verify that it is in the
608249259Sdim    // function that we expect.
609249259Sdim    Function *ActualF = 0;
610249259Sdim    if (Instruction *I = dyn_cast<Instruction>(Op))
611249259Sdim      ActualF = I->getParent()->getParent();
612249259Sdim    else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
613249259Sdim      ActualF = BB->getParent();
614249259Sdim    else if (Argument *A = dyn_cast<Argument>(Op))
615249259Sdim      ActualF = A->getParent();
616249259Sdim    assert(ActualF && "Unimplemented function local metadata case!");
617249259Sdim
618249259Sdim    Assert2(ActualF == F, "function-local metadata used in wrong function",
619249259Sdim            &MD, Op);
620249259Sdim  }
621249259Sdim}
622249259Sdim
623263509Sdimvoid Verifier::visitModuleIdents(Module &M) {
624263509Sdim  const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
625263509Sdim  if (!Idents)
626263509Sdim    return;
627263509Sdim
628263509Sdim  // llvm.ident takes a list of metadata entry. Each entry has only one string.
629263509Sdim  // Scan each llvm.ident entry and make sure that this requirement is met.
630263509Sdim  for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
631263509Sdim    const MDNode *N = Idents->getOperand(i);
632263509Sdim    Assert1(N->getNumOperands() == 1,
633263509Sdim            "incorrect number of operands in llvm.ident metadata", N);
634263509Sdim    Assert1(isa<MDString>(N->getOperand(0)),
635263509Sdim            ("invalid value for llvm.ident metadata entry operand"
636263509Sdim             "(the operand should be a string)"),
637263509Sdim            N->getOperand(0));
638263509Sdim  }
639263509Sdim}
640263509Sdim
641249259Sdimvoid Verifier::visitModuleFlags(Module &M) {
642249259Sdim  const NamedMDNode *Flags = M.getModuleFlagsMetadata();
643249259Sdim  if (!Flags) return;
644249259Sdim
645249259Sdim  // Scan each flag, and track the flags and requirements.
646249259Sdim  DenseMap<MDString*, MDNode*> SeenIDs;
647249259Sdim  SmallVector<MDNode*, 16> Requirements;
648249259Sdim  for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
649249259Sdim    visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
650249259Sdim  }
651249259Sdim
652249259Sdim  // Validate that the requirements in the module are valid.
653249259Sdim  for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
654249259Sdim    MDNode *Requirement = Requirements[I];
655249259Sdim    MDString *Flag = cast<MDString>(Requirement->getOperand(0));
656249259Sdim    Value *ReqValue = Requirement->getOperand(1);
657249259Sdim
658249259Sdim    MDNode *Op = SeenIDs.lookup(Flag);
659249259Sdim    if (!Op) {
660249259Sdim      CheckFailed("invalid requirement on flag, flag is not present in module",
661249259Sdim                  Flag);
662249259Sdim      continue;
663249259Sdim    }
664249259Sdim
665249259Sdim    if (Op->getOperand(2) != ReqValue) {
666249259Sdim      CheckFailed(("invalid requirement on flag, "
667249259Sdim                   "flag does not have the required value"),
668249259Sdim                  Flag);
669249259Sdim      continue;
670249259Sdim    }
671249259Sdim  }
672249259Sdim}
673249259Sdim
674249259Sdimvoid Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
675249259Sdim                               SmallVectorImpl<MDNode*> &Requirements) {
676249259Sdim  // Each module flag should have three arguments, the merge behavior (a
677249259Sdim  // constant int), the flag ID (an MDString), and the value.
678249259Sdim  Assert1(Op->getNumOperands() == 3,
679249259Sdim          "incorrect number of operands in module flag", Op);
680249259Sdim  ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
681249259Sdim  MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
682249259Sdim  Assert1(Behavior,
683249259Sdim          "invalid behavior operand in module flag (expected constant integer)",
684249259Sdim          Op->getOperand(0));
685249259Sdim  unsigned BehaviorValue = Behavior->getZExtValue();
686249259Sdim  Assert1(ID,
687249259Sdim          "invalid ID operand in module flag (expected metadata string)",
688249259Sdim          Op->getOperand(1));
689249259Sdim
690249259Sdim  // Sanity check the values for behaviors with additional requirements.
691249259Sdim  switch (BehaviorValue) {
692249259Sdim  default:
693249259Sdim    Assert1(false,
694249259Sdim            "invalid behavior operand in module flag (unexpected constant)",
695249259Sdim            Op->getOperand(0));
696249259Sdim    break;
697249259Sdim
698249259Sdim  case Module::Error:
699249259Sdim  case Module::Warning:
700249259Sdim  case Module::Override:
701249259Sdim    // These behavior types accept any value.
702249259Sdim    break;
703249259Sdim
704249259Sdim  case Module::Require: {
705249259Sdim    // The value should itself be an MDNode with two operands, a flag ID (an
706249259Sdim    // MDString), and a value.
707249259Sdim    MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
708249259Sdim    Assert1(Value && Value->getNumOperands() == 2,
709249259Sdim            "invalid value for 'require' module flag (expected metadata pair)",
710249259Sdim            Op->getOperand(2));
711249259Sdim    Assert1(isa<MDString>(Value->getOperand(0)),
712249259Sdim            ("invalid value for 'require' module flag "
713249259Sdim             "(first value operand should be a string)"),
714249259Sdim            Value->getOperand(0));
715249259Sdim
716249259Sdim    // Append it to the list of requirements, to check once all module flags are
717249259Sdim    // scanned.
718249259Sdim    Requirements.push_back(Value);
719249259Sdim    break;
720249259Sdim  }
721249259Sdim
722249259Sdim  case Module::Append:
723249259Sdim  case Module::AppendUnique: {
724249259Sdim    // These behavior types require the operand be an MDNode.
725249259Sdim    Assert1(isa<MDNode>(Op->getOperand(2)),
726249259Sdim            "invalid value for 'append'-type module flag "
727249259Sdim            "(expected a metadata node)", Op->getOperand(2));
728249259Sdim    break;
729249259Sdim  }
730249259Sdim  }
731249259Sdim
732249259Sdim  // Unless this is a "requires" flag, check the ID is unique.
733249259Sdim  if (BehaviorValue != Module::Require) {
734249259Sdim    bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
735249259Sdim    Assert1(Inserted,
736249259Sdim            "module flag identifiers must be unique (or of 'require' type)",
737249259Sdim            ID);
738249259Sdim  }
739249259Sdim}
740249259Sdim
741252723Sdimvoid Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
742263509Sdim                                    bool isFunction, const Value *V) {
743252723Sdim  unsigned Slot = ~0U;
744252723Sdim  for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
745252723Sdim    if (Attrs.getSlotIndex(I) == Idx) {
746252723Sdim      Slot = I;
747252723Sdim      break;
748252723Sdim    }
749252723Sdim
750252723Sdim  assert(Slot != ~0U && "Attribute set inconsistency!");
751252723Sdim
752252723Sdim  for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
753252723Sdim         I != E; ++I) {
754252723Sdim    if (I->isStringAttribute())
755252723Sdim      continue;
756252723Sdim
757252723Sdim    if (I->getKindAsEnum() == Attribute::NoReturn ||
758252723Sdim        I->getKindAsEnum() == Attribute::NoUnwind ||
759252723Sdim        I->getKindAsEnum() == Attribute::NoInline ||
760252723Sdim        I->getKindAsEnum() == Attribute::AlwaysInline ||
761252723Sdim        I->getKindAsEnum() == Attribute::OptimizeForSize ||
762252723Sdim        I->getKindAsEnum() == Attribute::StackProtect ||
763252723Sdim        I->getKindAsEnum() == Attribute::StackProtectReq ||
764252723Sdim        I->getKindAsEnum() == Attribute::StackProtectStrong ||
765252723Sdim        I->getKindAsEnum() == Attribute::NoRedZone ||
766252723Sdim        I->getKindAsEnum() == Attribute::NoImplicitFloat ||
767252723Sdim        I->getKindAsEnum() == Attribute::Naked ||
768252723Sdim        I->getKindAsEnum() == Attribute::InlineHint ||
769252723Sdim        I->getKindAsEnum() == Attribute::StackAlignment ||
770252723Sdim        I->getKindAsEnum() == Attribute::UWTable ||
771252723Sdim        I->getKindAsEnum() == Attribute::NonLazyBind ||
772252723Sdim        I->getKindAsEnum() == Attribute::ReturnsTwice ||
773252723Sdim        I->getKindAsEnum() == Attribute::SanitizeAddress ||
774252723Sdim        I->getKindAsEnum() == Attribute::SanitizeThread ||
775252723Sdim        I->getKindAsEnum() == Attribute::SanitizeMemory ||
776252723Sdim        I->getKindAsEnum() == Attribute::MinSize ||
777252723Sdim        I->getKindAsEnum() == Attribute::NoDuplicate ||
778263509Sdim        I->getKindAsEnum() == Attribute::Builtin ||
779263509Sdim        I->getKindAsEnum() == Attribute::NoBuiltin ||
780263509Sdim        I->getKindAsEnum() == Attribute::Cold ||
781263509Sdim        I->getKindAsEnum() == Attribute::OptimizeNone) {
782263509Sdim      if (!isFunction) {
783263509Sdim        CheckFailed("Attribute '" + I->getAsString() +
784263509Sdim                    "' only applies to functions!", V);
785263509Sdim        return;
786263509Sdim      }
787263509Sdim    } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
788263509Sdim               I->getKindAsEnum() == Attribute::ReadNone) {
789263509Sdim      if (Idx == 0) {
790263509Sdim        CheckFailed("Attribute '" + I->getAsString() +
791263509Sdim                    "' does not apply to function returns");
792263509Sdim        return;
793263509Sdim      }
794252723Sdim    } else if (isFunction) {
795263509Sdim      CheckFailed("Attribute '" + I->getAsString() +
796263509Sdim                  "' does not apply to functions!", V);
797263509Sdim      return;
798252723Sdim    }
799252723Sdim  }
800252723Sdim}
801252723Sdim
802249259Sdim// VerifyParameterAttrs - Check the given attributes for an argument or return
803249259Sdim// value of the specified type.  The value V is printed in error messages.
804252723Sdimvoid Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
805249259Sdim                                    bool isReturnValue, const Value *V) {
806249259Sdim  if (!Attrs.hasAttributes(Idx))
807249259Sdim    return;
808249259Sdim
809252723Sdim  VerifyAttributeTypes(Attrs, Idx, false, V);
810249259Sdim
811249259Sdim  if (isReturnValue)
812249259Sdim    Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
813249259Sdim            !Attrs.hasAttribute(Idx, Attribute::Nest) &&
814249259Sdim            !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
815252723Sdim            !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
816252723Sdim            !Attrs.hasAttribute(Idx, Attribute::Returned),
817252723Sdim            "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
818249259Sdim            "do not apply to return values!", V);
819249259Sdim
820249259Sdim  // Check for mutually incompatible attributes.
821249259Sdim  Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
822249259Sdim             Attrs.hasAttribute(Idx, Attribute::Nest)) ||
823249259Sdim            (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
824249259Sdim             Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
825249259Sdim            (Attrs.hasAttribute(Idx, Attribute::Nest) &&
826249259Sdim             Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
827249259Sdim          "'byval, nest, and sret' are incompatible!", V);
828249259Sdim
829249259Sdim  Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
830249259Sdim             Attrs.hasAttribute(Idx, Attribute::Nest)) ||
831249259Sdim            (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
832249259Sdim             Attrs.hasAttribute(Idx, Attribute::InReg)) ||
833249259Sdim            (Attrs.hasAttribute(Idx, Attribute::Nest) &&
834249259Sdim             Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
835249259Sdim          "'byval, nest, and inreg' are incompatible!", V);
836249259Sdim
837252723Sdim  Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
838252723Sdim            Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
839252723Sdim          "'sret and returned' are incompatible!", V);
840252723Sdim
841249259Sdim  Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
842249259Sdim            Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
843249259Sdim          "'zeroext and signext' are incompatible!", V);
844249259Sdim
845249259Sdim  Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
846249259Sdim            Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
847249259Sdim          "'readnone and readonly' are incompatible!", V);
848249259Sdim
849249259Sdim  Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
850249259Sdim            Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
851249259Sdim          "'noinline and alwaysinline' are incompatible!", V);
852249259Sdim
853249259Sdim  Assert1(!AttrBuilder(Attrs, Idx).
854249259Sdim            hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
855249259Sdim          "Wrong types for attribute: " +
856249259Sdim          AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
857249259Sdim
858249259Sdim  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
859249259Sdim    Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
860249259Sdim            PTy->getElementType()->isSized(),
861249259Sdim            "Attribute 'byval' does not support unsized types!", V);
862249259Sdim  else
863249259Sdim    Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
864249259Sdim            "Attribute 'byval' only applies to parameters with pointer type!",
865249259Sdim            V);
866249259Sdim}
867249259Sdim
868249259Sdim// VerifyFunctionAttrs - Check parameter attributes against a function type.
869249259Sdim// The value V is printed in error messages.
870252723Sdimvoid Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
871249259Sdim                                   const Value *V) {
872249259Sdim  if (Attrs.isEmpty())
873249259Sdim    return;
874249259Sdim
875249259Sdim  bool SawNest = false;
876252723Sdim  bool SawReturned = false;
877249259Sdim
878249259Sdim  for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
879252723Sdim    unsigned Idx = Attrs.getSlotIndex(i);
880249259Sdim
881249259Sdim    Type *Ty;
882252723Sdim    if (Idx == 0)
883249259Sdim      Ty = FT->getReturnType();
884252723Sdim    else if (Idx-1 < FT->getNumParams())
885252723Sdim      Ty = FT->getParamType(Idx-1);
886249259Sdim    else
887249259Sdim      break;  // VarArgs attributes, verified elsewhere.
888249259Sdim
889252723Sdim    VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
890249259Sdim
891252723Sdim    if (Idx == 0)
892252723Sdim      continue;
893252723Sdim
894252723Sdim    if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
895249259Sdim      Assert1(!SawNest, "More than one parameter has attribute nest!", V);
896249259Sdim      SawNest = true;
897249259Sdim    }
898249259Sdim
899252723Sdim    if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
900252723Sdim      Assert1(!SawReturned, "More than one parameter has attribute returned!",
901252723Sdim              V);
902252723Sdim      Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
903252723Sdim              "argument and return types for 'returned' attribute", V);
904252723Sdim      SawReturned = true;
905252723Sdim    }
906252723Sdim
907252723Sdim    if (Attrs.hasAttribute(Idx, Attribute::StructRet))
908252723Sdim      Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
909249259Sdim  }
910249259Sdim
911249259Sdim  if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
912249259Sdim    return;
913249259Sdim
914252723Sdim  VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
915249259Sdim
916249259Sdim  Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
917249259Sdim                               Attribute::ReadNone) &&
918249259Sdim            Attrs.hasAttribute(AttributeSet::FunctionIndex,
919249259Sdim                               Attribute::ReadOnly)),
920249259Sdim          "Attributes 'readnone and readonly' are incompatible!", V);
921249259Sdim
922249259Sdim  Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
923249259Sdim                               Attribute::NoInline) &&
924249259Sdim            Attrs.hasAttribute(AttributeSet::FunctionIndex,
925249259Sdim                               Attribute::AlwaysInline)),
926249259Sdim          "Attributes 'noinline and alwaysinline' are incompatible!", V);
927263509Sdim
928263509Sdim  if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
929263509Sdim                         Attribute::OptimizeNone)) {
930263509Sdim    Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
931263509Sdim                               Attribute::NoInline),
932263509Sdim            "Attribute 'optnone' requires 'noinline'!", V);
933263509Sdim
934263509Sdim    Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
935263509Sdim                                Attribute::OptimizeForSize),
936263509Sdim            "Attributes 'optsize and optnone' are incompatible!", V);
937263509Sdim
938263509Sdim    Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
939263509Sdim                                Attribute::MinSize),
940263509Sdim            "Attributes 'minsize and optnone' are incompatible!", V);
941263509Sdim  }
942249259Sdim}
943249259Sdim
944263509Sdimvoid Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
945263509Sdim  // Get the size of the types in bits, we'll need this later
946263509Sdim  unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
947263509Sdim  unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
948263509Sdim
949263509Sdim  // BitCast implies a no-op cast of type only. No bits change.
950263509Sdim  // However, you can't cast pointers to anything but pointers.
951263509Sdim  Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
952263509Sdim          "Bitcast requires both operands to be pointer or neither", V);
953263509Sdim  Assert1(SrcBitSize == DestBitSize,
954263509Sdim          "Bitcast requires types of same width", V);
955263509Sdim
956263509Sdim  // Disallow aggregates.
957263509Sdim  Assert1(!SrcTy->isAggregateType(),
958263509Sdim          "Bitcast operand must not be aggregate", V);
959263509Sdim  Assert1(!DestTy->isAggregateType(),
960263509Sdim          "Bitcast type must not be aggregate", V);
961263509Sdim
962263509Sdim  // Without datalayout, assume all address spaces are the same size.
963263509Sdim  // Don't check if both types are not pointers.
964263509Sdim  // Skip casts between scalars and vectors.
965263509Sdim  if (!DL ||
966263509Sdim      !SrcTy->isPtrOrPtrVectorTy() ||
967263509Sdim      !DestTy->isPtrOrPtrVectorTy() ||
968263509Sdim      SrcTy->isVectorTy() != DestTy->isVectorTy()) {
969263509Sdim    return;
970263509Sdim  }
971263509Sdim
972263509Sdim  unsigned SrcAS = SrcTy->getPointerAddressSpace();
973263509Sdim  unsigned DstAS = DestTy->getPointerAddressSpace();
974263509Sdim
975263509Sdim  Assert1(SrcAS == DstAS,
976263509Sdim          "Bitcasts between pointers of different address spaces is not legal."
977263509Sdim          "Use AddrSpaceCast instead.", V);
978263509Sdim}
979263509Sdim
980263509Sdimvoid Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
981263509Sdim  if (CE->getOpcode() == Instruction::BitCast) {
982263509Sdim    Type *SrcTy = CE->getOperand(0)->getType();
983263509Sdim    Type *DstTy = CE->getType();
984263509Sdim    VerifyBitcastType(CE, DstTy, SrcTy);
985263509Sdim  }
986263509Sdim}
987263509Sdim
988252723Sdimbool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
989249259Sdim  if (Attrs.getNumSlots() == 0)
990249259Sdim    return true;
991249259Sdim
992249259Sdim  unsigned LastSlot = Attrs.getNumSlots() - 1;
993249259Sdim  unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
994249259Sdim  if (LastIndex <= Params
995249259Sdim      || (LastIndex == AttributeSet::FunctionIndex
996249259Sdim          && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
997249259Sdim    return true;
998263509Sdim
999249259Sdim  return false;
1000249259Sdim}
1001249259Sdim
1002249259Sdim// visitFunction - Verify that a function is ok.
1003249259Sdim//
1004249259Sdimvoid Verifier::visitFunction(Function &F) {
1005249259Sdim  // Check function arguments.
1006249259Sdim  FunctionType *FT = F.getFunctionType();
1007249259Sdim  unsigned NumArgs = F.arg_size();
1008249259Sdim
1009249259Sdim  Assert1(Context == &F.getContext(),
1010249259Sdim          "Function context does not match Module context!", &F);
1011249259Sdim
1012249259Sdim  Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1013249259Sdim  Assert2(FT->getNumParams() == NumArgs,
1014249259Sdim          "# formal arguments must match # of arguments for function type!",
1015249259Sdim          &F, FT);
1016249259Sdim  Assert1(F.getReturnType()->isFirstClassType() ||
1017263509Sdim          F.getReturnType()->isVoidTy() ||
1018249259Sdim          F.getReturnType()->isStructTy(),
1019249259Sdim          "Functions cannot return aggregate values!", &F);
1020249259Sdim
1021249259Sdim  Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1022249259Sdim          "Invalid struct return type!", &F);
1023249259Sdim
1024252723Sdim  AttributeSet Attrs = F.getAttributes();
1025249259Sdim
1026249259Sdim  Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
1027249259Sdim          "Attribute after last parameter!", &F);
1028249259Sdim
1029249259Sdim  // Check function attributes.
1030249259Sdim  VerifyFunctionAttrs(FT, Attrs, &F);
1031249259Sdim
1032263509Sdim  // On function declarations/definitions, we do not support the builtin
1033263509Sdim  // attribute. We do not check this in VerifyFunctionAttrs since that is
1034263509Sdim  // checking for Attributes that can/can not ever be on functions.
1035263509Sdim  Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1036263509Sdim                              Attribute::Builtin),
1037263509Sdim          "Attribute 'builtin' can only be applied to a callsite.", &F);
1038263509Sdim
1039249259Sdim  // Check that this function meets the restrictions on this calling convention.
1040249259Sdim  switch (F.getCallingConv()) {
1041249259Sdim  default:
1042249259Sdim    break;
1043249259Sdim  case CallingConv::C:
1044249259Sdim    break;
1045249259Sdim  case CallingConv::Fast:
1046249259Sdim  case CallingConv::Cold:
1047249259Sdim  case CallingConv::X86_FastCall:
1048249259Sdim  case CallingConv::X86_ThisCall:
1049249259Sdim  case CallingConv::Intel_OCL_BI:
1050249259Sdim  case CallingConv::PTX_Kernel:
1051249259Sdim  case CallingConv::PTX_Device:
1052249259Sdim    Assert1(!F.isVarArg(),
1053249259Sdim            "Varargs functions must have C calling conventions!", &F);
1054249259Sdim    break;
1055249259Sdim  }
1056249259Sdim
1057249259Sdim  bool isLLVMdotName = F.getName().size() >= 5 &&
1058249259Sdim                       F.getName().substr(0, 5) == "llvm.";
1059249259Sdim
1060249259Sdim  // Check that the argument values match the function type for this function...
1061249259Sdim  unsigned i = 0;
1062249259Sdim  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1063249259Sdim       I != E; ++I, ++i) {
1064249259Sdim    Assert2(I->getType() == FT->getParamType(i),
1065249259Sdim            "Argument value does not match function argument type!",
1066249259Sdim            I, FT->getParamType(i));
1067249259Sdim    Assert1(I->getType()->isFirstClassType(),
1068249259Sdim            "Function arguments must have first-class types!", I);
1069249259Sdim    if (!isLLVMdotName)
1070249259Sdim      Assert2(!I->getType()->isMetadataTy(),
1071249259Sdim              "Function takes metadata but isn't an intrinsic", I, &F);
1072249259Sdim  }
1073249259Sdim
1074249259Sdim  if (F.isMaterializable()) {
1075249259Sdim    // Function has a body somewhere we can't see.
1076249259Sdim  } else if (F.isDeclaration()) {
1077249259Sdim    Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
1078249259Sdim            F.hasExternalWeakLinkage(),
1079249259Sdim            "invalid linkage type for function declaration", &F);
1080249259Sdim  } else {
1081249259Sdim    // Verify that this function (which has a body) is not named "llvm.*".  It
1082249259Sdim    // is not legal to define intrinsics.
1083249259Sdim    Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1084263509Sdim
1085249259Sdim    // Check the entry node
1086249259Sdim    BasicBlock *Entry = &F.getEntryBlock();
1087249259Sdim    Assert1(pred_begin(Entry) == pred_end(Entry),
1088249259Sdim            "Entry block to function must not have predecessors!", Entry);
1089263509Sdim
1090249259Sdim    // The address of the entry block cannot be taken, unless it is dead.
1091249259Sdim    if (Entry->hasAddressTaken()) {
1092249259Sdim      Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
1093249259Sdim              "blockaddress may not be used with the entry block!", Entry);
1094249259Sdim    }
1095249259Sdim  }
1096263509Sdim
1097249259Sdim  // If this function is actually an intrinsic, verify that it is only used in
1098249259Sdim  // direct call/invokes, never having its "address taken".
1099249259Sdim  if (F.getIntrinsicID()) {
1100249259Sdim    const User *U;
1101249259Sdim    if (F.hasAddressTaken(&U))
1102263509Sdim      Assert1(0, "Invalid user of intrinsic instruction!", U);
1103249259Sdim  }
1104249259Sdim}
1105249259Sdim
1106249259Sdim// verifyBasicBlock - Verify that a basic block is well formed...
1107249259Sdim//
1108249259Sdimvoid Verifier::visitBasicBlock(BasicBlock &BB) {
1109249259Sdim  InstsInThisBlock.clear();
1110249259Sdim
1111249259Sdim  // Ensure that basic blocks have terminators!
1112249259Sdim  Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1113249259Sdim
1114249259Sdim  // Check constraints that this basic block imposes on all of the PHI nodes in
1115249259Sdim  // it.
1116249259Sdim  if (isa<PHINode>(BB.front())) {
1117249259Sdim    SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1118249259Sdim    SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1119249259Sdim    std::sort(Preds.begin(), Preds.end());
1120249259Sdim    PHINode *PN;
1121249259Sdim    for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1122249259Sdim      // Ensure that PHI nodes have at least one entry!
1123249259Sdim      Assert1(PN->getNumIncomingValues() != 0,
1124249259Sdim              "PHI nodes must have at least one entry.  If the block is dead, "
1125249259Sdim              "the PHI should be removed!", PN);
1126249259Sdim      Assert1(PN->getNumIncomingValues() == Preds.size(),
1127249259Sdim              "PHINode should have one entry for each predecessor of its "
1128249259Sdim              "parent basic block!", PN);
1129249259Sdim
1130249259Sdim      // Get and sort all incoming values in the PHI node...
1131249259Sdim      Values.clear();
1132249259Sdim      Values.reserve(PN->getNumIncomingValues());
1133249259Sdim      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1134249259Sdim        Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1135249259Sdim                                        PN->getIncomingValue(i)));
1136249259Sdim      std::sort(Values.begin(), Values.end());
1137249259Sdim
1138249259Sdim      for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1139249259Sdim        // Check to make sure that if there is more than one entry for a
1140249259Sdim        // particular basic block in this PHI node, that the incoming values are
1141249259Sdim        // all identical.
1142249259Sdim        //
1143249259Sdim        Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
1144249259Sdim                Values[i].second == Values[i-1].second,
1145249259Sdim                "PHI node has multiple entries for the same basic block with "
1146249259Sdim                "different incoming values!", PN, Values[i].first,
1147249259Sdim                Values[i].second, Values[i-1].second);
1148249259Sdim
1149249259Sdim        // Check to make sure that the predecessors and PHI node entries are
1150249259Sdim        // matched up.
1151249259Sdim        Assert3(Values[i].first == Preds[i],
1152249259Sdim                "PHI node entries do not match predecessors!", PN,
1153249259Sdim                Values[i].first, Preds[i]);
1154249259Sdim      }
1155249259Sdim    }
1156249259Sdim  }
1157249259Sdim}
1158249259Sdim
1159249259Sdimvoid Verifier::visitTerminatorInst(TerminatorInst &I) {
1160249259Sdim  // Ensure that terminators only exist at the end of the basic block.
1161249259Sdim  Assert1(&I == I.getParent()->getTerminator(),
1162249259Sdim          "Terminator found in the middle of a basic block!", I.getParent());
1163249259Sdim  visitInstruction(I);
1164249259Sdim}
1165249259Sdim
1166249259Sdimvoid Verifier::visitBranchInst(BranchInst &BI) {
1167249259Sdim  if (BI.isConditional()) {
1168249259Sdim    Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1169249259Sdim            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1170249259Sdim  }
1171249259Sdim  visitTerminatorInst(BI);
1172249259Sdim}
1173249259Sdim
1174249259Sdimvoid Verifier::visitReturnInst(ReturnInst &RI) {
1175249259Sdim  Function *F = RI.getParent()->getParent();
1176249259Sdim  unsigned N = RI.getNumOperands();
1177263509Sdim  if (F->getReturnType()->isVoidTy())
1178249259Sdim    Assert2(N == 0,
1179249259Sdim            "Found return instr that returns non-void in Function of void "
1180249259Sdim            "return type!", &RI, F->getReturnType());
1181249259Sdim  else
1182249259Sdim    Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1183249259Sdim            "Function return type does not match operand "
1184249259Sdim            "type of return inst!", &RI, F->getReturnType());
1185249259Sdim
1186249259Sdim  // Check to make sure that the return value has necessary properties for
1187249259Sdim  // terminators...
1188249259Sdim  visitTerminatorInst(RI);
1189249259Sdim}
1190249259Sdim
1191249259Sdimvoid Verifier::visitSwitchInst(SwitchInst &SI) {
1192249259Sdim  // Check to make sure that all of the constants in the switch instruction
1193249259Sdim  // have the same type as the switched-on value.
1194249259Sdim  Type *SwitchTy = SI.getCondition()->getType();
1195263509Sdim  SmallPtrSet<ConstantInt*, 32> Constants;
1196249259Sdim  for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1197263509Sdim    Assert1(i.getCaseValue()->getType() == SwitchTy,
1198263509Sdim            "Switch constants must all be same type as switch value!", &SI);
1199263509Sdim    Assert2(Constants.insert(i.getCaseValue()),
1200263509Sdim            "Duplicate integer as switch case", &SI, i.getCaseValue());
1201249259Sdim  }
1202263509Sdim
1203249259Sdim  visitTerminatorInst(SI);
1204249259Sdim}
1205249259Sdim
1206249259Sdimvoid Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1207249259Sdim  Assert1(BI.getAddress()->getType()->isPointerTy(),
1208249259Sdim          "Indirectbr operand must have pointer type!", &BI);
1209249259Sdim  for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1210249259Sdim    Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1211249259Sdim            "Indirectbr destinations must all have pointer type!", &BI);
1212249259Sdim
1213249259Sdim  visitTerminatorInst(BI);
1214249259Sdim}
1215249259Sdim
1216249259Sdimvoid Verifier::visitSelectInst(SelectInst &SI) {
1217249259Sdim  Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1218249259Sdim                                          SI.getOperand(2)),
1219249259Sdim          "Invalid operands for select instruction!", &SI);
1220249259Sdim
1221249259Sdim  Assert1(SI.getTrueValue()->getType() == SI.getType(),
1222249259Sdim          "Select values must have same type as select instruction!", &SI);
1223249259Sdim  visitInstruction(SI);
1224249259Sdim}
1225249259Sdim
1226249259Sdim/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1227249259Sdim/// a pass, if any exist, it's an error.
1228249259Sdim///
1229249259Sdimvoid Verifier::visitUserOp1(Instruction &I) {
1230249259Sdim  Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1231249259Sdim}
1232249259Sdim
1233249259Sdimvoid Verifier::visitTruncInst(TruncInst &I) {
1234249259Sdim  // Get the source and destination types
1235249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1236249259Sdim  Type *DestTy = I.getType();
1237249259Sdim
1238249259Sdim  // Get the size of the types in bits, we'll need this later
1239249259Sdim  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1240249259Sdim  unsigned DestBitSize = DestTy->getScalarSizeInBits();
1241249259Sdim
1242249259Sdim  Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1243249259Sdim  Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1244249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1245249259Sdim          "trunc source and destination must both be a vector or neither", &I);
1246249259Sdim  Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1247249259Sdim
1248249259Sdim  visitInstruction(I);
1249249259Sdim}
1250249259Sdim
1251249259Sdimvoid Verifier::visitZExtInst(ZExtInst &I) {
1252249259Sdim  // Get the source and destination types
1253249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1254249259Sdim  Type *DestTy = I.getType();
1255249259Sdim
1256249259Sdim  // Get the size of the types in bits, we'll need this later
1257249259Sdim  Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1258249259Sdim  Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1259249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1260249259Sdim          "zext source and destination must both be a vector or neither", &I);
1261249259Sdim  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1262249259Sdim  unsigned DestBitSize = DestTy->getScalarSizeInBits();
1263249259Sdim
1264249259Sdim  Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1265249259Sdim
1266249259Sdim  visitInstruction(I);
1267249259Sdim}
1268249259Sdim
1269249259Sdimvoid Verifier::visitSExtInst(SExtInst &I) {
1270249259Sdim  // Get the source and destination types
1271249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1272249259Sdim  Type *DestTy = I.getType();
1273249259Sdim
1274249259Sdim  // Get the size of the types in bits, we'll need this later
1275249259Sdim  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1276249259Sdim  unsigned DestBitSize = DestTy->getScalarSizeInBits();
1277249259Sdim
1278249259Sdim  Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1279249259Sdim  Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1280249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1281249259Sdim          "sext source and destination must both be a vector or neither", &I);
1282249259Sdim  Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1283249259Sdim
1284249259Sdim  visitInstruction(I);
1285249259Sdim}
1286249259Sdim
1287249259Sdimvoid Verifier::visitFPTruncInst(FPTruncInst &I) {
1288249259Sdim  // Get the source and destination types
1289249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1290249259Sdim  Type *DestTy = I.getType();
1291249259Sdim  // Get the size of the types in bits, we'll need this later
1292249259Sdim  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1293249259Sdim  unsigned DestBitSize = DestTy->getScalarSizeInBits();
1294249259Sdim
1295249259Sdim  Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1296249259Sdim  Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1297249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1298249259Sdim          "fptrunc source and destination must both be a vector or neither",&I);
1299249259Sdim  Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1300249259Sdim
1301249259Sdim  visitInstruction(I);
1302249259Sdim}
1303249259Sdim
1304249259Sdimvoid Verifier::visitFPExtInst(FPExtInst &I) {
1305249259Sdim  // Get the source and destination types
1306249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1307249259Sdim  Type *DestTy = I.getType();
1308249259Sdim
1309249259Sdim  // Get the size of the types in bits, we'll need this later
1310249259Sdim  unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1311249259Sdim  unsigned DestBitSize = DestTy->getScalarSizeInBits();
1312249259Sdim
1313249259Sdim  Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1314249259Sdim  Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1315249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1316249259Sdim          "fpext source and destination must both be a vector or neither", &I);
1317249259Sdim  Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1318249259Sdim
1319249259Sdim  visitInstruction(I);
1320249259Sdim}
1321249259Sdim
1322249259Sdimvoid Verifier::visitUIToFPInst(UIToFPInst &I) {
1323249259Sdim  // Get the source and destination types
1324249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1325249259Sdim  Type *DestTy = I.getType();
1326249259Sdim
1327249259Sdim  bool SrcVec = SrcTy->isVectorTy();
1328249259Sdim  bool DstVec = DestTy->isVectorTy();
1329249259Sdim
1330249259Sdim  Assert1(SrcVec == DstVec,
1331249259Sdim          "UIToFP source and dest must both be vector or scalar", &I);
1332249259Sdim  Assert1(SrcTy->isIntOrIntVectorTy(),
1333249259Sdim          "UIToFP source must be integer or integer vector", &I);
1334249259Sdim  Assert1(DestTy->isFPOrFPVectorTy(),
1335249259Sdim          "UIToFP result must be FP or FP vector", &I);
1336249259Sdim
1337249259Sdim  if (SrcVec && DstVec)
1338249259Sdim    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1339249259Sdim            cast<VectorType>(DestTy)->getNumElements(),
1340249259Sdim            "UIToFP source and dest vector length mismatch", &I);
1341249259Sdim
1342249259Sdim  visitInstruction(I);
1343249259Sdim}
1344249259Sdim
1345249259Sdimvoid Verifier::visitSIToFPInst(SIToFPInst &I) {
1346249259Sdim  // Get the source and destination types
1347249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1348249259Sdim  Type *DestTy = I.getType();
1349249259Sdim
1350249259Sdim  bool SrcVec = SrcTy->isVectorTy();
1351249259Sdim  bool DstVec = DestTy->isVectorTy();
1352249259Sdim
1353249259Sdim  Assert1(SrcVec == DstVec,
1354249259Sdim          "SIToFP source and dest must both be vector or scalar", &I);
1355249259Sdim  Assert1(SrcTy->isIntOrIntVectorTy(),
1356249259Sdim          "SIToFP source must be integer or integer vector", &I);
1357249259Sdim  Assert1(DestTy->isFPOrFPVectorTy(),
1358249259Sdim          "SIToFP result must be FP or FP vector", &I);
1359249259Sdim
1360249259Sdim  if (SrcVec && DstVec)
1361249259Sdim    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1362249259Sdim            cast<VectorType>(DestTy)->getNumElements(),
1363249259Sdim            "SIToFP source and dest vector length mismatch", &I);
1364249259Sdim
1365249259Sdim  visitInstruction(I);
1366249259Sdim}
1367249259Sdim
1368249259Sdimvoid Verifier::visitFPToUIInst(FPToUIInst &I) {
1369249259Sdim  // Get the source and destination types
1370249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1371249259Sdim  Type *DestTy = I.getType();
1372249259Sdim
1373249259Sdim  bool SrcVec = SrcTy->isVectorTy();
1374249259Sdim  bool DstVec = DestTy->isVectorTy();
1375249259Sdim
1376249259Sdim  Assert1(SrcVec == DstVec,
1377249259Sdim          "FPToUI source and dest must both be vector or scalar", &I);
1378249259Sdim  Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1379249259Sdim          &I);
1380249259Sdim  Assert1(DestTy->isIntOrIntVectorTy(),
1381249259Sdim          "FPToUI result must be integer or integer vector", &I);
1382249259Sdim
1383249259Sdim  if (SrcVec && DstVec)
1384249259Sdim    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1385249259Sdim            cast<VectorType>(DestTy)->getNumElements(),
1386249259Sdim            "FPToUI source and dest vector length mismatch", &I);
1387249259Sdim
1388249259Sdim  visitInstruction(I);
1389249259Sdim}
1390249259Sdim
1391249259Sdimvoid Verifier::visitFPToSIInst(FPToSIInst &I) {
1392249259Sdim  // Get the source and destination types
1393249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1394249259Sdim  Type *DestTy = I.getType();
1395249259Sdim
1396249259Sdim  bool SrcVec = SrcTy->isVectorTy();
1397249259Sdim  bool DstVec = DestTy->isVectorTy();
1398249259Sdim
1399249259Sdim  Assert1(SrcVec == DstVec,
1400249259Sdim          "FPToSI source and dest must both be vector or scalar", &I);
1401249259Sdim  Assert1(SrcTy->isFPOrFPVectorTy(),
1402249259Sdim          "FPToSI source must be FP or FP vector", &I);
1403249259Sdim  Assert1(DestTy->isIntOrIntVectorTy(),
1404249259Sdim          "FPToSI result must be integer or integer vector", &I);
1405249259Sdim
1406249259Sdim  if (SrcVec && DstVec)
1407249259Sdim    Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1408249259Sdim            cast<VectorType>(DestTy)->getNumElements(),
1409249259Sdim            "FPToSI source and dest vector length mismatch", &I);
1410249259Sdim
1411249259Sdim  visitInstruction(I);
1412249259Sdim}
1413249259Sdim
1414249259Sdimvoid Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1415249259Sdim  // Get the source and destination types
1416249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1417249259Sdim  Type *DestTy = I.getType();
1418249259Sdim
1419249259Sdim  Assert1(SrcTy->getScalarType()->isPointerTy(),
1420249259Sdim          "PtrToInt source must be pointer", &I);
1421249259Sdim  Assert1(DestTy->getScalarType()->isIntegerTy(),
1422249259Sdim          "PtrToInt result must be integral", &I);
1423249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1424249259Sdim          "PtrToInt type mismatch", &I);
1425249259Sdim
1426249259Sdim  if (SrcTy->isVectorTy()) {
1427249259Sdim    VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1428249259Sdim    VectorType *VDest = dyn_cast<VectorType>(DestTy);
1429249259Sdim    Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1430249259Sdim          "PtrToInt Vector width mismatch", &I);
1431249259Sdim  }
1432249259Sdim
1433249259Sdim  visitInstruction(I);
1434249259Sdim}
1435249259Sdim
1436249259Sdimvoid Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1437249259Sdim  // Get the source and destination types
1438249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1439249259Sdim  Type *DestTy = I.getType();
1440249259Sdim
1441249259Sdim  Assert1(SrcTy->getScalarType()->isIntegerTy(),
1442249259Sdim          "IntToPtr source must be an integral", &I);
1443249259Sdim  Assert1(DestTy->getScalarType()->isPointerTy(),
1444249259Sdim          "IntToPtr result must be a pointer",&I);
1445249259Sdim  Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1446249259Sdim          "IntToPtr type mismatch", &I);
1447249259Sdim  if (SrcTy->isVectorTy()) {
1448249259Sdim    VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1449249259Sdim    VectorType *VDest = dyn_cast<VectorType>(DestTy);
1450249259Sdim    Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1451249259Sdim          "IntToPtr Vector width mismatch", &I);
1452249259Sdim  }
1453249259Sdim  visitInstruction(I);
1454249259Sdim}
1455249259Sdim
1456249259Sdimvoid Verifier::visitBitCastInst(BitCastInst &I) {
1457249259Sdim  Type *SrcTy = I.getOperand(0)->getType();
1458249259Sdim  Type *DestTy = I.getType();
1459263509Sdim  VerifyBitcastType(&I, DestTy, SrcTy);
1460263509Sdim  visitInstruction(I);
1461263509Sdim}
1462249259Sdim
1463263509Sdimvoid Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1464263509Sdim  Type *SrcTy = I.getOperand(0)->getType();
1465263509Sdim  Type *DestTy = I.getType();
1466249259Sdim
1467263509Sdim  Assert1(SrcTy->isPtrOrPtrVectorTy(),
1468263509Sdim          "AddrSpaceCast source must be a pointer", &I);
1469263509Sdim  Assert1(DestTy->isPtrOrPtrVectorTy(),
1470263509Sdim          "AddrSpaceCast result must be a pointer", &I);
1471263509Sdim  Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1472263509Sdim          "AddrSpaceCast must be between different address spaces", &I);
1473263509Sdim  if (SrcTy->isVectorTy())
1474263509Sdim    Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1475263509Sdim            "AddrSpaceCast vector pointer number of elements mismatch", &I);
1476249259Sdim  visitInstruction(I);
1477249259Sdim}
1478249259Sdim
1479249259Sdim/// visitPHINode - Ensure that a PHI node is well formed.
1480249259Sdim///
1481249259Sdimvoid Verifier::visitPHINode(PHINode &PN) {
1482249259Sdim  // Ensure that the PHI nodes are all grouped together at the top of the block.
1483249259Sdim  // This can be tested by checking whether the instruction before this is
1484249259Sdim  // either nonexistent (because this is begin()) or is a PHI node.  If not,
1485249259Sdim  // then there is some other instruction before a PHI.
1486263509Sdim  Assert2(&PN == &PN.getParent()->front() ||
1487249259Sdim          isa<PHINode>(--BasicBlock::iterator(&PN)),
1488249259Sdim          "PHI nodes not grouped at top of basic block!",
1489249259Sdim          &PN, PN.getParent());
1490249259Sdim
1491249259Sdim  // Check that all of the values of the PHI node have the same type as the
1492249259Sdim  // result, and that the incoming blocks are really basic blocks.
1493249259Sdim  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1494249259Sdim    Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1495249259Sdim            "PHI node operands are not the same type as the result!", &PN);
1496249259Sdim  }
1497249259Sdim
1498249259Sdim  // All other PHI node constraints are checked in the visitBasicBlock method.
1499249259Sdim
1500249259Sdim  visitInstruction(PN);
1501249259Sdim}
1502249259Sdim
1503249259Sdimvoid Verifier::VerifyCallSite(CallSite CS) {
1504249259Sdim  Instruction *I = CS.getInstruction();
1505249259Sdim
1506249259Sdim  Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1507249259Sdim          "Called function must be a pointer!", I);
1508249259Sdim  PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1509249259Sdim
1510249259Sdim  Assert1(FPTy->getElementType()->isFunctionTy(),
1511249259Sdim          "Called function is not pointer to function type!", I);
1512249259Sdim  FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1513249259Sdim
1514249259Sdim  // Verify that the correct number of arguments are being passed
1515249259Sdim  if (FTy->isVarArg())
1516249259Sdim    Assert1(CS.arg_size() >= FTy->getNumParams(),
1517249259Sdim            "Called function requires more parameters than were provided!",I);
1518249259Sdim  else
1519249259Sdim    Assert1(CS.arg_size() == FTy->getNumParams(),
1520249259Sdim            "Incorrect number of arguments passed to called function!", I);
1521249259Sdim
1522249259Sdim  // Verify that all arguments to the call match the function type.
1523249259Sdim  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1524249259Sdim    Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1525249259Sdim            "Call parameter type does not match function signature!",
1526249259Sdim            CS.getArgument(i), FTy->getParamType(i), I);
1527249259Sdim
1528252723Sdim  AttributeSet Attrs = CS.getAttributes();
1529249259Sdim
1530249259Sdim  Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1531249259Sdim          "Attribute after last parameter!", I);
1532249259Sdim
1533249259Sdim  // Verify call attributes.
1534249259Sdim  VerifyFunctionAttrs(FTy, Attrs, I);
1535249259Sdim
1536252723Sdim  if (FTy->isVarArg()) {
1537252723Sdim    // FIXME? is 'nest' even legal here?
1538252723Sdim    bool SawNest = false;
1539252723Sdim    bool SawReturned = false;
1540252723Sdim
1541252723Sdim    for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1542252723Sdim      if (Attrs.hasAttribute(Idx, Attribute::Nest))
1543252723Sdim        SawNest = true;
1544252723Sdim      if (Attrs.hasAttribute(Idx, Attribute::Returned))
1545252723Sdim        SawReturned = true;
1546252723Sdim    }
1547252723Sdim
1548249259Sdim    // Check attributes on the varargs part.
1549249259Sdim    for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1550263509Sdim      Type *Ty = CS.getArgument(Idx-1)->getType();
1551252723Sdim      VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1552263509Sdim
1553252723Sdim      if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1554252723Sdim        Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1555252723Sdim        SawNest = true;
1556252723Sdim      }
1557249259Sdim
1558252723Sdim      if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1559252723Sdim        Assert1(!SawReturned, "More than one parameter has attribute returned!",
1560252723Sdim                I);
1561252723Sdim        Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1562252723Sdim                "Incompatible argument and return types for 'returned' "
1563252723Sdim                "attribute", I);
1564252723Sdim        SawReturned = true;
1565252723Sdim      }
1566252723Sdim
1567249259Sdim      Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1568249259Sdim              "Attribute 'sret' cannot be used for vararg call arguments!", I);
1569249259Sdim    }
1570252723Sdim  }
1571249259Sdim
1572249259Sdim  // Verify that there's no metadata unless it's a direct call to an intrinsic.
1573249259Sdim  if (CS.getCalledFunction() == 0 ||
1574249259Sdim      !CS.getCalledFunction()->getName().startswith("llvm.")) {
1575249259Sdim    for (FunctionType::param_iterator PI = FTy->param_begin(),
1576249259Sdim           PE = FTy->param_end(); PI != PE; ++PI)
1577249259Sdim      Assert1(!(*PI)->isMetadataTy(),
1578249259Sdim              "Function has metadata parameter but isn't an intrinsic", I);
1579249259Sdim  }
1580249259Sdim
1581249259Sdim  visitInstruction(*I);
1582249259Sdim}
1583249259Sdim
1584249259Sdimvoid Verifier::visitCallInst(CallInst &CI) {
1585249259Sdim  VerifyCallSite(&CI);
1586249259Sdim
1587249259Sdim  if (Function *F = CI.getCalledFunction())
1588249259Sdim    if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1589249259Sdim      visitIntrinsicFunctionCall(ID, CI);
1590249259Sdim}
1591249259Sdim
1592249259Sdimvoid Verifier::visitInvokeInst(InvokeInst &II) {
1593249259Sdim  VerifyCallSite(&II);
1594249259Sdim
1595249259Sdim  // Verify that there is a landingpad instruction as the first non-PHI
1596249259Sdim  // instruction of the 'unwind' destination.
1597249259Sdim  Assert1(II.getUnwindDest()->isLandingPad(),
1598249259Sdim          "The unwind destination does not have a landingpad instruction!",&II);
1599249259Sdim
1600249259Sdim  visitTerminatorInst(II);
1601249259Sdim}
1602249259Sdim
1603249259Sdim/// visitBinaryOperator - Check that both arguments to the binary operator are
1604249259Sdim/// of the same type!
1605249259Sdim///
1606249259Sdimvoid Verifier::visitBinaryOperator(BinaryOperator &B) {
1607249259Sdim  Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1608249259Sdim          "Both operands to a binary operator are not of the same type!", &B);
1609249259Sdim
1610249259Sdim  switch (B.getOpcode()) {
1611249259Sdim  // Check that integer arithmetic operators are only used with
1612249259Sdim  // integral operands.
1613249259Sdim  case Instruction::Add:
1614249259Sdim  case Instruction::Sub:
1615249259Sdim  case Instruction::Mul:
1616249259Sdim  case Instruction::SDiv:
1617249259Sdim  case Instruction::UDiv:
1618249259Sdim  case Instruction::SRem:
1619249259Sdim  case Instruction::URem:
1620249259Sdim    Assert1(B.getType()->isIntOrIntVectorTy(),
1621249259Sdim            "Integer arithmetic operators only work with integral types!", &B);
1622249259Sdim    Assert1(B.getType() == B.getOperand(0)->getType(),
1623249259Sdim            "Integer arithmetic operators must have same type "
1624249259Sdim            "for operands and result!", &B);
1625249259Sdim    break;
1626249259Sdim  // Check that floating-point arithmetic operators are only used with
1627249259Sdim  // floating-point operands.
1628249259Sdim  case Instruction::FAdd:
1629249259Sdim  case Instruction::FSub:
1630249259Sdim  case Instruction::FMul:
1631249259Sdim  case Instruction::FDiv:
1632249259Sdim  case Instruction::FRem:
1633249259Sdim    Assert1(B.getType()->isFPOrFPVectorTy(),
1634249259Sdim            "Floating-point arithmetic operators only work with "
1635249259Sdim            "floating-point types!", &B);
1636249259Sdim    Assert1(B.getType() == B.getOperand(0)->getType(),
1637249259Sdim            "Floating-point arithmetic operators must have same type "
1638249259Sdim            "for operands and result!", &B);
1639249259Sdim    break;
1640249259Sdim  // Check that logical operators are only used with integral operands.
1641249259Sdim  case Instruction::And:
1642249259Sdim  case Instruction::Or:
1643249259Sdim  case Instruction::Xor:
1644249259Sdim    Assert1(B.getType()->isIntOrIntVectorTy(),
1645249259Sdim            "Logical operators only work with integral types!", &B);
1646249259Sdim    Assert1(B.getType() == B.getOperand(0)->getType(),
1647249259Sdim            "Logical operators must have same type for operands and result!",
1648249259Sdim            &B);
1649249259Sdim    break;
1650249259Sdim  case Instruction::Shl:
1651249259Sdim  case Instruction::LShr:
1652249259Sdim  case Instruction::AShr:
1653249259Sdim    Assert1(B.getType()->isIntOrIntVectorTy(),
1654249259Sdim            "Shifts only work with integral types!", &B);
1655249259Sdim    Assert1(B.getType() == B.getOperand(0)->getType(),
1656249259Sdim            "Shift return type must be same as operands!", &B);
1657249259Sdim    break;
1658249259Sdim  default:
1659249259Sdim    llvm_unreachable("Unknown BinaryOperator opcode!");
1660249259Sdim  }
1661249259Sdim
1662249259Sdim  visitInstruction(B);
1663249259Sdim}
1664249259Sdim
1665249259Sdimvoid Verifier::visitICmpInst(ICmpInst &IC) {
1666249259Sdim  // Check that the operands are the same type
1667249259Sdim  Type *Op0Ty = IC.getOperand(0)->getType();
1668249259Sdim  Type *Op1Ty = IC.getOperand(1)->getType();
1669249259Sdim  Assert1(Op0Ty == Op1Ty,
1670249259Sdim          "Both operands to ICmp instruction are not of the same type!", &IC);
1671249259Sdim  // Check that the operands are the right type
1672249259Sdim  Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1673249259Sdim          "Invalid operand types for ICmp instruction", &IC);
1674249259Sdim  // Check that the predicate is valid.
1675249259Sdim  Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1676249259Sdim          IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1677249259Sdim          "Invalid predicate in ICmp instruction!", &IC);
1678249259Sdim
1679249259Sdim  visitInstruction(IC);
1680249259Sdim}
1681249259Sdim
1682249259Sdimvoid Verifier::visitFCmpInst(FCmpInst &FC) {
1683249259Sdim  // Check that the operands are the same type
1684249259Sdim  Type *Op0Ty = FC.getOperand(0)->getType();
1685249259Sdim  Type *Op1Ty = FC.getOperand(1)->getType();
1686249259Sdim  Assert1(Op0Ty == Op1Ty,
1687249259Sdim          "Both operands to FCmp instruction are not of the same type!", &FC);
1688249259Sdim  // Check that the operands are the right type
1689249259Sdim  Assert1(Op0Ty->isFPOrFPVectorTy(),
1690249259Sdim          "Invalid operand types for FCmp instruction", &FC);
1691249259Sdim  // Check that the predicate is valid.
1692249259Sdim  Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1693249259Sdim          FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1694249259Sdim          "Invalid predicate in FCmp instruction!", &FC);
1695249259Sdim
1696249259Sdim  visitInstruction(FC);
1697249259Sdim}
1698249259Sdim
1699249259Sdimvoid Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1700249259Sdim  Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1701249259Sdim                                              EI.getOperand(1)),
1702249259Sdim          "Invalid extractelement operands!", &EI);
1703249259Sdim  visitInstruction(EI);
1704249259Sdim}
1705249259Sdim
1706249259Sdimvoid Verifier::visitInsertElementInst(InsertElementInst &IE) {
1707249259Sdim  Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1708249259Sdim                                             IE.getOperand(1),
1709249259Sdim                                             IE.getOperand(2)),
1710249259Sdim          "Invalid insertelement operands!", &IE);
1711249259Sdim  visitInstruction(IE);
1712249259Sdim}
1713249259Sdim
1714249259Sdimvoid Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1715249259Sdim  Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1716249259Sdim                                             SV.getOperand(2)),
1717249259Sdim          "Invalid shufflevector operands!", &SV);
1718249259Sdim  visitInstruction(SV);
1719249259Sdim}
1720249259Sdim
1721249259Sdimvoid Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1722249259Sdim  Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1723249259Sdim
1724249259Sdim  Assert1(isa<PointerType>(TargetTy),
1725249259Sdim    "GEP base pointer is not a vector or a vector of pointers", &GEP);
1726249259Sdim  Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1727249259Sdim          "GEP into unsized type!", &GEP);
1728249259Sdim  Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1729249259Sdim          GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1730249259Sdim          &GEP);
1731249259Sdim
1732249259Sdim  SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1733249259Sdim  Type *ElTy =
1734249259Sdim    GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1735249259Sdim  Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1736249259Sdim
1737249259Sdim  Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1738249259Sdim          cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1739249259Sdim          == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1740249259Sdim
1741249259Sdim  if (GEP.getPointerOperandType()->isVectorTy()) {
1742249259Sdim    // Additional checks for vector GEPs.
1743249259Sdim    unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1744249259Sdim    Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1745249259Sdim            "Vector GEP result width doesn't match operand's", &GEP);
1746249259Sdim    for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1747249259Sdim      Type *IndexTy = Idxs[i]->getType();
1748249259Sdim      Assert1(IndexTy->isVectorTy(),
1749249259Sdim              "Vector GEP must have vector indices!", &GEP);
1750249259Sdim      unsigned IndexWidth = IndexTy->getVectorNumElements();
1751249259Sdim      Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1752249259Sdim    }
1753249259Sdim  }
1754249259Sdim  visitInstruction(GEP);
1755249259Sdim}
1756249259Sdim
1757249259Sdimstatic bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1758249259Sdim  return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1759249259Sdim}
1760249259Sdim
1761249259Sdimvoid Verifier::visitLoadInst(LoadInst &LI) {
1762249259Sdim  PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1763249259Sdim  Assert1(PTy, "Load operand must be a pointer.", &LI);
1764249259Sdim  Type *ElTy = PTy->getElementType();
1765249259Sdim  Assert2(ElTy == LI.getType(),
1766249259Sdim          "Load result type does not match pointer operand type!", &LI, ElTy);
1767249259Sdim  if (LI.isAtomic()) {
1768249259Sdim    Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1769249259Sdim            "Load cannot have Release ordering", &LI);
1770249259Sdim    Assert1(LI.getAlignment() != 0,
1771249259Sdim            "Atomic load must specify explicit alignment", &LI);
1772249259Sdim    if (!ElTy->isPointerTy()) {
1773249259Sdim      Assert2(ElTy->isIntegerTy(),
1774249259Sdim              "atomic store operand must have integer type!",
1775249259Sdim              &LI, ElTy);
1776249259Sdim      unsigned Size = ElTy->getPrimitiveSizeInBits();
1777249259Sdim      Assert2(Size >= 8 && !(Size & (Size - 1)),
1778249259Sdim              "atomic store operand must be power-of-two byte-sized integer",
1779249259Sdim              &LI, ElTy);
1780249259Sdim    }
1781249259Sdim  } else {
1782249259Sdim    Assert1(LI.getSynchScope() == CrossThread,
1783249259Sdim            "Non-atomic load cannot have SynchronizationScope specified", &LI);
1784249259Sdim  }
1785249259Sdim
1786249259Sdim  if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1787249259Sdim    unsigned NumOperands = Range->getNumOperands();
1788249259Sdim    Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1789249259Sdim    unsigned NumRanges = NumOperands / 2;
1790249259Sdim    Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1791249259Sdim
1792249259Sdim    ConstantRange LastRange(1); // Dummy initial value
1793249259Sdim    for (unsigned i = 0; i < NumRanges; ++i) {
1794249259Sdim      ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1795249259Sdim      Assert1(Low, "The lower limit must be an integer!", Low);
1796249259Sdim      ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1797249259Sdim      Assert1(High, "The upper limit must be an integer!", High);
1798249259Sdim      Assert1(High->getType() == Low->getType() &&
1799249259Sdim              High->getType() == ElTy, "Range types must match load type!",
1800249259Sdim              &LI);
1801249259Sdim
1802249259Sdim      APInt HighV = High->getValue();
1803249259Sdim      APInt LowV = Low->getValue();
1804249259Sdim      ConstantRange CurRange(LowV, HighV);
1805249259Sdim      Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1806249259Sdim              "Range must not be empty!", Range);
1807249259Sdim      if (i != 0) {
1808249259Sdim        Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1809249259Sdim                "Intervals are overlapping", Range);
1810249259Sdim        Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1811249259Sdim                Range);
1812249259Sdim        Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1813249259Sdim                Range);
1814249259Sdim      }
1815249259Sdim      LastRange = ConstantRange(LowV, HighV);
1816249259Sdim    }
1817249259Sdim    if (NumRanges > 2) {
1818249259Sdim      APInt FirstLow =
1819249259Sdim        dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1820249259Sdim      APInt FirstHigh =
1821249259Sdim        dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1822249259Sdim      ConstantRange FirstRange(FirstLow, FirstHigh);
1823249259Sdim      Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1824249259Sdim              "Intervals are overlapping", Range);
1825249259Sdim      Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1826249259Sdim              Range);
1827249259Sdim    }
1828249259Sdim
1829249259Sdim
1830249259Sdim  }
1831249259Sdim
1832249259Sdim  visitInstruction(LI);
1833249259Sdim}
1834249259Sdim
1835249259Sdimvoid Verifier::visitStoreInst(StoreInst &SI) {
1836249259Sdim  PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1837249259Sdim  Assert1(PTy, "Store operand must be a pointer.", &SI);
1838249259Sdim  Type *ElTy = PTy->getElementType();
1839249259Sdim  Assert2(ElTy == SI.getOperand(0)->getType(),
1840249259Sdim          "Stored value type does not match pointer operand type!",
1841249259Sdim          &SI, ElTy);
1842249259Sdim  if (SI.isAtomic()) {
1843249259Sdim    Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1844249259Sdim            "Store cannot have Acquire ordering", &SI);
1845249259Sdim    Assert1(SI.getAlignment() != 0,
1846249259Sdim            "Atomic store must specify explicit alignment", &SI);
1847249259Sdim    if (!ElTy->isPointerTy()) {
1848249259Sdim      Assert2(ElTy->isIntegerTy(),
1849249259Sdim              "atomic store operand must have integer type!",
1850249259Sdim              &SI, ElTy);
1851249259Sdim      unsigned Size = ElTy->getPrimitiveSizeInBits();
1852249259Sdim      Assert2(Size >= 8 && !(Size & (Size - 1)),
1853249259Sdim              "atomic store operand must be power-of-two byte-sized integer",
1854249259Sdim              &SI, ElTy);
1855249259Sdim    }
1856249259Sdim  } else {
1857249259Sdim    Assert1(SI.getSynchScope() == CrossThread,
1858249259Sdim            "Non-atomic store cannot have SynchronizationScope specified", &SI);
1859249259Sdim  }
1860249259Sdim  visitInstruction(SI);
1861249259Sdim}
1862249259Sdim
1863249259Sdimvoid Verifier::visitAllocaInst(AllocaInst &AI) {
1864249259Sdim  PointerType *PTy = AI.getType();
1865263509Sdim  Assert1(PTy->getAddressSpace() == 0,
1866249259Sdim          "Allocation instruction pointer not in the generic address space!",
1867249259Sdim          &AI);
1868249259Sdim  Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1869249259Sdim          &AI);
1870249259Sdim  Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1871249259Sdim          "Alloca array size must have integer type", &AI);
1872249259Sdim  visitInstruction(AI);
1873249259Sdim}
1874249259Sdim
1875249259Sdimvoid Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1876249259Sdim  Assert1(CXI.getOrdering() != NotAtomic,
1877249259Sdim          "cmpxchg instructions must be atomic.", &CXI);
1878249259Sdim  Assert1(CXI.getOrdering() != Unordered,
1879249259Sdim          "cmpxchg instructions cannot be unordered.", &CXI);
1880249259Sdim  PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1881249259Sdim  Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1882249259Sdim  Type *ElTy = PTy->getElementType();
1883249259Sdim  Assert2(ElTy->isIntegerTy(),
1884249259Sdim          "cmpxchg operand must have integer type!",
1885249259Sdim          &CXI, ElTy);
1886249259Sdim  unsigned Size = ElTy->getPrimitiveSizeInBits();
1887249259Sdim  Assert2(Size >= 8 && !(Size & (Size - 1)),
1888249259Sdim          "cmpxchg operand must be power-of-two byte-sized integer",
1889249259Sdim          &CXI, ElTy);
1890249259Sdim  Assert2(ElTy == CXI.getOperand(1)->getType(),
1891249259Sdim          "Expected value type does not match pointer operand type!",
1892249259Sdim          &CXI, ElTy);
1893249259Sdim  Assert2(ElTy == CXI.getOperand(2)->getType(),
1894249259Sdim          "Stored value type does not match pointer operand type!",
1895249259Sdim          &CXI, ElTy);
1896249259Sdim  visitInstruction(CXI);
1897249259Sdim}
1898249259Sdim
1899249259Sdimvoid Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1900249259Sdim  Assert1(RMWI.getOrdering() != NotAtomic,
1901249259Sdim          "atomicrmw instructions must be atomic.", &RMWI);
1902249259Sdim  Assert1(RMWI.getOrdering() != Unordered,
1903249259Sdim          "atomicrmw instructions cannot be unordered.", &RMWI);
1904249259Sdim  PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1905249259Sdim  Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1906249259Sdim  Type *ElTy = PTy->getElementType();
1907249259Sdim  Assert2(ElTy->isIntegerTy(),
1908249259Sdim          "atomicrmw operand must have integer type!",
1909249259Sdim          &RMWI, ElTy);
1910249259Sdim  unsigned Size = ElTy->getPrimitiveSizeInBits();
1911249259Sdim  Assert2(Size >= 8 && !(Size & (Size - 1)),
1912249259Sdim          "atomicrmw operand must be power-of-two byte-sized integer",
1913249259Sdim          &RMWI, ElTy);
1914249259Sdim  Assert2(ElTy == RMWI.getOperand(1)->getType(),
1915249259Sdim          "Argument value type does not match pointer operand type!",
1916249259Sdim          &RMWI, ElTy);
1917249259Sdim  Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1918249259Sdim          RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1919249259Sdim          "Invalid binary operation!", &RMWI);
1920249259Sdim  visitInstruction(RMWI);
1921249259Sdim}
1922249259Sdim
1923249259Sdimvoid Verifier::visitFenceInst(FenceInst &FI) {
1924249259Sdim  const AtomicOrdering Ordering = FI.getOrdering();
1925249259Sdim  Assert1(Ordering == Acquire || Ordering == Release ||
1926249259Sdim          Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1927249259Sdim          "fence instructions may only have "
1928249259Sdim          "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1929249259Sdim  visitInstruction(FI);
1930249259Sdim}
1931249259Sdim
1932249259Sdimvoid Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1933249259Sdim  Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1934249259Sdim                                           EVI.getIndices()) ==
1935249259Sdim          EVI.getType(),
1936249259Sdim          "Invalid ExtractValueInst operands!", &EVI);
1937263509Sdim
1938249259Sdim  visitInstruction(EVI);
1939249259Sdim}
1940249259Sdim
1941249259Sdimvoid Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1942249259Sdim  Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1943249259Sdim                                           IVI.getIndices()) ==
1944249259Sdim          IVI.getOperand(1)->getType(),
1945249259Sdim          "Invalid InsertValueInst operands!", &IVI);
1946263509Sdim
1947249259Sdim  visitInstruction(IVI);
1948249259Sdim}
1949249259Sdim
1950249259Sdimvoid Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1951249259Sdim  BasicBlock *BB = LPI.getParent();
1952249259Sdim
1953249259Sdim  // The landingpad instruction is ill-formed if it doesn't have any clauses and
1954249259Sdim  // isn't a cleanup.
1955249259Sdim  Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1956249259Sdim          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1957249259Sdim
1958249259Sdim  // The landingpad instruction defines its parent as a landing pad block. The
1959249259Sdim  // landing pad block may be branched to only by the unwind edge of an invoke.
1960249259Sdim  for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1961249259Sdim    const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1962249259Sdim    Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1963249259Sdim            "Block containing LandingPadInst must be jumped to "
1964249259Sdim            "only by the unwind edge of an invoke.", &LPI);
1965249259Sdim  }
1966249259Sdim
1967249259Sdim  // The landingpad instruction must be the first non-PHI instruction in the
1968249259Sdim  // block.
1969249259Sdim  Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1970249259Sdim          "LandingPadInst not the first non-PHI instruction in the block.",
1971249259Sdim          &LPI);
1972249259Sdim
1973249259Sdim  // The personality functions for all landingpad instructions within the same
1974249259Sdim  // function should match.
1975249259Sdim  if (PersonalityFn)
1976249259Sdim    Assert1(LPI.getPersonalityFn() == PersonalityFn,
1977249259Sdim            "Personality function doesn't match others in function", &LPI);
1978249259Sdim  PersonalityFn = LPI.getPersonalityFn();
1979249259Sdim
1980249259Sdim  // All operands must be constants.
1981249259Sdim  Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1982249259Sdim          &LPI);
1983249259Sdim  for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1984249259Sdim    Value *Clause = LPI.getClause(i);
1985249259Sdim    Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1986249259Sdim    if (LPI.isCatch(i)) {
1987249259Sdim      Assert1(isa<PointerType>(Clause->getType()),
1988249259Sdim              "Catch operand does not have pointer type!", &LPI);
1989249259Sdim    } else {
1990249259Sdim      Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1991249259Sdim      Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1992249259Sdim              "Filter operand is not an array of constants!", &LPI);
1993249259Sdim    }
1994249259Sdim  }
1995249259Sdim
1996249259Sdim  visitInstruction(LPI);
1997249259Sdim}
1998249259Sdim
1999249259Sdimvoid Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2000249259Sdim  Instruction *Op = cast<Instruction>(I.getOperand(i));
2001249259Sdim  // If the we have an invalid invoke, don't try to compute the dominance.
2002249259Sdim  // We already reject it in the invoke specific checks and the dominance
2003249259Sdim  // computation doesn't handle multiple edges.
2004249259Sdim  if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2005249259Sdim    if (II->getNormalDest() == II->getUnwindDest())
2006249259Sdim      return;
2007249259Sdim  }
2008249259Sdim
2009249259Sdim  const Use &U = I.getOperandUse(i);
2010249259Sdim  Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
2011249259Sdim          "Instruction does not dominate all uses!", Op, &I);
2012249259Sdim}
2013249259Sdim
2014249259Sdim/// verifyInstruction - Verify that an instruction is well formed.
2015249259Sdim///
2016249259Sdimvoid Verifier::visitInstruction(Instruction &I) {
2017249259Sdim  BasicBlock *BB = I.getParent();
2018249259Sdim  Assert1(BB, "Instruction not embedded in basic block!", &I);
2019249259Sdim
2020249259Sdim  if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
2021249259Sdim    for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
2022249259Sdim         UI != UE; ++UI)
2023249259Sdim      Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
2024249259Sdim              "Only PHI nodes may reference their own value!", &I);
2025249259Sdim  }
2026249259Sdim
2027249259Sdim  // Check that void typed values don't have names
2028249259Sdim  Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2029249259Sdim          "Instruction has a name, but provides a void value!", &I);
2030249259Sdim
2031249259Sdim  // Check that the return value of the instruction is either void or a legal
2032249259Sdim  // value type.
2033263509Sdim  Assert1(I.getType()->isVoidTy() ||
2034249259Sdim          I.getType()->isFirstClassType(),
2035249259Sdim          "Instruction returns a non-scalar type!", &I);
2036249259Sdim
2037249259Sdim  // Check that the instruction doesn't produce metadata. Calls are already
2038249259Sdim  // checked against the callee type.
2039249259Sdim  Assert1(!I.getType()->isMetadataTy() ||
2040249259Sdim          isa<CallInst>(I) || isa<InvokeInst>(I),
2041249259Sdim          "Invalid use of metadata!", &I);
2042249259Sdim
2043249259Sdim  // Check that all uses of the instruction, if they are instructions
2044249259Sdim  // themselves, actually have parent basic blocks.  If the use is not an
2045249259Sdim  // instruction, it is an error!
2046249259Sdim  for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
2047249259Sdim       UI != UE; ++UI) {
2048249259Sdim    if (Instruction *Used = dyn_cast<Instruction>(*UI))
2049249259Sdim      Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2050249259Sdim              " embedded in a basic block!", &I, Used);
2051249259Sdim    else {
2052249259Sdim      CheckFailed("Use of instruction is not an instruction!", *UI);
2053249259Sdim      return;
2054249259Sdim    }
2055249259Sdim  }
2056249259Sdim
2057249259Sdim  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2058249259Sdim    Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2059249259Sdim
2060249259Sdim    // Check to make sure that only first-class-values are operands to
2061249259Sdim    // instructions.
2062249259Sdim    if (!I.getOperand(i)->getType()->isFirstClassType()) {
2063249259Sdim      Assert1(0, "Instruction operands must be first-class values!", &I);
2064249259Sdim    }
2065249259Sdim
2066249259Sdim    if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2067249259Sdim      // Check to make sure that the "address of" an intrinsic function is never
2068249259Sdim      // taken.
2069249259Sdim      Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2070249259Sdim              "Cannot take the address of an intrinsic!", &I);
2071249259Sdim      Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2072249259Sdim              F->getIntrinsicID() == Intrinsic::donothing,
2073249259Sdim              "Cannot invoke an intrinsinc other than donothing", &I);
2074249259Sdim      Assert1(F->getParent() == Mod, "Referencing function in another module!",
2075249259Sdim              &I);
2076249259Sdim    } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2077249259Sdim      Assert1(OpBB->getParent() == BB->getParent(),
2078249259Sdim              "Referring to a basic block in another function!", &I);
2079249259Sdim    } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2080249259Sdim      Assert1(OpArg->getParent() == BB->getParent(),
2081249259Sdim              "Referring to an argument in another function!", &I);
2082249259Sdim    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2083249259Sdim      Assert1(GV->getParent() == Mod, "Referencing global in another module!",
2084249259Sdim              &I);
2085249259Sdim    } else if (isa<Instruction>(I.getOperand(i))) {
2086249259Sdim      verifyDominatesUse(I, i);
2087249259Sdim    } else if (isa<InlineAsm>(I.getOperand(i))) {
2088249259Sdim      Assert1((i + 1 == e && isa<CallInst>(I)) ||
2089249259Sdim              (i + 3 == e && isa<InvokeInst>(I)),
2090249259Sdim              "Cannot take the address of an inline asm!", &I);
2091263509Sdim    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2092263509Sdim      if (CE->getType()->isPtrOrPtrVectorTy()) {
2093263509Sdim        // If we have a ConstantExpr pointer, we need to see if it came from an
2094263509Sdim        // illegal bitcast (inttoptr <constant int> )
2095263509Sdim        SmallVector<const ConstantExpr *, 4> Stack;
2096263509Sdim        SmallPtrSet<const ConstantExpr *, 4> Visited;
2097263509Sdim        Stack.push_back(CE);
2098263509Sdim
2099263509Sdim        while (!Stack.empty()) {
2100263509Sdim          const ConstantExpr *V = Stack.pop_back_val();
2101263509Sdim          if (!Visited.insert(V))
2102263509Sdim            continue;
2103263509Sdim
2104263509Sdim          VerifyConstantExprBitcastType(V);
2105263509Sdim
2106263509Sdim          for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2107263509Sdim            if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2108263509Sdim              Stack.push_back(Op);
2109263509Sdim          }
2110263509Sdim        }
2111263509Sdim      }
2112249259Sdim    }
2113249259Sdim  }
2114249259Sdim
2115249259Sdim  if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2116249259Sdim    Assert1(I.getType()->isFPOrFPVectorTy(),
2117249259Sdim            "fpmath requires a floating point result!", &I);
2118249259Sdim    Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2119249259Sdim    Value *Op0 = MD->getOperand(0);
2120249259Sdim    if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2121249259Sdim      APFloat Accuracy = CFP0->getValueAPF();
2122263509Sdim      Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2123249259Sdim              "fpmath accuracy not a positive number!", &I);
2124249259Sdim    } else {
2125249259Sdim      Assert1(false, "invalid fpmath accuracy!", &I);
2126249259Sdim    }
2127249259Sdim  }
2128249259Sdim
2129249259Sdim  MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2130249259Sdim  Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2131249259Sdim
2132263509Sdim  if (!DisableDebugInfoVerifier) {
2133263509Sdim    MD = I.getMetadata(LLVMContext::MD_dbg);
2134263509Sdim    Finder.processLocation(*Mod, DILocation(MD));
2135263509Sdim  }
2136263509Sdim
2137249259Sdim  InstsInThisBlock.insert(&I);
2138249259Sdim}
2139249259Sdim
2140249259Sdim/// VerifyIntrinsicType - Verify that the specified type (which comes from an
2141249259Sdim/// intrinsic argument or return value) matches the type constraints specified
2142249259Sdim/// by the .td file (e.g. an "any integer" argument really is an integer).
2143249259Sdim///
2144249259Sdim/// This return true on error but does not print a message.
2145249259Sdimbool Verifier::VerifyIntrinsicType(Type *Ty,
2146249259Sdim                                   ArrayRef<Intrinsic::IITDescriptor> &Infos,
2147249259Sdim                                   SmallVectorImpl<Type*> &ArgTys) {
2148249259Sdim  using namespace Intrinsic;
2149249259Sdim
2150249259Sdim  // If we ran out of descriptors, there are too many arguments.
2151263509Sdim  if (Infos.empty()) return true;
2152249259Sdim  IITDescriptor D = Infos.front();
2153249259Sdim  Infos = Infos.slice(1);
2154263509Sdim
2155249259Sdim  switch (D.Kind) {
2156249259Sdim  case IITDescriptor::Void: return !Ty->isVoidTy();
2157263509Sdim  case IITDescriptor::VarArg: return true;
2158249259Sdim  case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2159249259Sdim  case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2160249259Sdim  case IITDescriptor::Half: return !Ty->isHalfTy();
2161249259Sdim  case IITDescriptor::Float: return !Ty->isFloatTy();
2162249259Sdim  case IITDescriptor::Double: return !Ty->isDoubleTy();
2163249259Sdim  case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2164249259Sdim  case IITDescriptor::Vector: {
2165249259Sdim    VectorType *VT = dyn_cast<VectorType>(Ty);
2166249259Sdim    return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2167249259Sdim           VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2168249259Sdim  }
2169249259Sdim  case IITDescriptor::Pointer: {
2170249259Sdim    PointerType *PT = dyn_cast<PointerType>(Ty);
2171249259Sdim    return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2172249259Sdim           VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2173249259Sdim  }
2174263509Sdim
2175249259Sdim  case IITDescriptor::Struct: {
2176249259Sdim    StructType *ST = dyn_cast<StructType>(Ty);
2177249259Sdim    if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2178249259Sdim      return true;
2179263509Sdim
2180249259Sdim    for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2181249259Sdim      if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2182249259Sdim        return true;
2183249259Sdim    return false;
2184249259Sdim  }
2185263509Sdim
2186249259Sdim  case IITDescriptor::Argument:
2187249259Sdim    // Two cases here - If this is the second occurrence of an argument, verify
2188263509Sdim    // that the later instance matches the previous instance.
2189249259Sdim    if (D.getArgumentNumber() < ArgTys.size())
2190263509Sdim      return Ty != ArgTys[D.getArgumentNumber()];
2191263509Sdim
2192249259Sdim    // Otherwise, if this is the first instance of an argument, record it and
2193249259Sdim    // verify the "Any" kind.
2194249259Sdim    assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2195249259Sdim    ArgTys.push_back(Ty);
2196263509Sdim
2197249259Sdim    switch (D.getArgumentKind()) {
2198249259Sdim    case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2199249259Sdim    case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2200249259Sdim    case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2201249259Sdim    case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2202249259Sdim    }
2203249259Sdim    llvm_unreachable("all argument kinds not covered");
2204263509Sdim
2205249259Sdim  case IITDescriptor::ExtendVecArgument:
2206249259Sdim    // This may only be used when referring to a previous vector argument.
2207249259Sdim    return D.getArgumentNumber() >= ArgTys.size() ||
2208249259Sdim           !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2209249259Sdim           VectorType::getExtendedElementVectorType(
2210249259Sdim                       cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2211249259Sdim
2212249259Sdim  case IITDescriptor::TruncVecArgument:
2213249259Sdim    // This may only be used when referring to a previous vector argument.
2214249259Sdim    return D.getArgumentNumber() >= ArgTys.size() ||
2215249259Sdim           !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2216249259Sdim           VectorType::getTruncatedElementVectorType(
2217249259Sdim                         cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2218249259Sdim  }
2219249259Sdim  llvm_unreachable("unhandled");
2220249259Sdim}
2221249259Sdim
2222263509Sdim/// \brief Verify if the intrinsic has variable arguments.
2223263509Sdim/// This method is intended to be called after all the fixed arguments have been
2224263509Sdim/// verified first.
2225263509Sdim///
2226263509Sdim/// This method returns true on error and does not print an error message.
2227263509Sdimbool
2228263509SdimVerifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2229263509Sdim                                  ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2230263509Sdim  using namespace Intrinsic;
2231263509Sdim
2232263509Sdim  // If there are no descriptors left, then it can't be a vararg.
2233263509Sdim  if (Infos.empty())
2234263509Sdim    return isVarArg ? true : false;
2235263509Sdim
2236263509Sdim  // There should be only one descriptor remaining at this point.
2237263509Sdim  if (Infos.size() != 1)
2238263509Sdim    return true;
2239263509Sdim
2240263509Sdim  // Check and verify the descriptor.
2241263509Sdim  IITDescriptor D = Infos.front();
2242263509Sdim  Infos = Infos.slice(1);
2243263509Sdim  if (D.Kind == IITDescriptor::VarArg)
2244263509Sdim    return isVarArg ? false : true;
2245263509Sdim
2246263509Sdim  return true;
2247263509Sdim}
2248263509Sdim
2249249259Sdim/// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2250249259Sdim///
2251249259Sdimvoid Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2252249259Sdim  Function *IF = CI.getCalledFunction();
2253249259Sdim  Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2254249259Sdim          IF);
2255249259Sdim
2256249259Sdim  // Verify that the intrinsic prototype lines up with what the .td files
2257249259Sdim  // describe.
2258249259Sdim  FunctionType *IFTy = IF->getFunctionType();
2259263509Sdim  bool IsVarArg = IFTy->isVarArg();
2260263509Sdim
2261249259Sdim  SmallVector<Intrinsic::IITDescriptor, 8> Table;
2262249259Sdim  getIntrinsicInfoTableEntries(ID, Table);
2263249259Sdim  ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2264249259Sdim
2265249259Sdim  SmallVector<Type *, 4> ArgTys;
2266249259Sdim  Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2267249259Sdim          "Intrinsic has incorrect return type!", IF);
2268249259Sdim  for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2269249259Sdim    Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2270249259Sdim            "Intrinsic has incorrect argument type!", IF);
2271263509Sdim
2272263509Sdim  // Verify if the intrinsic call matches the vararg property.
2273263509Sdim  if (IsVarArg)
2274263509Sdim    Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2275263509Sdim            "Intrinsic was not defined with variable arguments!", IF);
2276263509Sdim  else
2277263509Sdim    Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2278263509Sdim            "Callsite was not defined with variable arguments!", IF);
2279263509Sdim
2280263509Sdim  // All descriptors should be absorbed by now.
2281249259Sdim  Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2282249259Sdim
2283249259Sdim  // Now that we have the intrinsic ID and the actual argument types (and we
2284249259Sdim  // know they are legal for the intrinsic!) get the intrinsic name through the
2285249259Sdim  // usual means.  This allows us to verify the mangling of argument types into
2286249259Sdim  // the name.
2287249259Sdim  Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2288249259Sdim          "Intrinsic name not mangled correctly for type arguments!", IF);
2289263509Sdim
2290249259Sdim  // If the intrinsic takes MDNode arguments, verify that they are either global
2291249259Sdim  // or are local to *this* function.
2292249259Sdim  for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2293249259Sdim    if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2294249259Sdim      visitMDNode(*MD, CI.getParent()->getParent());
2295249259Sdim
2296249259Sdim  switch (ID) {
2297249259Sdim  default:
2298249259Sdim    break;
2299249259Sdim  case Intrinsic::ctlz:  // llvm.ctlz
2300249259Sdim  case Intrinsic::cttz:  // llvm.cttz
2301249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2302249259Sdim            "is_zero_undef argument of bit counting intrinsics must be a "
2303249259Sdim            "constant int", &CI);
2304249259Sdim    break;
2305249259Sdim  case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2306249259Sdim    Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2307249259Sdim                "invalid llvm.dbg.declare intrinsic call 1", &CI);
2308249259Sdim    MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2309249259Sdim    Assert1(MD->getNumOperands() == 1,
2310249259Sdim                "invalid llvm.dbg.declare intrinsic call 2", &CI);
2311263509Sdim    if (!DisableDebugInfoVerifier)
2312263509Sdim      Finder.processDeclare(*Mod, cast<DbgDeclareInst>(&CI));
2313249259Sdim  } break;
2314263509Sdim  case Intrinsic::dbg_value: { //llvm.dbg.value
2315263509Sdim    if (!DisableDebugInfoVerifier) {
2316263509Sdim      Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2317263509Sdim              "invalid llvm.dbg.value intrinsic call 1", &CI);
2318263509Sdim      Finder.processValue(*Mod, cast<DbgValueInst>(&CI));
2319263509Sdim    }
2320263509Sdim    break;
2321263509Sdim  }
2322249259Sdim  case Intrinsic::memcpy:
2323249259Sdim  case Intrinsic::memmove:
2324249259Sdim  case Intrinsic::memset:
2325249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2326249259Sdim            "alignment argument of memory intrinsics must be a constant int",
2327249259Sdim            &CI);
2328249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2329249259Sdim            "isvolatile argument of memory intrinsics must be a constant int",
2330249259Sdim            &CI);
2331249259Sdim    break;
2332249259Sdim  case Intrinsic::gcroot:
2333249259Sdim  case Intrinsic::gcwrite:
2334249259Sdim  case Intrinsic::gcread:
2335249259Sdim    if (ID == Intrinsic::gcroot) {
2336249259Sdim      AllocaInst *AI =
2337249259Sdim        dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2338249259Sdim      Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2339249259Sdim      Assert1(isa<Constant>(CI.getArgOperand(1)),
2340249259Sdim              "llvm.gcroot parameter #2 must be a constant.", &CI);
2341249259Sdim      if (!AI->getType()->getElementType()->isPointerTy()) {
2342249259Sdim        Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2343249259Sdim                "llvm.gcroot parameter #1 must either be a pointer alloca, "
2344249259Sdim                "or argument #2 must be a non-null constant.", &CI);
2345249259Sdim      }
2346249259Sdim    }
2347249259Sdim
2348249259Sdim    Assert1(CI.getParent()->getParent()->hasGC(),
2349249259Sdim            "Enclosing function does not use GC.", &CI);
2350249259Sdim    break;
2351249259Sdim  case Intrinsic::init_trampoline:
2352249259Sdim    Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2353249259Sdim            "llvm.init_trampoline parameter #2 must resolve to a function.",
2354249259Sdim            &CI);
2355249259Sdim    break;
2356249259Sdim  case Intrinsic::prefetch:
2357249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2358249259Sdim            isa<ConstantInt>(CI.getArgOperand(2)) &&
2359249259Sdim            cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2360249259Sdim            cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2361249259Sdim            "invalid arguments to llvm.prefetch",
2362249259Sdim            &CI);
2363249259Sdim    break;
2364249259Sdim  case Intrinsic::stackprotector:
2365249259Sdim    Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2366249259Sdim            "llvm.stackprotector parameter #2 must resolve to an alloca.",
2367249259Sdim            &CI);
2368249259Sdim    break;
2369249259Sdim  case Intrinsic::lifetime_start:
2370249259Sdim  case Intrinsic::lifetime_end:
2371249259Sdim  case Intrinsic::invariant_start:
2372249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2373249259Sdim            "size argument of memory use markers must be a constant integer",
2374249259Sdim            &CI);
2375249259Sdim    break;
2376249259Sdim  case Intrinsic::invariant_end:
2377249259Sdim    Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2378249259Sdim            "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2379249259Sdim    break;
2380249259Sdim  }
2381249259Sdim}
2382249259Sdim
2383263509Sdimvoid Verifier::verifyDebugInfo() {
2384263509Sdim  // Verify Debug Info.
2385263509Sdim  if (!DisableDebugInfoVerifier) {
2386263509Sdim    for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2387263509Sdim         E = Finder.compile_unit_end(); I != E; ++I)
2388263509Sdim      Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2389263509Sdim    for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2390263509Sdim         E = Finder.subprogram_end(); I != E; ++I)
2391263509Sdim      Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2392263509Sdim    for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2393263509Sdim         E = Finder.global_variable_end(); I != E; ++I)
2394263509Sdim      Assert1(DIGlobalVariable(*I).Verify(),
2395263509Sdim              "DIGlobalVariable does not Verify!", *I);
2396263509Sdim    for (DebugInfoFinder::iterator I = Finder.type_begin(),
2397263509Sdim         E = Finder.type_end(); I != E; ++I)
2398263509Sdim      Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2399263509Sdim    for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2400263509Sdim         E = Finder.scope_end(); I != E; ++I)
2401263509Sdim      Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2402263509Sdim  }
2403263509Sdim}
2404263509Sdim
2405249259Sdim//===----------------------------------------------------------------------===//
2406249259Sdim//  Implement the public interfaces to this file...
2407249259Sdim//===----------------------------------------------------------------------===//
2408249259Sdim
2409249259SdimFunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2410249259Sdim  return new Verifier(action);
2411249259Sdim}
2412249259Sdim
2413249259Sdim
2414249259Sdim/// verifyFunction - Check a function for errors, printing messages on stderr.
2415249259Sdim/// Return true if the function is corrupt.
2416249259Sdim///
2417249259Sdimbool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2418249259Sdim  Function &F = const_cast<Function&>(f);
2419249259Sdim  assert(!F.isDeclaration() && "Cannot verify external functions");
2420249259Sdim
2421249259Sdim  FunctionPassManager FPM(F.getParent());
2422249259Sdim  Verifier *V = new Verifier(action);
2423249259Sdim  FPM.add(V);
2424263509Sdim  FPM.doInitialization();
2425249259Sdim  FPM.run(F);
2426249259Sdim  return V->Broken;
2427249259Sdim}
2428249259Sdim
2429249259Sdim/// verifyModule - Check a module for errors, printing messages on stderr.
2430249259Sdim/// Return true if the module is corrupt.
2431249259Sdim///
2432249259Sdimbool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2433249259Sdim                        std::string *ErrorInfo) {
2434249259Sdim  PassManager PM;
2435249259Sdim  Verifier *V = new Verifier(action);
2436249259Sdim  PM.add(V);
2437249259Sdim  PM.run(const_cast<Module&>(M));
2438249259Sdim
2439249259Sdim  if (ErrorInfo && V->Broken)
2440249259Sdim    *ErrorInfo = V->MessagesStr.str();
2441249259Sdim  return V->Broken;
2442249259Sdim}
2443