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