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