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