dc723f63ea981bdafdf3a1c75fe50a824e3b6146
[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 //  * Landingpad instructions must be in a function with a personality function.
43 //  * All other things that are tested by asserts spread about the code...
44 //
45 //===----------------------------------------------------------------------===//
46
47 #include "llvm/IR/Verifier.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/CallSite.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/ConstantRange.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DebugInfo.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/Dominators.h"
62 #include "llvm/IR/InlineAsm.h"
63 #include "llvm/IR/InstIterator.h"
64 #include "llvm/IR/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/IR/Statepoint.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
81
82 namespace {
83 struct VerifierSupport {
84   raw_ostream &OS;
85   const Module *M;
86
87   /// \brief Track the brokenness of the module while recursively visiting.
88   bool Broken;
89
90   explicit VerifierSupport(raw_ostream &OS)
91       : OS(OS), M(nullptr), Broken(false) {}
92
93 private:
94   template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
95     Write(&*I);
96   }
97
98   void Write(const Module *M) {
99     if (!M)
100       return;
101     OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
102   }
103
104   void Write(const Value *V) {
105     if (!V)
106       return;
107     if (isa<Instruction>(V)) {
108       OS << *V << '\n';
109     } else {
110       V->printAsOperand(OS, true, M);
111       OS << '\n';
112     }
113   }
114   void Write(ImmutableCallSite CS) {
115     Write(CS.getInstruction());
116   }
117
118   void Write(const Metadata *MD) {
119     if (!MD)
120       return;
121     MD->print(OS, M);
122     OS << '\n';
123   }
124
125   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
126     Write(MD.get());
127   }
128
129   void Write(const NamedMDNode *NMD) {
130     if (!NMD)
131       return;
132     NMD->print(OS);
133     OS << '\n';
134   }
135
136   void Write(Type *T) {
137     if (!T)
138       return;
139     OS << ' ' << *T;
140   }
141
142   void Write(const Comdat *C) {
143     if (!C)
144       return;
145     OS << *C;
146   }
147
148   template <typename T1, typename... Ts>
149   void WriteTs(const T1 &V1, const Ts &... Vs) {
150     Write(V1);
151     WriteTs(Vs...);
152   }
153
154   template <typename... Ts> void WriteTs() {}
155
156 public:
157   /// \brief A check failed, so printout out the condition and the message.
158   ///
159   /// This provides a nice place to put a breakpoint if you want to see why
160   /// something is not correct.
161   void CheckFailed(const Twine &Message) {
162     OS << Message << '\n';
163     Broken = true;
164   }
165
166   /// \brief A check failed (with values to print).
167   ///
168   /// This calls the Message-only version so that the above is easier to set a
169   /// breakpoint on.
170   template <typename T1, typename... Ts>
171   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
172     CheckFailed(Message);
173     WriteTs(V1, Vs...);
174   }
175 };
176
177 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
178   friend class InstVisitor<Verifier>;
179
180   LLVMContext *Context;
181   DominatorTree DT;
182
183   /// \brief When verifying a basic block, keep track of all of the
184   /// instructions we have seen so far.
185   ///
186   /// This allows us to do efficient dominance checks for the case when an
187   /// instruction has an operand that is an instruction in the same block.
188   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
189
190   /// \brief Keep track of the metadata nodes that have been checked already.
191   SmallPtrSet<const Metadata *, 32> MDNodes;
192
193   /// \brief Track unresolved string-based type references.
194   SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
195
196   /// \brief The result type for a landingpad.
197   Type *LandingPadResultTy;
198
199   /// \brief Whether we've seen a call to @llvm.localescape in this function
200   /// already.
201   bool SawFrameEscape;
202
203   /// Stores the count of how many objects were passed to llvm.localescape for a
204   /// given function and the largest index passed to llvm.localrecover.
205   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
206
207   /// Cache of constants visited in search of ConstantExprs.
208   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
209
210   void checkAtomicMemAccessSize(const Module *M, Type *Ty,
211                                 const Instruction *I);
212 public:
213   explicit Verifier(raw_ostream &OS)
214       : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
215         SawFrameEscape(false) {}
216
217   bool verify(const Function &F) {
218     M = F.getParent();
219     Context = &M->getContext();
220
221     // First ensure the function is well-enough formed to compute dominance
222     // information.
223     if (F.empty()) {
224       OS << "Function '" << F.getName()
225          << "' does not contain an entry block!\n";
226       return false;
227     }
228     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
229       if (I->empty() || !I->back().isTerminator()) {
230         OS << "Basic Block in function '" << F.getName()
231            << "' does not have terminator!\n";
232         I->printAsOperand(OS, true);
233         OS << "\n";
234         return false;
235       }
236     }
237
238     // Now directly compute a dominance tree. We don't rely on the pass
239     // manager to provide this as it isolates us from a potentially
240     // out-of-date dominator tree and makes it significantly more complex to
241     // run this code outside of a pass manager.
242     // FIXME: It's really gross that we have to cast away constness here.
243     DT.recalculate(const_cast<Function &>(F));
244
245     Broken = false;
246     // FIXME: We strip const here because the inst visitor strips const.
247     visit(const_cast<Function &>(F));
248     InstsInThisBlock.clear();
249     LandingPadResultTy = nullptr;
250     SawFrameEscape = false;
251
252     return !Broken;
253   }
254
255   bool verify(const Module &M) {
256     this->M = &M;
257     Context = &M.getContext();
258     Broken = false;
259
260     // Scan through, checking all of the external function's linkage now...
261     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
262       visitGlobalValue(*I);
263
264       // Check to make sure function prototypes are okay.
265       if (I->isDeclaration())
266         visitFunction(*I);
267     }
268
269     // Now that we've visited every function, verify that we never asked to
270     // recover a frame index that wasn't escaped.
271     verifyFrameRecoverIndices();
272
273     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
274          I != E; ++I)
275       visitGlobalVariable(*I);
276
277     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
278          I != E; ++I)
279       visitGlobalAlias(*I);
280
281     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
282                                                E = M.named_metadata_end();
283          I != E; ++I)
284       visitNamedMDNode(*I);
285
286     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
287       visitComdat(SMEC.getValue());
288
289     visitModuleFlags(M);
290     visitModuleIdents(M);
291
292     // Verify type referneces last.
293     verifyTypeRefs();
294
295     return !Broken;
296   }
297
298 private:
299   // Verification methods...
300   void visitGlobalValue(const GlobalValue &GV);
301   void visitGlobalVariable(const GlobalVariable &GV);
302   void visitGlobalAlias(const GlobalAlias &GA);
303   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
304   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
305                            const GlobalAlias &A, const Constant &C);
306   void visitNamedMDNode(const NamedMDNode &NMD);
307   void visitMDNode(const MDNode &MD);
308   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
309   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
310   void visitComdat(const Comdat &C);
311   void visitModuleIdents(const Module &M);
312   void visitModuleFlags(const Module &M);
313   void visitModuleFlag(const MDNode *Op,
314                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
315                        SmallVectorImpl<const MDNode *> &Requirements);
316   void visitFunction(const Function &F);
317   void visitBasicBlock(BasicBlock &BB);
318   void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
319   void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
320
321   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
322 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
323 #include "llvm/IR/Metadata.def"
324   void visitDIScope(const DIScope &N);
325   void visitDIVariable(const DIVariable &N);
326   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
327   void visitDITemplateParameter(const DITemplateParameter &N);
328
329   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
330
331   /// \brief Check for a valid string-based type reference.
332   ///
333   /// Checks if \c MD is a string-based type reference.  If it is, keeps track
334   /// of it (and its user, \c N) for error messages later.
335   bool isValidUUID(const MDNode &N, const Metadata *MD);
336
337   /// \brief Check for a valid type reference.
338   ///
339   /// Checks for subclasses of \a DIType, or \a isValidUUID().
340   bool isTypeRef(const MDNode &N, const Metadata *MD);
341
342   /// \brief Check for a valid scope reference.
343   ///
344   /// Checks for subclasses of \a DIScope, or \a isValidUUID().
345   bool isScopeRef(const MDNode &N, const Metadata *MD);
346
347   /// \brief Check for a valid debug info reference.
348   ///
349   /// Checks for subclasses of \a DINode, or \a isValidUUID().
350   bool isDIRef(const MDNode &N, const Metadata *MD);
351
352   // InstVisitor overrides...
353   using InstVisitor<Verifier>::visit;
354   void visit(Instruction &I);
355
356   void visitTruncInst(TruncInst &I);
357   void visitZExtInst(ZExtInst &I);
358   void visitSExtInst(SExtInst &I);
359   void visitFPTruncInst(FPTruncInst &I);
360   void visitFPExtInst(FPExtInst &I);
361   void visitFPToUIInst(FPToUIInst &I);
362   void visitFPToSIInst(FPToSIInst &I);
363   void visitUIToFPInst(UIToFPInst &I);
364   void visitSIToFPInst(SIToFPInst &I);
365   void visitIntToPtrInst(IntToPtrInst &I);
366   void visitPtrToIntInst(PtrToIntInst &I);
367   void visitBitCastInst(BitCastInst &I);
368   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
369   void visitPHINode(PHINode &PN);
370   void visitBinaryOperator(BinaryOperator &B);
371   void visitICmpInst(ICmpInst &IC);
372   void visitFCmpInst(FCmpInst &FC);
373   void visitExtractElementInst(ExtractElementInst &EI);
374   void visitInsertElementInst(InsertElementInst &EI);
375   void visitShuffleVectorInst(ShuffleVectorInst &EI);
376   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
377   void visitCallInst(CallInst &CI);
378   void visitInvokeInst(InvokeInst &II);
379   void visitGetElementPtrInst(GetElementPtrInst &GEP);
380   void visitLoadInst(LoadInst &LI);
381   void visitStoreInst(StoreInst &SI);
382   void verifyDominatesUse(Instruction &I, unsigned i);
383   void visitInstruction(Instruction &I);
384   void visitTerminatorInst(TerminatorInst &I);
385   void visitBranchInst(BranchInst &BI);
386   void visitReturnInst(ReturnInst &RI);
387   void visitSwitchInst(SwitchInst &SI);
388   void visitIndirectBrInst(IndirectBrInst &BI);
389   void visitSelectInst(SelectInst &SI);
390   void visitUserOp1(Instruction &I);
391   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
392   void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
393   template <class DbgIntrinsicTy>
394   void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
395   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
396   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
397   void visitFenceInst(FenceInst &FI);
398   void visitAllocaInst(AllocaInst &AI);
399   void visitExtractValueInst(ExtractValueInst &EVI);
400   void visitInsertValueInst(InsertValueInst &IVI);
401   void visitEHPadPredecessors(Instruction &I);
402   void visitLandingPadInst(LandingPadInst &LPI);
403   void visitCatchPadInst(CatchPadInst &CPI);
404   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
405   void visitCleanupPadInst(CleanupPadInst &CPI);
406   void visitFuncletPadInst(FuncletPadInst &FPI);
407   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
408   void visitCleanupReturnInst(CleanupReturnInst &CRI);
409
410   void VerifyCallSite(CallSite CS);
411   void verifyMustTailCall(CallInst &CI);
412   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
413                         unsigned ArgNo, std::string &Suffix);
414   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
415                            SmallVectorImpl<Type *> &ArgTys);
416   bool VerifyIntrinsicIsVarArg(bool isVarArg,
417                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
418   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
419   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
420                             const Value *V);
421   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
422                             bool isReturnValue, const Value *V);
423   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
424                            const Value *V);
425   void VerifyFunctionMetadata(
426       const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
427
428   void visitConstantExprsRecursively(const Constant *EntryC);
429   void visitConstantExpr(const ConstantExpr *CE);
430   void VerifyStatepoint(ImmutableCallSite CS);
431   void verifyFrameRecoverIndices();
432
433   // Module-level debug info verification...
434   void verifyTypeRefs();
435   template <class MapTy>
436   void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
437                                 const MapTy &TypeRefs);
438   void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
439 };
440 } // End anonymous namespace
441
442 // Assert - We know that cond should be true, if not print an error message.
443 #define Assert(C, ...) \
444   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
445
446 void Verifier::visit(Instruction &I) {
447   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
448     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
449   InstVisitor<Verifier>::visit(I);
450 }
451
452
453 void Verifier::visitGlobalValue(const GlobalValue &GV) {
454   Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
455              GV.hasExternalWeakLinkage(),
456          "Global is external, but doesn't have external or weak linkage!", &GV);
457
458   Assert(GV.getAlignment() <= Value::MaximumAlignment,
459          "huge alignment values are unsupported", &GV);
460   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
461          "Only global variables can have appending linkage!", &GV);
462
463   if (GV.hasAppendingLinkage()) {
464     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
465     Assert(GVar && GVar->getValueType()->isArrayTy(),
466            "Only global arrays can have appending linkage!", GVar);
467   }
468
469   if (GV.isDeclarationForLinker())
470     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
471 }
472
473 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
474   if (GV.hasInitializer()) {
475     Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
476            "Global variable initializer type does not match global "
477            "variable type!",
478            &GV);
479
480     // If the global has common linkage, it must have a zero initializer and
481     // cannot be constant.
482     if (GV.hasCommonLinkage()) {
483       Assert(GV.getInitializer()->isNullValue(),
484              "'common' global must have a zero initializer!", &GV);
485       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
486              &GV);
487       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
488     }
489   } else {
490     Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
491            "invalid linkage type for global declaration", &GV);
492   }
493
494   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
495                        GV.getName() == "llvm.global_dtors")) {
496     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
497            "invalid linkage for intrinsic global variable", &GV);
498     // Don't worry about emitting an error for it not being an array,
499     // visitGlobalValue will complain on appending non-array.
500     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
501       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
502       PointerType *FuncPtrTy =
503           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
504       // FIXME: Reject the 2-field form in LLVM 4.0.
505       Assert(STy &&
506                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
507                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
508                  STy->getTypeAtIndex(1) == FuncPtrTy,
509              "wrong type for intrinsic global variable", &GV);
510       if (STy->getNumElements() == 3) {
511         Type *ETy = STy->getTypeAtIndex(2);
512         Assert(ETy->isPointerTy() &&
513                    cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
514                "wrong type for intrinsic global variable", &GV);
515       }
516     }
517   }
518
519   if (GV.hasName() && (GV.getName() == "llvm.used" ||
520                        GV.getName() == "llvm.compiler.used")) {
521     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
522            "invalid linkage for intrinsic global variable", &GV);
523     Type *GVType = GV.getValueType();
524     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
525       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
526       Assert(PTy, "wrong type for intrinsic global variable", &GV);
527       if (GV.hasInitializer()) {
528         const Constant *Init = GV.getInitializer();
529         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
530         Assert(InitArray, "wrong initalizer for intrinsic global variable",
531                Init);
532         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
533           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
534           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
535                      isa<GlobalAlias>(V),
536                  "invalid llvm.used member", V);
537           Assert(V->hasName(), "members of llvm.used must be named", V);
538         }
539       }
540     }
541   }
542
543   Assert(!GV.hasDLLImportStorageClass() ||
544              (GV.isDeclaration() && GV.hasExternalLinkage()) ||
545              GV.hasAvailableExternallyLinkage(),
546          "Global is marked as dllimport, but not external", &GV);
547
548   if (!GV.hasInitializer()) {
549     visitGlobalValue(GV);
550     return;
551   }
552
553   // Walk any aggregate initializers looking for bitcasts between address spaces
554   visitConstantExprsRecursively(GV.getInitializer());
555
556   visitGlobalValue(GV);
557 }
558
559 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
560   SmallPtrSet<const GlobalAlias*, 4> Visited;
561   Visited.insert(&GA);
562   visitAliaseeSubExpr(Visited, GA, C);
563 }
564
565 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
566                                    const GlobalAlias &GA, const Constant &C) {
567   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
568     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
569            &GA);
570
571     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
572       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
573
574       Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
575              &GA);
576     } else {
577       // Only continue verifying subexpressions of GlobalAliases.
578       // Do not recurse into global initializers.
579       return;
580     }
581   }
582
583   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
584     visitConstantExprsRecursively(CE);
585
586   for (const Use &U : C.operands()) {
587     Value *V = &*U;
588     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
589       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
590     else if (const auto *C2 = dyn_cast<Constant>(V))
591       visitAliaseeSubExpr(Visited, GA, *C2);
592   }
593 }
594
595 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
596   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
597          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
598          "weak_odr, or external linkage!",
599          &GA);
600   const Constant *Aliasee = GA.getAliasee();
601   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
602   Assert(GA.getType() == Aliasee->getType(),
603          "Alias and aliasee types should match!", &GA);
604
605   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
606          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
607
608   visitAliaseeSubExpr(GA, *Aliasee);
609
610   visitGlobalValue(GA);
611 }
612
613 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
614   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
615     MDNode *MD = NMD.getOperand(i);
616
617     if (NMD.getName() == "llvm.dbg.cu") {
618       Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
619     }
620
621     if (!MD)
622       continue;
623
624     visitMDNode(*MD);
625   }
626 }
627
628 void Verifier::visitMDNode(const MDNode &MD) {
629   // Only visit each node once.  Metadata can be mutually recursive, so this
630   // avoids infinite recursion here, as well as being an optimization.
631   if (!MDNodes.insert(&MD).second)
632     return;
633
634   switch (MD.getMetadataID()) {
635   default:
636     llvm_unreachable("Invalid MDNode subclass");
637   case Metadata::MDTupleKind:
638     break;
639 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
640   case Metadata::CLASS##Kind:                                                  \
641     visit##CLASS(cast<CLASS>(MD));                                             \
642     break;
643 #include "llvm/IR/Metadata.def"
644   }
645
646   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
647     Metadata *Op = MD.getOperand(i);
648     if (!Op)
649       continue;
650     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
651            &MD, Op);
652     if (auto *N = dyn_cast<MDNode>(Op)) {
653       visitMDNode(*N);
654       continue;
655     }
656     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
657       visitValueAsMetadata(*V, nullptr);
658       continue;
659     }
660   }
661
662   // Check these last, so we diagnose problems in operands first.
663   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
664   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
665 }
666
667 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
668   Assert(MD.getValue(), "Expected valid value", &MD);
669   Assert(!MD.getValue()->getType()->isMetadataTy(),
670          "Unexpected metadata round-trip through values", &MD, MD.getValue());
671
672   auto *L = dyn_cast<LocalAsMetadata>(&MD);
673   if (!L)
674     return;
675
676   Assert(F, "function-local metadata used outside a function", L);
677
678   // If this was an instruction, bb, or argument, verify that it is in the
679   // function that we expect.
680   Function *ActualF = nullptr;
681   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
682     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
683     ActualF = I->getParent()->getParent();
684   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
685     ActualF = BB->getParent();
686   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
687     ActualF = A->getParent();
688   assert(ActualF && "Unimplemented function local metadata case!");
689
690   Assert(ActualF == F, "function-local metadata used in wrong function", L);
691 }
692
693 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
694   Metadata *MD = MDV.getMetadata();
695   if (auto *N = dyn_cast<MDNode>(MD)) {
696     visitMDNode(*N);
697     return;
698   }
699
700   // Only visit each node once.  Metadata can be mutually recursive, so this
701   // avoids infinite recursion here, as well as being an optimization.
702   if (!MDNodes.insert(MD).second)
703     return;
704
705   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
706     visitValueAsMetadata(*V, F);
707 }
708
709 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
710   auto *S = dyn_cast<MDString>(MD);
711   if (!S)
712     return false;
713   if (S->getString().empty())
714     return false;
715
716   // Keep track of names of types referenced via UUID so we can check that they
717   // actually exist.
718   UnresolvedTypeRefs.insert(std::make_pair(S, &N));
719   return true;
720 }
721
722 /// \brief Check if a value can be a reference to a type.
723 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
724   return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
725 }
726
727 /// \brief Check if a value can be a ScopeRef.
728 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
729   return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
730 }
731
732 /// \brief Check if a value can be a debug info ref.
733 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
734   return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
735 }
736
737 template <class Ty>
738 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
739   for (Metadata *MD : N.operands()) {
740     if (MD) {
741       if (!isa<Ty>(MD))
742         return false;
743     } else {
744       if (!AllowNull)
745         return false;
746     }
747   }
748   return true;
749 }
750
751 template <class Ty>
752 bool isValidMetadataArray(const MDTuple &N) {
753   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
754 }
755
756 template <class Ty>
757 bool isValidMetadataNullArray(const MDTuple &N) {
758   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
759 }
760
761 void Verifier::visitDILocation(const DILocation &N) {
762   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
763          "location requires a valid scope", &N, N.getRawScope());
764   if (auto *IA = N.getRawInlinedAt())
765     Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
766 }
767
768 void Verifier::visitGenericDINode(const GenericDINode &N) {
769   Assert(N.getTag(), "invalid tag", &N);
770 }
771
772 void Verifier::visitDIScope(const DIScope &N) {
773   if (auto *F = N.getRawFile())
774     Assert(isa<DIFile>(F), "invalid file", &N, F);
775 }
776
777 void Verifier::visitDISubrange(const DISubrange &N) {
778   Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
779   Assert(N.getCount() >= -1, "invalid subrange count", &N);
780 }
781
782 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
783   Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
784 }
785
786 void Verifier::visitDIBasicType(const DIBasicType &N) {
787   Assert(N.getTag() == dwarf::DW_TAG_base_type ||
788              N.getTag() == dwarf::DW_TAG_unspecified_type,
789          "invalid tag", &N);
790 }
791
792 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
793   // Common scope checks.
794   visitDIScope(N);
795
796   Assert(N.getTag() == dwarf::DW_TAG_typedef ||
797              N.getTag() == dwarf::DW_TAG_pointer_type ||
798              N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
799              N.getTag() == dwarf::DW_TAG_reference_type ||
800              N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
801              N.getTag() == dwarf::DW_TAG_const_type ||
802              N.getTag() == dwarf::DW_TAG_volatile_type ||
803              N.getTag() == dwarf::DW_TAG_restrict_type ||
804              N.getTag() == dwarf::DW_TAG_member ||
805              N.getTag() == dwarf::DW_TAG_inheritance ||
806              N.getTag() == dwarf::DW_TAG_friend,
807          "invalid tag", &N);
808   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
809     Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
810            N.getExtraData());
811   }
812
813   Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
814   Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
815          N.getBaseType());
816 }
817
818 static bool hasConflictingReferenceFlags(unsigned Flags) {
819   return (Flags & DINode::FlagLValueReference) &&
820          (Flags & DINode::FlagRValueReference);
821 }
822
823 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
824   auto *Params = dyn_cast<MDTuple>(&RawParams);
825   Assert(Params, "invalid template params", &N, &RawParams);
826   for (Metadata *Op : Params->operands()) {
827     Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
828            Params, Op);
829   }
830 }
831
832 void Verifier::visitDICompositeType(const DICompositeType &N) {
833   // Common scope checks.
834   visitDIScope(N);
835
836   Assert(N.getTag() == dwarf::DW_TAG_array_type ||
837              N.getTag() == dwarf::DW_TAG_structure_type ||
838              N.getTag() == dwarf::DW_TAG_union_type ||
839              N.getTag() == dwarf::DW_TAG_enumeration_type ||
840              N.getTag() == dwarf::DW_TAG_class_type,
841          "invalid tag", &N);
842
843   Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
844   Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
845          N.getBaseType());
846
847   Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
848          "invalid composite elements", &N, N.getRawElements());
849   Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
850          N.getRawVTableHolder());
851   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
852          &N);
853   if (auto *Params = N.getRawTemplateParams())
854     visitTemplateParams(N, *Params);
855
856   if (N.getTag() == dwarf::DW_TAG_class_type ||
857       N.getTag() == dwarf::DW_TAG_union_type) {
858     Assert(N.getFile() && !N.getFile()->getFilename().empty(),
859            "class/union requires a filename", &N, N.getFile());
860   }
861 }
862
863 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
864   Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
865   if (auto *Types = N.getRawTypeArray()) {
866     Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
867     for (Metadata *Ty : N.getTypeArray()->operands()) {
868       Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
869     }
870   }
871   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
872          &N);
873 }
874
875 void Verifier::visitDIFile(const DIFile &N) {
876   Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
877 }
878
879 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
880   Assert(N.isDistinct(), "compile units must be distinct", &N);
881   Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
882
883   // Don't bother verifying the compilation directory or producer string
884   // as those could be empty.
885   Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
886          N.getRawFile());
887   Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
888          N.getFile());
889
890   if (auto *Array = N.getRawEnumTypes()) {
891     Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
892     for (Metadata *Op : N.getEnumTypes()->operands()) {
893       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
894       Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
895              "invalid enum type", &N, N.getEnumTypes(), Op);
896     }
897   }
898   if (auto *Array = N.getRawRetainedTypes()) {
899     Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
900     for (Metadata *Op : N.getRetainedTypes()->operands()) {
901       Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
902     }
903   }
904   if (auto *Array = N.getRawSubprograms()) {
905     Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
906     for (Metadata *Op : N.getSubprograms()->operands()) {
907       Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
908     }
909   }
910   if (auto *Array = N.getRawGlobalVariables()) {
911     Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
912     for (Metadata *Op : N.getGlobalVariables()->operands()) {
913       Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
914              Op);
915     }
916   }
917   if (auto *Array = N.getRawImportedEntities()) {
918     Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
919     for (Metadata *Op : N.getImportedEntities()->operands()) {
920       Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
921              Op);
922     }
923   }
924   if (auto *Array = N.getRawMacros()) {
925     Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
926     for (Metadata *Op : N.getMacros()->operands()) {
927       Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
928     }
929   }
930 }
931
932 void Verifier::visitDISubprogram(const DISubprogram &N) {
933   Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
934   Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
935   if (auto *T = N.getRawType())
936     Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
937   Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
938          N.getRawContainingType());
939   if (auto *Params = N.getRawTemplateParams())
940     visitTemplateParams(N, *Params);
941   if (auto *S = N.getRawDeclaration()) {
942     Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
943            "invalid subprogram declaration", &N, S);
944   }
945   if (auto *RawVars = N.getRawVariables()) {
946     auto *Vars = dyn_cast<MDTuple>(RawVars);
947     Assert(Vars, "invalid variable list", &N, RawVars);
948     for (Metadata *Op : Vars->operands()) {
949       Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
950              Op);
951     }
952   }
953   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
954          &N);
955
956   if (N.isDefinition())
957     Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
958 }
959
960 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
961   Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
962   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
963          "invalid local scope", &N, N.getRawScope());
964 }
965
966 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
967   visitDILexicalBlockBase(N);
968
969   Assert(N.getLine() || !N.getColumn(),
970          "cannot have column info without line info", &N);
971 }
972
973 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
974   visitDILexicalBlockBase(N);
975 }
976
977 void Verifier::visitDINamespace(const DINamespace &N) {
978   Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
979   if (auto *S = N.getRawScope())
980     Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
981 }
982
983 void Verifier::visitDIMacro(const DIMacro &N) {
984   Assert(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
985          N.getMacinfoType() == dwarf::DW_MACINFO_undef,
986          "invalid macinfo type", &N);
987   Assert(!N.getName().empty(), "anonymous macro", &N);
988   if (!N.getValue().empty()) {
989     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
990   }
991 }
992
993 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
994   Assert(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
995          "invalid macinfo type", &N);
996   if (auto *F = N.getRawFile())
997     Assert(isa<DIFile>(F), "invalid file", &N, F);
998
999   if (auto *Array = N.getRawElements()) {
1000     Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1001     for (Metadata *Op : N.getElements()->operands()) {
1002       Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1003     }
1004   }
1005 }
1006
1007 void Verifier::visitDIModule(const DIModule &N) {
1008   Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1009   Assert(!N.getName().empty(), "anonymous module", &N);
1010 }
1011
1012 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1013   Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1014 }
1015
1016 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1017   visitDITemplateParameter(N);
1018
1019   Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1020          &N);
1021 }
1022
1023 void Verifier::visitDITemplateValueParameter(
1024     const DITemplateValueParameter &N) {
1025   visitDITemplateParameter(N);
1026
1027   Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1028              N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1029              N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1030          "invalid tag", &N);
1031 }
1032
1033 void Verifier::visitDIVariable(const DIVariable &N) {
1034   if (auto *S = N.getRawScope())
1035     Assert(isa<DIScope>(S), "invalid scope", &N, S);
1036   Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1037   if (auto *F = N.getRawFile())
1038     Assert(isa<DIFile>(F), "invalid file", &N, F);
1039 }
1040
1041 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1042   // Checks common to all variables.
1043   visitDIVariable(N);
1044
1045   Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1046   Assert(!N.getName().empty(), "missing global variable name", &N);
1047   if (auto *V = N.getRawVariable()) {
1048     Assert(isa<ConstantAsMetadata>(V) &&
1049                !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1050            "invalid global varaible ref", &N, V);
1051   }
1052   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1053     Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1054            &N, Member);
1055   }
1056 }
1057
1058 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1059   // Checks common to all variables.
1060   visitDIVariable(N);
1061
1062   Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1063   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1064          "local variable requires a valid scope", &N, N.getRawScope());
1065 }
1066
1067 void Verifier::visitDIExpression(const DIExpression &N) {
1068   Assert(N.isValid(), "invalid expression", &N);
1069 }
1070
1071 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1072   Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1073   if (auto *T = N.getRawType())
1074     Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1075   if (auto *F = N.getRawFile())
1076     Assert(isa<DIFile>(F), "invalid file", &N, F);
1077 }
1078
1079 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1080   Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1081              N.getTag() == dwarf::DW_TAG_imported_declaration,
1082          "invalid tag", &N);
1083   if (auto *S = N.getRawScope())
1084     Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1085   Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1086          N.getEntity());
1087 }
1088
1089 void Verifier::visitComdat(const Comdat &C) {
1090   // The Module is invalid if the GlobalValue has private linkage.  Entities
1091   // with private linkage don't have entries in the symbol table.
1092   if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1093     Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1094            GV);
1095 }
1096
1097 void Verifier::visitModuleIdents(const Module &M) {
1098   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1099   if (!Idents) 
1100     return;
1101   
1102   // llvm.ident takes a list of metadata entry. Each entry has only one string.
1103   // Scan each llvm.ident entry and make sure that this requirement is met.
1104   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1105     const MDNode *N = Idents->getOperand(i);
1106     Assert(N->getNumOperands() == 1,
1107            "incorrect number of operands in llvm.ident metadata", N);
1108     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1109            ("invalid value for llvm.ident metadata entry operand"
1110             "(the operand should be a string)"),
1111            N->getOperand(0));
1112   } 
1113 }
1114
1115 void Verifier::visitModuleFlags(const Module &M) {
1116   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1117   if (!Flags) return;
1118
1119   // Scan each flag, and track the flags and requirements.
1120   DenseMap<const MDString*, const MDNode*> SeenIDs;
1121   SmallVector<const MDNode*, 16> Requirements;
1122   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1123     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1124   }
1125
1126   // Validate that the requirements in the module are valid.
1127   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1128     const MDNode *Requirement = Requirements[I];
1129     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1130     const Metadata *ReqValue = Requirement->getOperand(1);
1131
1132     const MDNode *Op = SeenIDs.lookup(Flag);
1133     if (!Op) {
1134       CheckFailed("invalid requirement on flag, flag is not present in module",
1135                   Flag);
1136       continue;
1137     }
1138
1139     if (Op->getOperand(2) != ReqValue) {
1140       CheckFailed(("invalid requirement on flag, "
1141                    "flag does not have the required value"),
1142                   Flag);
1143       continue;
1144     }
1145   }
1146 }
1147
1148 void
1149 Verifier::visitModuleFlag(const MDNode *Op,
1150                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
1151                           SmallVectorImpl<const MDNode *> &Requirements) {
1152   // Each module flag should have three arguments, the merge behavior (a
1153   // constant int), the flag ID (an MDString), and the value.
1154   Assert(Op->getNumOperands() == 3,
1155          "incorrect number of operands in module flag", Op);
1156   Module::ModFlagBehavior MFB;
1157   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1158     Assert(
1159         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1160         "invalid behavior operand in module flag (expected constant integer)",
1161         Op->getOperand(0));
1162     Assert(false,
1163            "invalid behavior operand in module flag (unexpected constant)",
1164            Op->getOperand(0));
1165   }
1166   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1167   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1168          Op->getOperand(1));
1169
1170   // Sanity check the values for behaviors with additional requirements.
1171   switch (MFB) {
1172   case Module::Error:
1173   case Module::Warning:
1174   case Module::Override:
1175     // These behavior types accept any value.
1176     break;
1177
1178   case Module::Require: {
1179     // The value should itself be an MDNode with two operands, a flag ID (an
1180     // MDString), and a value.
1181     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1182     Assert(Value && Value->getNumOperands() == 2,
1183            "invalid value for 'require' module flag (expected metadata pair)",
1184            Op->getOperand(2));
1185     Assert(isa<MDString>(Value->getOperand(0)),
1186            ("invalid value for 'require' module flag "
1187             "(first value operand should be a string)"),
1188            Value->getOperand(0));
1189
1190     // Append it to the list of requirements, to check once all module flags are
1191     // scanned.
1192     Requirements.push_back(Value);
1193     break;
1194   }
1195
1196   case Module::Append:
1197   case Module::AppendUnique: {
1198     // These behavior types require the operand be an MDNode.
1199     Assert(isa<MDNode>(Op->getOperand(2)),
1200            "invalid value for 'append'-type module flag "
1201            "(expected a metadata node)",
1202            Op->getOperand(2));
1203     break;
1204   }
1205   }
1206
1207   // Unless this is a "requires" flag, check the ID is unique.
1208   if (MFB != Module::Require) {
1209     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1210     Assert(Inserted,
1211            "module flag identifiers must be unique (or of 'require' type)", ID);
1212   }
1213 }
1214
1215 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1216                                     bool isFunction, const Value *V) {
1217   unsigned Slot = ~0U;
1218   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1219     if (Attrs.getSlotIndex(I) == Idx) {
1220       Slot = I;
1221       break;
1222     }
1223
1224   assert(Slot != ~0U && "Attribute set inconsistency!");
1225
1226   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1227          I != E; ++I) {
1228     if (I->isStringAttribute())
1229       continue;
1230
1231     if (I->getKindAsEnum() == Attribute::NoReturn ||
1232         I->getKindAsEnum() == Attribute::NoUnwind ||
1233         I->getKindAsEnum() == Attribute::NoInline ||
1234         I->getKindAsEnum() == Attribute::AlwaysInline ||
1235         I->getKindAsEnum() == Attribute::OptimizeForSize ||
1236         I->getKindAsEnum() == Attribute::StackProtect ||
1237         I->getKindAsEnum() == Attribute::StackProtectReq ||
1238         I->getKindAsEnum() == Attribute::StackProtectStrong ||
1239         I->getKindAsEnum() == Attribute::SafeStack ||
1240         I->getKindAsEnum() == Attribute::NoRedZone ||
1241         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1242         I->getKindAsEnum() == Attribute::Naked ||
1243         I->getKindAsEnum() == Attribute::InlineHint ||
1244         I->getKindAsEnum() == Attribute::StackAlignment ||
1245         I->getKindAsEnum() == Attribute::UWTable ||
1246         I->getKindAsEnum() == Attribute::NonLazyBind ||
1247         I->getKindAsEnum() == Attribute::ReturnsTwice ||
1248         I->getKindAsEnum() == Attribute::SanitizeAddress ||
1249         I->getKindAsEnum() == Attribute::SanitizeThread ||
1250         I->getKindAsEnum() == Attribute::SanitizeMemory ||
1251         I->getKindAsEnum() == Attribute::MinSize ||
1252         I->getKindAsEnum() == Attribute::NoDuplicate ||
1253         I->getKindAsEnum() == Attribute::Builtin ||
1254         I->getKindAsEnum() == Attribute::NoBuiltin ||
1255         I->getKindAsEnum() == Attribute::Cold ||
1256         I->getKindAsEnum() == Attribute::OptimizeNone ||
1257         I->getKindAsEnum() == Attribute::JumpTable ||
1258         I->getKindAsEnum() == Attribute::Convergent ||
1259         I->getKindAsEnum() == Attribute::ArgMemOnly ||
1260         I->getKindAsEnum() == Attribute::NoRecurse ||
1261         I->getKindAsEnum() == Attribute::InaccessibleMemOnly ||
1262         I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly) {
1263       if (!isFunction) {
1264         CheckFailed("Attribute '" + I->getAsString() +
1265                     "' only applies to functions!", V);
1266         return;
1267       }
1268     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1269                I->getKindAsEnum() == Attribute::ReadNone) {
1270       if (Idx == 0) {
1271         CheckFailed("Attribute '" + I->getAsString() +
1272                     "' does not apply to function returns");
1273         return;
1274       }
1275     } else if (isFunction) {
1276       CheckFailed("Attribute '" + I->getAsString() +
1277                   "' does not apply to functions!", V);
1278       return;
1279     }
1280   }
1281 }
1282
1283 // VerifyParameterAttrs - Check the given attributes for an argument or return
1284 // value of the specified type.  The value V is printed in error messages.
1285 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1286                                     bool isReturnValue, const Value *V) {
1287   if (!Attrs.hasAttributes(Idx))
1288     return;
1289
1290   VerifyAttributeTypes(Attrs, Idx, false, V);
1291
1292   if (isReturnValue)
1293     Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1294                !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1295                !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1296                !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1297                !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1298                !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1299            "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1300            "'returned' do not apply to return values!",
1301            V);
1302
1303   // Check for mutually incompatible attributes.  Only inreg is compatible with
1304   // sret.
1305   unsigned AttrCount = 0;
1306   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1307   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1308   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1309                Attrs.hasAttribute(Idx, Attribute::InReg);
1310   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1311   Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1312                          "and 'sret' are incompatible!",
1313          V);
1314
1315   Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1316            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1317          "Attributes "
1318          "'inalloca and readonly' are incompatible!",
1319          V);
1320
1321   Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1322            Attrs.hasAttribute(Idx, Attribute::Returned)),
1323          "Attributes "
1324          "'sret and returned' are incompatible!",
1325          V);
1326
1327   Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1328            Attrs.hasAttribute(Idx, Attribute::SExt)),
1329          "Attributes "
1330          "'zeroext and signext' are incompatible!",
1331          V);
1332
1333   Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1334            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1335          "Attributes "
1336          "'readnone and readonly' are incompatible!",
1337          V);
1338
1339   Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1340            Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1341          "Attributes "
1342          "'noinline and alwaysinline' are incompatible!",
1343          V);
1344
1345   Assert(!AttrBuilder(Attrs, Idx)
1346               .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1347          "Wrong types for attribute: " +
1348          AttributeSet::get(*Context, Idx,
1349                         AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1350          V);
1351
1352   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1353     SmallPtrSet<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::ReadNone) &&
1434         Attrs.hasAttribute(AttributeSet::FunctionIndex, 
1435                            Attribute::InaccessibleMemOrArgMemOnly)),
1436       "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V);
1437
1438   Assert(
1439       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1440         Attrs.hasAttribute(AttributeSet::FunctionIndex, 
1441                            Attribute::InaccessibleMemOnly)),
1442       "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1443
1444   Assert(
1445       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1446         Attrs.hasAttribute(AttributeSet::FunctionIndex,
1447                            Attribute::AlwaysInline)),
1448       "Attributes 'noinline and alwaysinline' are incompatible!", V);
1449
1450   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
1451                          Attribute::OptimizeNone)) {
1452     Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1453            "Attribute 'optnone' requires 'noinline'!", V);
1454
1455     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1456                                Attribute::OptimizeForSize),
1457            "Attributes 'optsize and optnone' are incompatible!", V);
1458
1459     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1460            "Attributes 'minsize and optnone' are incompatible!", V);
1461   }
1462
1463   if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1464                          Attribute::JumpTable)) {
1465     const GlobalValue *GV = cast<GlobalValue>(V);
1466     Assert(GV->hasUnnamedAddr(),
1467            "Attribute 'jumptable' requires 'unnamed_addr'", V);
1468   }
1469 }
1470
1471 void Verifier::VerifyFunctionMetadata(
1472     const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1473   if (MDs.empty())
1474     return;
1475
1476   for (unsigned i = 0; i < MDs.size(); i++) {
1477     if (MDs[i].first == LLVMContext::MD_prof) {
1478       MDNode *MD = MDs[i].second;
1479       Assert(MD->getNumOperands() == 2,
1480              "!prof annotations should have exactly 2 operands", MD);
1481
1482       // Check first operand.
1483       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1484              MD);
1485       Assert(isa<MDString>(MD->getOperand(0)),
1486              "expected string with name of the !prof annotation", MD);
1487       MDString *MDS = cast<MDString>(MD->getOperand(0));
1488       StringRef ProfName = MDS->getString();
1489       Assert(ProfName.equals("function_entry_count"),
1490              "first operand should be 'function_entry_count'", MD);
1491
1492       // Check second operand.
1493       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1494              MD);
1495       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1496              "expected integer argument to function_entry_count", MD);
1497     }
1498   }
1499 }
1500
1501 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1502   if (!ConstantExprVisited.insert(EntryC).second)
1503     return;
1504
1505   SmallVector<const Constant *, 16> Stack;
1506   Stack.push_back(EntryC);
1507
1508   while (!Stack.empty()) {
1509     const Constant *C = Stack.pop_back_val();
1510
1511     // Check this constant expression.
1512     if (const auto *CE = dyn_cast<ConstantExpr>(C))
1513       visitConstantExpr(CE);
1514
1515     // Visit all sub-expressions.
1516     for (const Use &U : C->operands()) {
1517       const auto *OpC = dyn_cast<Constant>(U);
1518       if (!OpC)
1519         continue;
1520       if (isa<GlobalValue>(OpC))
1521         continue; // Global values get visited separately.
1522       if (!ConstantExprVisited.insert(OpC).second)
1523         continue;
1524       Stack.push_back(OpC);
1525     }
1526   }
1527 }
1528
1529 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
1530   if (CE->getOpcode() != Instruction::BitCast)
1531     return;
1532
1533   Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1534                                CE->getType()),
1535          "Invalid bitcast", CE);
1536 }
1537
1538 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1539   if (Attrs.getNumSlots() == 0)
1540     return true;
1541
1542   unsigned LastSlot = Attrs.getNumSlots() - 1;
1543   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1544   if (LastIndex <= Params
1545       || (LastIndex == AttributeSet::FunctionIndex
1546           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1547     return true;
1548
1549   return false;
1550 }
1551
1552 /// \brief Verify that statepoint intrinsic is well formed.
1553 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1554   assert(CS.getCalledFunction() &&
1555          CS.getCalledFunction()->getIntrinsicID() ==
1556            Intrinsic::experimental_gc_statepoint);
1557
1558   const Instruction &CI = *CS.getInstruction();
1559
1560   Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1561          !CS.onlyAccessesArgMemory(),
1562          "gc.statepoint must read and write all memory to preserve "
1563          "reordering restrictions required by safepoint semantics",
1564          &CI);
1565
1566   const Value *IDV = CS.getArgument(0);
1567   Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1568          &CI);
1569
1570   const Value *NumPatchBytesV = CS.getArgument(1);
1571   Assert(isa<ConstantInt>(NumPatchBytesV),
1572          "gc.statepoint number of patchable bytes must be a constant integer",
1573          &CI);
1574   const int64_t NumPatchBytes =
1575       cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1576   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1577   Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1578                              "positive",
1579          &CI);
1580
1581   const Value *Target = CS.getArgument(2);
1582   auto *PT = dyn_cast<PointerType>(Target->getType());
1583   Assert(PT && PT->getElementType()->isFunctionTy(),
1584          "gc.statepoint callee must be of function pointer type", &CI, Target);
1585   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1586
1587   const Value *NumCallArgsV = CS.getArgument(3);
1588   Assert(isa<ConstantInt>(NumCallArgsV),
1589          "gc.statepoint number of arguments to underlying call "
1590          "must be constant integer",
1591          &CI);
1592   const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1593   Assert(NumCallArgs >= 0,
1594          "gc.statepoint number of arguments to underlying call "
1595          "must be positive",
1596          &CI);
1597   const int NumParams = (int)TargetFuncType->getNumParams();
1598   if (TargetFuncType->isVarArg()) {
1599     Assert(NumCallArgs >= NumParams,
1600            "gc.statepoint mismatch in number of vararg call args", &CI);
1601
1602     // TODO: Remove this limitation
1603     Assert(TargetFuncType->getReturnType()->isVoidTy(),
1604            "gc.statepoint doesn't support wrapping non-void "
1605            "vararg functions yet",
1606            &CI);
1607   } else
1608     Assert(NumCallArgs == NumParams,
1609            "gc.statepoint mismatch in number of call args", &CI);
1610
1611   const Value *FlagsV = CS.getArgument(4);
1612   Assert(isa<ConstantInt>(FlagsV),
1613          "gc.statepoint flags must be constant integer", &CI);
1614   const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1615   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1616          "unknown flag used in gc.statepoint flags argument", &CI);
1617
1618   // Verify that the types of the call parameter arguments match
1619   // the type of the wrapped callee.
1620   for (int i = 0; i < NumParams; i++) {
1621     Type *ParamType = TargetFuncType->getParamType(i);
1622     Type *ArgType = CS.getArgument(5 + i)->getType();
1623     Assert(ArgType == ParamType,
1624            "gc.statepoint call argument does not match wrapped "
1625            "function type",
1626            &CI);
1627   }
1628
1629   const int EndCallArgsInx = 4 + NumCallArgs;
1630
1631   const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1632   Assert(isa<ConstantInt>(NumTransitionArgsV),
1633          "gc.statepoint number of transition arguments "
1634          "must be constant integer",
1635          &CI);
1636   const int NumTransitionArgs =
1637       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1638   Assert(NumTransitionArgs >= 0,
1639          "gc.statepoint number of transition arguments must be positive", &CI);
1640   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1641
1642   const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1643   Assert(isa<ConstantInt>(NumDeoptArgsV),
1644          "gc.statepoint number of deoptimization arguments "
1645          "must be constant integer",
1646          &CI);
1647   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1648   Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1649                             "must be positive",
1650          &CI);
1651
1652   const int ExpectedNumArgs =
1653       7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1654   Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1655          "gc.statepoint too few arguments according to length fields", &CI);
1656
1657   // Check that the only uses of this gc.statepoint are gc.result or 
1658   // gc.relocate calls which are tied to this statepoint and thus part
1659   // of the same statepoint sequence
1660   for (const User *U : CI.users()) {
1661     const CallInst *Call = dyn_cast<const CallInst>(U);
1662     Assert(Call, "illegal use of statepoint token", &CI, U);
1663     if (!Call) continue;
1664     Assert(isa<GCRelocateInst>(Call) || isGCResult(Call),
1665            "gc.result or gc.relocate are the only value uses"
1666            "of a gc.statepoint",
1667            &CI, U);
1668     if (isGCResult(Call)) {
1669       Assert(Call->getArgOperand(0) == &CI,
1670              "gc.result connected to wrong gc.statepoint", &CI, Call);
1671     } else if (isa<GCRelocateInst>(Call)) {
1672       Assert(Call->getArgOperand(0) == &CI,
1673              "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1674     }
1675   }
1676
1677   // Note: It is legal for a single derived pointer to be listed multiple
1678   // times.  It's non-optimal, but it is legal.  It can also happen after
1679   // insertion if we strip a bitcast away.
1680   // Note: It is really tempting to check that each base is relocated and
1681   // that a derived pointer is never reused as a base pointer.  This turns
1682   // out to be problematic since optimizations run after safepoint insertion
1683   // can recognize equality properties that the insertion logic doesn't know
1684   // about.  See example statepoint.ll in the verifier subdirectory
1685 }
1686
1687 void Verifier::verifyFrameRecoverIndices() {
1688   for (auto &Counts : FrameEscapeInfo) {
1689     Function *F = Counts.first;
1690     unsigned EscapedObjectCount = Counts.second.first;
1691     unsigned MaxRecoveredIndex = Counts.second.second;
1692     Assert(MaxRecoveredIndex <= EscapedObjectCount,
1693            "all indices passed to llvm.localrecover must be less than the "
1694            "number of arguments passed ot llvm.localescape in the parent "
1695            "function",
1696            F);
1697   }
1698 }
1699
1700 // visitFunction - Verify that a function is ok.
1701 //
1702 void Verifier::visitFunction(const Function &F) {
1703   // Check function arguments.
1704   FunctionType *FT = F.getFunctionType();
1705   unsigned NumArgs = F.arg_size();
1706
1707   Assert(Context == &F.getContext(),
1708          "Function context does not match Module context!", &F);
1709
1710   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1711   Assert(FT->getNumParams() == NumArgs,
1712          "# formal arguments must match # of arguments for function type!", &F,
1713          FT);
1714   Assert(F.getReturnType()->isFirstClassType() ||
1715              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1716          "Functions cannot return aggregate values!", &F);
1717
1718   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1719          "Invalid struct return type!", &F);
1720
1721   AttributeSet Attrs = F.getAttributes();
1722
1723   Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1724          "Attribute after last parameter!", &F);
1725
1726   // Check function attributes.
1727   VerifyFunctionAttrs(FT, Attrs, &F);
1728
1729   // On function declarations/definitions, we do not support the builtin
1730   // attribute. We do not check this in VerifyFunctionAttrs since that is
1731   // checking for Attributes that can/can not ever be on functions.
1732   Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1733          "Attribute 'builtin' can only be applied to a callsite.", &F);
1734
1735   // Check that this function meets the restrictions on this calling convention.
1736   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1737   // restrictions can be lifted.
1738   switch (F.getCallingConv()) {
1739   default:
1740   case CallingConv::C:
1741     break;
1742   case CallingConv::Fast:
1743   case CallingConv::Cold:
1744   case CallingConv::Intel_OCL_BI:
1745   case CallingConv::PTX_Kernel:
1746   case CallingConv::PTX_Device:
1747     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1748                           "perfect forwarding!",
1749            &F);
1750     break;
1751   }
1752
1753   bool isLLVMdotName = F.getName().size() >= 5 &&
1754                        F.getName().substr(0, 5) == "llvm.";
1755
1756   // Check that the argument values match the function type for this function...
1757   unsigned i = 0;
1758   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1759        ++I, ++i) {
1760     Assert(I->getType() == FT->getParamType(i),
1761            "Argument value does not match function argument type!", I,
1762            FT->getParamType(i));
1763     Assert(I->getType()->isFirstClassType(),
1764            "Function arguments must have first-class types!", I);
1765     if (!isLLVMdotName) {
1766       Assert(!I->getType()->isMetadataTy(),
1767              "Function takes metadata but isn't an intrinsic", I, &F);
1768       Assert(!I->getType()->isTokenTy(),
1769              "Function takes token but isn't an intrinsic", I, &F);
1770     }
1771   }
1772
1773   if (!isLLVMdotName)
1774     Assert(!F.getReturnType()->isTokenTy(),
1775            "Functions returns a token but isn't an intrinsic", &F);
1776
1777   // Get the function metadata attachments.
1778   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1779   F.getAllMetadata(MDs);
1780   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1781   VerifyFunctionMetadata(MDs);
1782
1783   // Check validity of the personality function
1784   if (F.hasPersonalityFn()) {
1785     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1786     if (Per)
1787       Assert(Per->getParent() == F.getParent(),
1788              "Referencing personality function in another module!",
1789              &F, F.getParent(), Per, Per->getParent());
1790   }
1791
1792   if (F.isMaterializable()) {
1793     // Function has a body somewhere we can't see.
1794     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1795            MDs.empty() ? nullptr : MDs.front().second);
1796   } else if (F.isDeclaration()) {
1797     Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1798            "invalid linkage type for function declaration", &F);
1799     Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1800            MDs.empty() ? nullptr : MDs.front().second);
1801     Assert(!F.hasPersonalityFn(),
1802            "Function declaration shouldn't have a personality routine", &F);
1803   } else {
1804     // Verify that this function (which has a body) is not named "llvm.*".  It
1805     // is not legal to define intrinsics.
1806     Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1807
1808     // Check the entry node
1809     const BasicBlock *Entry = &F.getEntryBlock();
1810     Assert(pred_empty(Entry),
1811            "Entry block to function must not have predecessors!", Entry);
1812
1813     // The address of the entry block cannot be taken, unless it is dead.
1814     if (Entry->hasAddressTaken()) {
1815       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1816              "blockaddress may not be used with the entry block!", Entry);
1817     }
1818
1819     // Visit metadata attachments.
1820     for (const auto &I : MDs) {
1821       // Verify that the attachment is legal.
1822       switch (I.first) {
1823       default:
1824         break;
1825       case LLVMContext::MD_dbg:
1826         Assert(isa<DISubprogram>(I.second),
1827                "function !dbg attachment must be a subprogram", &F, I.second);
1828         break;
1829       }
1830
1831       // Verify the metadata itself.
1832       visitMDNode(*I.second);
1833     }
1834   }
1835
1836   // If this function is actually an intrinsic, verify that it is only used in
1837   // direct call/invokes, never having its "address taken".
1838   // Only do this if the module is materialized, otherwise we don't have all the
1839   // uses.
1840   if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
1841     const User *U;
1842     if (F.hasAddressTaken(&U))
1843       Assert(0, "Invalid user of intrinsic instruction!", U);
1844   }
1845
1846   Assert(!F.hasDLLImportStorageClass() ||
1847              (F.isDeclaration() && F.hasExternalLinkage()) ||
1848              F.hasAvailableExternallyLinkage(),
1849          "Function is marked as dllimport, but not external.", &F);
1850
1851   auto *N = F.getSubprogram();
1852   if (!N)
1853     return;
1854
1855   // Check that all !dbg attachments lead to back to N (or, at least, another
1856   // subprogram that describes the same function).
1857   //
1858   // FIXME: Check this incrementally while visiting !dbg attachments.
1859   // FIXME: Only check when N is the canonical subprogram for F.
1860   SmallPtrSet<const MDNode *, 32> Seen;
1861   for (auto &BB : F)
1862     for (auto &I : BB) {
1863       // Be careful about using DILocation here since we might be dealing with
1864       // broken code (this is the Verifier after all).
1865       DILocation *DL =
1866           dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1867       if (!DL)
1868         continue;
1869       if (!Seen.insert(DL).second)
1870         continue;
1871
1872       DILocalScope *Scope = DL->getInlinedAtScope();
1873       if (Scope && !Seen.insert(Scope).second)
1874         continue;
1875
1876       DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1877
1878       // Scope and SP could be the same MDNode and we don't want to skip
1879       // validation in that case
1880       if (SP && ((Scope != SP) && !Seen.insert(SP).second))
1881         continue;
1882
1883       // FIXME: Once N is canonical, check "SP == &N".
1884       Assert(SP->describes(&F),
1885              "!dbg attachment points at wrong subprogram for function", N, &F,
1886              &I, DL, Scope, SP);
1887     }
1888 }
1889
1890 // verifyBasicBlock - Verify that a basic block is well formed...
1891 //
1892 void Verifier::visitBasicBlock(BasicBlock &BB) {
1893   InstsInThisBlock.clear();
1894
1895   // Ensure that basic blocks have terminators!
1896   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1897
1898   // Check constraints that this basic block imposes on all of the PHI nodes in
1899   // it.
1900   if (isa<PHINode>(BB.front())) {
1901     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1902     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1903     std::sort(Preds.begin(), Preds.end());
1904     PHINode *PN;
1905     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1906       // Ensure that PHI nodes have at least one entry!
1907       Assert(PN->getNumIncomingValues() != 0,
1908              "PHI nodes must have at least one entry.  If the block is dead, "
1909              "the PHI should be removed!",
1910              PN);
1911       Assert(PN->getNumIncomingValues() == Preds.size(),
1912              "PHINode should have one entry for each predecessor of its "
1913              "parent basic block!",
1914              PN);
1915
1916       // Get and sort all incoming values in the PHI node...
1917       Values.clear();
1918       Values.reserve(PN->getNumIncomingValues());
1919       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1920         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1921                                         PN->getIncomingValue(i)));
1922       std::sort(Values.begin(), Values.end());
1923
1924       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1925         // Check to make sure that if there is more than one entry for a
1926         // particular basic block in this PHI node, that the incoming values are
1927         // all identical.
1928         //
1929         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1930                    Values[i].second == Values[i - 1].second,
1931                "PHI node has multiple entries for the same basic block with "
1932                "different incoming values!",
1933                PN, Values[i].first, Values[i].second, Values[i - 1].second);
1934
1935         // Check to make sure that the predecessors and PHI node entries are
1936         // matched up.
1937         Assert(Values[i].first == Preds[i],
1938                "PHI node entries do not match predecessors!", PN,
1939                Values[i].first, Preds[i]);
1940       }
1941     }
1942   }
1943
1944   // Check that all instructions have their parent pointers set up correctly.
1945   for (auto &I : BB)
1946   {
1947     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1948   }
1949 }
1950
1951 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1952   // Ensure that terminators only exist at the end of the basic block.
1953   Assert(&I == I.getParent()->getTerminator(),
1954          "Terminator found in the middle of a basic block!", I.getParent());
1955   visitInstruction(I);
1956 }
1957
1958 void Verifier::visitBranchInst(BranchInst &BI) {
1959   if (BI.isConditional()) {
1960     Assert(BI.getCondition()->getType()->isIntegerTy(1),
1961            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1962   }
1963   visitTerminatorInst(BI);
1964 }
1965
1966 void Verifier::visitReturnInst(ReturnInst &RI) {
1967   Function *F = RI.getParent()->getParent();
1968   unsigned N = RI.getNumOperands();
1969   if (F->getReturnType()->isVoidTy())
1970     Assert(N == 0,
1971            "Found return instr that returns non-void in Function of void "
1972            "return type!",
1973            &RI, F->getReturnType());
1974   else
1975     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1976            "Function return type does not match operand "
1977            "type of return inst!",
1978            &RI, F->getReturnType());
1979
1980   // Check to make sure that the return value has necessary properties for
1981   // terminators...
1982   visitTerminatorInst(RI);
1983 }
1984
1985 void Verifier::visitSwitchInst(SwitchInst &SI) {
1986   // Check to make sure that all of the constants in the switch instruction
1987   // have the same type as the switched-on value.
1988   Type *SwitchTy = SI.getCondition()->getType();
1989   SmallPtrSet<ConstantInt*, 32> Constants;
1990   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1991     Assert(i.getCaseValue()->getType() == SwitchTy,
1992            "Switch constants must all be same type as switch value!", &SI);
1993     Assert(Constants.insert(i.getCaseValue()).second,
1994            "Duplicate integer as switch case", &SI, i.getCaseValue());
1995   }
1996
1997   visitTerminatorInst(SI);
1998 }
1999
2000 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2001   Assert(BI.getAddress()->getType()->isPointerTy(),
2002          "Indirectbr operand must have pointer type!", &BI);
2003   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2004     Assert(BI.getDestination(i)->getType()->isLabelTy(),
2005            "Indirectbr destinations must all have pointer type!", &BI);
2006
2007   visitTerminatorInst(BI);
2008 }
2009
2010 void Verifier::visitSelectInst(SelectInst &SI) {
2011   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2012                                          SI.getOperand(2)),
2013          "Invalid operands for select instruction!", &SI);
2014
2015   Assert(SI.getTrueValue()->getType() == SI.getType(),
2016          "Select values must have same type as select instruction!", &SI);
2017   visitInstruction(SI);
2018 }
2019
2020 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2021 /// a pass, if any exist, it's an error.
2022 ///
2023 void Verifier::visitUserOp1(Instruction &I) {
2024   Assert(0, "User-defined operators should not live outside of a pass!", &I);
2025 }
2026
2027 void Verifier::visitTruncInst(TruncInst &I) {
2028   // Get the source and destination types
2029   Type *SrcTy = I.getOperand(0)->getType();
2030   Type *DestTy = I.getType();
2031
2032   // Get the size of the types in bits, we'll need this later
2033   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2034   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2035
2036   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2037   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2038   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2039          "trunc source and destination must both be a vector or neither", &I);
2040   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2041
2042   visitInstruction(I);
2043 }
2044
2045 void Verifier::visitZExtInst(ZExtInst &I) {
2046   // Get the source and destination types
2047   Type *SrcTy = I.getOperand(0)->getType();
2048   Type *DestTy = I.getType();
2049
2050   // Get the size of the types in bits, we'll need this later
2051   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2052   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2053   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2054          "zext source and destination must both be a vector or neither", &I);
2055   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2056   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2057
2058   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2059
2060   visitInstruction(I);
2061 }
2062
2063 void Verifier::visitSExtInst(SExtInst &I) {
2064   // Get the source and destination types
2065   Type *SrcTy = I.getOperand(0)->getType();
2066   Type *DestTy = I.getType();
2067
2068   // Get the size of the types in bits, we'll need this later
2069   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2070   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2071
2072   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2073   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2074   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2075          "sext source and destination must both be a vector or neither", &I);
2076   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2077
2078   visitInstruction(I);
2079 }
2080
2081 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2082   // Get the source and destination types
2083   Type *SrcTy = I.getOperand(0)->getType();
2084   Type *DestTy = I.getType();
2085   // Get the size of the types in bits, we'll need this later
2086   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2087   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2088
2089   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2090   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2091   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2092          "fptrunc source and destination must both be a vector or neither", &I);
2093   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2094
2095   visitInstruction(I);
2096 }
2097
2098 void Verifier::visitFPExtInst(FPExtInst &I) {
2099   // Get the source and destination types
2100   Type *SrcTy = I.getOperand(0)->getType();
2101   Type *DestTy = I.getType();
2102
2103   // Get the size of the types in bits, we'll need this later
2104   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2105   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2106
2107   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2108   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2109   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2110          "fpext source and destination must both be a vector or neither", &I);
2111   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2112
2113   visitInstruction(I);
2114 }
2115
2116 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2117   // Get the source and destination types
2118   Type *SrcTy = I.getOperand(0)->getType();
2119   Type *DestTy = I.getType();
2120
2121   bool SrcVec = SrcTy->isVectorTy();
2122   bool DstVec = DestTy->isVectorTy();
2123
2124   Assert(SrcVec == DstVec,
2125          "UIToFP source and dest must both be vector or scalar", &I);
2126   Assert(SrcTy->isIntOrIntVectorTy(),
2127          "UIToFP source must be integer or integer vector", &I);
2128   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2129          &I);
2130
2131   if (SrcVec && DstVec)
2132     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2133                cast<VectorType>(DestTy)->getNumElements(),
2134            "UIToFP source and dest vector length mismatch", &I);
2135
2136   visitInstruction(I);
2137 }
2138
2139 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2140   // Get the source and destination types
2141   Type *SrcTy = I.getOperand(0)->getType();
2142   Type *DestTy = I.getType();
2143
2144   bool SrcVec = SrcTy->isVectorTy();
2145   bool DstVec = DestTy->isVectorTy();
2146
2147   Assert(SrcVec == DstVec,
2148          "SIToFP source and dest must both be vector or scalar", &I);
2149   Assert(SrcTy->isIntOrIntVectorTy(),
2150          "SIToFP source must be integer or integer vector", &I);
2151   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2152          &I);
2153
2154   if (SrcVec && DstVec)
2155     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2156                cast<VectorType>(DestTy)->getNumElements(),
2157            "SIToFP source and dest vector length mismatch", &I);
2158
2159   visitInstruction(I);
2160 }
2161
2162 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2163   // Get the source and destination types
2164   Type *SrcTy = I.getOperand(0)->getType();
2165   Type *DestTy = I.getType();
2166
2167   bool SrcVec = SrcTy->isVectorTy();
2168   bool DstVec = DestTy->isVectorTy();
2169
2170   Assert(SrcVec == DstVec,
2171          "FPToUI source and dest must both be vector or scalar", &I);
2172   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2173          &I);
2174   Assert(DestTy->isIntOrIntVectorTy(),
2175          "FPToUI result must be integer or integer vector", &I);
2176
2177   if (SrcVec && DstVec)
2178     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2179                cast<VectorType>(DestTy)->getNumElements(),
2180            "FPToUI source and dest vector length mismatch", &I);
2181
2182   visitInstruction(I);
2183 }
2184
2185 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2186   // Get the source and destination types
2187   Type *SrcTy = I.getOperand(0)->getType();
2188   Type *DestTy = I.getType();
2189
2190   bool SrcVec = SrcTy->isVectorTy();
2191   bool DstVec = DestTy->isVectorTy();
2192
2193   Assert(SrcVec == DstVec,
2194          "FPToSI source and dest must both be vector or scalar", &I);
2195   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2196          &I);
2197   Assert(DestTy->isIntOrIntVectorTy(),
2198          "FPToSI result must be integer or integer vector", &I);
2199
2200   if (SrcVec && DstVec)
2201     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2202                cast<VectorType>(DestTy)->getNumElements(),
2203            "FPToSI source and dest vector length mismatch", &I);
2204
2205   visitInstruction(I);
2206 }
2207
2208 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2209   // Get the source and destination types
2210   Type *SrcTy = I.getOperand(0)->getType();
2211   Type *DestTy = I.getType();
2212
2213   Assert(SrcTy->getScalarType()->isPointerTy(),
2214          "PtrToInt source must be pointer", &I);
2215   Assert(DestTy->getScalarType()->isIntegerTy(),
2216          "PtrToInt result must be integral", &I);
2217   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2218          &I);
2219
2220   if (SrcTy->isVectorTy()) {
2221     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2222     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2223     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2224            "PtrToInt Vector width mismatch", &I);
2225   }
2226
2227   visitInstruction(I);
2228 }
2229
2230 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2231   // Get the source and destination types
2232   Type *SrcTy = I.getOperand(0)->getType();
2233   Type *DestTy = I.getType();
2234
2235   Assert(SrcTy->getScalarType()->isIntegerTy(),
2236          "IntToPtr source must be an integral", &I);
2237   Assert(DestTy->getScalarType()->isPointerTy(),
2238          "IntToPtr result must be a pointer", &I);
2239   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2240          &I);
2241   if (SrcTy->isVectorTy()) {
2242     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2243     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2244     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2245            "IntToPtr Vector width mismatch", &I);
2246   }
2247   visitInstruction(I);
2248 }
2249
2250 void Verifier::visitBitCastInst(BitCastInst &I) {
2251   Assert(
2252       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2253       "Invalid bitcast", &I);
2254   visitInstruction(I);
2255 }
2256
2257 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2258   Type *SrcTy = I.getOperand(0)->getType();
2259   Type *DestTy = I.getType();
2260
2261   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2262          &I);
2263   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2264          &I);
2265   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2266          "AddrSpaceCast must be between different address spaces", &I);
2267   if (SrcTy->isVectorTy())
2268     Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2269            "AddrSpaceCast vector pointer number of elements mismatch", &I);
2270   visitInstruction(I);
2271 }
2272
2273 /// visitPHINode - Ensure that a PHI node is well formed.
2274 ///
2275 void Verifier::visitPHINode(PHINode &PN) {
2276   // Ensure that the PHI nodes are all grouped together at the top of the block.
2277   // This can be tested by checking whether the instruction before this is
2278   // either nonexistent (because this is begin()) or is a PHI node.  If not,
2279   // then there is some other instruction before a PHI.
2280   Assert(&PN == &PN.getParent()->front() ||
2281              isa<PHINode>(--BasicBlock::iterator(&PN)),
2282          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2283
2284   // Check that a PHI doesn't yield a Token.
2285   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2286
2287   // Check that all of the values of the PHI node have the same type as the
2288   // result, and that the incoming blocks are really basic blocks.
2289   for (Value *IncValue : PN.incoming_values()) {
2290     Assert(PN.getType() == IncValue->getType(),
2291            "PHI node operands are not the same type as the result!", &PN);
2292   }
2293
2294   // All other PHI node constraints are checked in the visitBasicBlock method.
2295
2296   visitInstruction(PN);
2297 }
2298
2299 void Verifier::VerifyCallSite(CallSite CS) {
2300   Instruction *I = CS.getInstruction();
2301
2302   Assert(CS.getCalledValue()->getType()->isPointerTy(),
2303          "Called function must be a pointer!", I);
2304   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2305
2306   Assert(FPTy->getElementType()->isFunctionTy(),
2307          "Called function is not pointer to function type!", I);
2308
2309   Assert(FPTy->getElementType() == CS.getFunctionType(),
2310          "Called function is not the same type as the call!", I);
2311
2312   FunctionType *FTy = CS.getFunctionType();
2313
2314   // Verify that the correct number of arguments are being passed
2315   if (FTy->isVarArg())
2316     Assert(CS.arg_size() >= FTy->getNumParams(),
2317            "Called function requires more parameters than were provided!", I);
2318   else
2319     Assert(CS.arg_size() == FTy->getNumParams(),
2320            "Incorrect number of arguments passed to called function!", I);
2321
2322   // Verify that all arguments to the call match the function type.
2323   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2324     Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2325            "Call parameter type does not match function signature!",
2326            CS.getArgument(i), FTy->getParamType(i), I);
2327
2328   AttributeSet Attrs = CS.getAttributes();
2329
2330   Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2331          "Attribute after last parameter!", I);
2332
2333   // Verify call attributes.
2334   VerifyFunctionAttrs(FTy, Attrs, I);
2335
2336   // Conservatively check the inalloca argument.
2337   // We have a bug if we can find that there is an underlying alloca without
2338   // inalloca.
2339   if (CS.hasInAllocaArgument()) {
2340     Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2341     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2342       Assert(AI->isUsedWithInAlloca(),
2343              "inalloca argument for call has mismatched alloca", AI, I);
2344   }
2345
2346   if (FTy->isVarArg()) {
2347     // FIXME? is 'nest' even legal here?
2348     bool SawNest = false;
2349     bool SawReturned = false;
2350
2351     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2352       if (Attrs.hasAttribute(Idx, Attribute::Nest))
2353         SawNest = true;
2354       if (Attrs.hasAttribute(Idx, Attribute::Returned))
2355         SawReturned = true;
2356     }
2357
2358     // Check attributes on the varargs part.
2359     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2360       Type *Ty = CS.getArgument(Idx-1)->getType();
2361       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2362
2363       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2364         Assert(!SawNest, "More than one parameter has attribute nest!", I);
2365         SawNest = true;
2366       }
2367
2368       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2369         Assert(!SawReturned, "More than one parameter has attribute returned!",
2370                I);
2371         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2372                "Incompatible argument and return types for 'returned' "
2373                "attribute",
2374                I);
2375         SawReturned = true;
2376       }
2377
2378       Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2379              "Attribute 'sret' cannot be used for vararg call arguments!", I);
2380
2381       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2382         Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2383     }
2384   }
2385
2386   // Verify that there's no metadata unless it's a direct call to an intrinsic.
2387   if (CS.getCalledFunction() == nullptr ||
2388       !CS.getCalledFunction()->getName().startswith("llvm.")) {
2389     for (Type *ParamTy : FTy->params()) {
2390       Assert(!ParamTy->isMetadataTy(),
2391              "Function has metadata parameter but isn't an intrinsic", I);
2392       Assert(!ParamTy->isTokenTy(),
2393              "Function has token parameter but isn't an intrinsic", I);
2394     }
2395   }
2396
2397   // Verify that indirect calls don't return tokens.
2398   if (CS.getCalledFunction() == nullptr)
2399     Assert(!FTy->getReturnType()->isTokenTy(),
2400            "Return type cannot be token for indirect call!");
2401
2402   if (Function *F = CS.getCalledFunction())
2403     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2404       visitIntrinsicCallSite(ID, CS);
2405
2406   // Verify that a callsite has at most one "deopt" and one "funclet" operand
2407   // bundle.
2408   bool FoundDeoptBundle = false, FoundFuncletBundle = false;
2409   for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2410     OperandBundleUse BU = CS.getOperandBundleAt(i);
2411     uint32_t Tag = BU.getTagID();
2412     if (Tag == LLVMContext::OB_deopt) {
2413       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2414       FoundDeoptBundle = true;
2415     }
2416     if (Tag == LLVMContext::OB_funclet) {
2417       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2418       FoundFuncletBundle = true;
2419       Assert(BU.Inputs.size() == 1,
2420              "Expected exactly one funclet bundle operand", I);
2421       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2422              "Funclet bundle operands should correspond to a FuncletPadInst",
2423              I);
2424     }
2425   }
2426
2427   visitInstruction(*I);
2428 }
2429
2430 /// Two types are "congruent" if they are identical, or if they are both pointer
2431 /// types with different pointee types and the same address space.
2432 static bool isTypeCongruent(Type *L, Type *R) {
2433   if (L == R)
2434     return true;
2435   PointerType *PL = dyn_cast<PointerType>(L);
2436   PointerType *PR = dyn_cast<PointerType>(R);
2437   if (!PL || !PR)
2438     return false;
2439   return PL->getAddressSpace() == PR->getAddressSpace();
2440 }
2441
2442 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2443   static const Attribute::AttrKind ABIAttrs[] = {
2444       Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2445       Attribute::InReg, Attribute::Returned};
2446   AttrBuilder Copy;
2447   for (auto AK : ABIAttrs) {
2448     if (Attrs.hasAttribute(I + 1, AK))
2449       Copy.addAttribute(AK);
2450   }
2451   if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2452     Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2453   return Copy;
2454 }
2455
2456 void Verifier::verifyMustTailCall(CallInst &CI) {
2457   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2458
2459   // - The caller and callee prototypes must match.  Pointer types of
2460   //   parameters or return types may differ in pointee type, but not
2461   //   address space.
2462   Function *F = CI.getParent()->getParent();
2463   FunctionType *CallerTy = F->getFunctionType();
2464   FunctionType *CalleeTy = CI.getFunctionType();
2465   Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2466          "cannot guarantee tail call due to mismatched parameter counts", &CI);
2467   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2468          "cannot guarantee tail call due to mismatched varargs", &CI);
2469   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2470          "cannot guarantee tail call due to mismatched return types", &CI);
2471   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2472     Assert(
2473         isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2474         "cannot guarantee tail call due to mismatched parameter types", &CI);
2475   }
2476
2477   // - The calling conventions of the caller and callee must match.
2478   Assert(F->getCallingConv() == CI.getCallingConv(),
2479          "cannot guarantee tail call due to mismatched calling conv", &CI);
2480
2481   // - All ABI-impacting function attributes, such as sret, byval, inreg,
2482   //   returned, and inalloca, must match.
2483   AttributeSet CallerAttrs = F->getAttributes();
2484   AttributeSet CalleeAttrs = CI.getAttributes();
2485   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2486     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2487     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2488     Assert(CallerABIAttrs == CalleeABIAttrs,
2489            "cannot guarantee tail call due to mismatched ABI impacting "
2490            "function attributes",
2491            &CI, CI.getOperand(I));
2492   }
2493
2494   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2495   //   or a pointer bitcast followed by a ret instruction.
2496   // - The ret instruction must return the (possibly bitcasted) value
2497   //   produced by the call or void.
2498   Value *RetVal = &CI;
2499   Instruction *Next = CI.getNextNode();
2500
2501   // Handle the optional bitcast.
2502   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2503     Assert(BI->getOperand(0) == RetVal,
2504            "bitcast following musttail call must use the call", BI);
2505     RetVal = BI;
2506     Next = BI->getNextNode();
2507   }
2508
2509   // Check the return.
2510   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2511   Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2512          &CI);
2513   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2514          "musttail call result must be returned", Ret);
2515 }
2516
2517 void Verifier::visitCallInst(CallInst &CI) {
2518   VerifyCallSite(&CI);
2519
2520   if (CI.isMustTailCall())
2521     verifyMustTailCall(CI);
2522 }
2523
2524 void Verifier::visitInvokeInst(InvokeInst &II) {
2525   VerifyCallSite(&II);
2526
2527   // Verify that the first non-PHI instruction of the unwind destination is an
2528   // exception handling instruction.
2529   Assert(
2530       II.getUnwindDest()->isEHPad(),
2531       "The unwind destination does not have an exception handling instruction!",
2532       &II);
2533
2534   visitTerminatorInst(II);
2535 }
2536
2537 /// visitBinaryOperator - Check that both arguments to the binary operator are
2538 /// of the same type!
2539 ///
2540 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2541   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2542          "Both operands to a binary operator are not of the same type!", &B);
2543
2544   switch (B.getOpcode()) {
2545   // Check that integer arithmetic operators are only used with
2546   // integral operands.
2547   case Instruction::Add:
2548   case Instruction::Sub:
2549   case Instruction::Mul:
2550   case Instruction::SDiv:
2551   case Instruction::UDiv:
2552   case Instruction::SRem:
2553   case Instruction::URem:
2554     Assert(B.getType()->isIntOrIntVectorTy(),
2555            "Integer arithmetic operators only work with integral types!", &B);
2556     Assert(B.getType() == B.getOperand(0)->getType(),
2557            "Integer arithmetic operators must have same type "
2558            "for operands and result!",
2559            &B);
2560     break;
2561   // Check that floating-point arithmetic operators are only used with
2562   // floating-point operands.
2563   case Instruction::FAdd:
2564   case Instruction::FSub:
2565   case Instruction::FMul:
2566   case Instruction::FDiv:
2567   case Instruction::FRem:
2568     Assert(B.getType()->isFPOrFPVectorTy(),
2569            "Floating-point arithmetic operators only work with "
2570            "floating-point types!",
2571            &B);
2572     Assert(B.getType() == B.getOperand(0)->getType(),
2573            "Floating-point arithmetic operators must have same type "
2574            "for operands and result!",
2575            &B);
2576     break;
2577   // Check that logical operators are only used with integral operands.
2578   case Instruction::And:
2579   case Instruction::Or:
2580   case Instruction::Xor:
2581     Assert(B.getType()->isIntOrIntVectorTy(),
2582            "Logical operators only work with integral types!", &B);
2583     Assert(B.getType() == B.getOperand(0)->getType(),
2584            "Logical operators must have same type for operands and result!",
2585            &B);
2586     break;
2587   case Instruction::Shl:
2588   case Instruction::LShr:
2589   case Instruction::AShr:
2590     Assert(B.getType()->isIntOrIntVectorTy(),
2591            "Shifts only work with integral types!", &B);
2592     Assert(B.getType() == B.getOperand(0)->getType(),
2593            "Shift return type must be same as operands!", &B);
2594     break;
2595   default:
2596     llvm_unreachable("Unknown BinaryOperator opcode!");
2597   }
2598
2599   visitInstruction(B);
2600 }
2601
2602 void Verifier::visitICmpInst(ICmpInst &IC) {
2603   // Check that the operands are the same type
2604   Type *Op0Ty = IC.getOperand(0)->getType();
2605   Type *Op1Ty = IC.getOperand(1)->getType();
2606   Assert(Op0Ty == Op1Ty,
2607          "Both operands to ICmp instruction are not of the same type!", &IC);
2608   // Check that the operands are the right type
2609   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2610          "Invalid operand types for ICmp instruction", &IC);
2611   // Check that the predicate is valid.
2612   Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2613              IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2614          "Invalid predicate in ICmp instruction!", &IC);
2615
2616   visitInstruction(IC);
2617 }
2618
2619 void Verifier::visitFCmpInst(FCmpInst &FC) {
2620   // Check that the operands are the same type
2621   Type *Op0Ty = FC.getOperand(0)->getType();
2622   Type *Op1Ty = FC.getOperand(1)->getType();
2623   Assert(Op0Ty == Op1Ty,
2624          "Both operands to FCmp instruction are not of the same type!", &FC);
2625   // Check that the operands are the right type
2626   Assert(Op0Ty->isFPOrFPVectorTy(),
2627          "Invalid operand types for FCmp instruction", &FC);
2628   // Check that the predicate is valid.
2629   Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2630              FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2631          "Invalid predicate in FCmp instruction!", &FC);
2632
2633   visitInstruction(FC);
2634 }
2635
2636 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2637   Assert(
2638       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2639       "Invalid extractelement operands!", &EI);
2640   visitInstruction(EI);
2641 }
2642
2643 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2644   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2645                                             IE.getOperand(2)),
2646          "Invalid insertelement operands!", &IE);
2647   visitInstruction(IE);
2648 }
2649
2650 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2651   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2652                                             SV.getOperand(2)),
2653          "Invalid shufflevector operands!", &SV);
2654   visitInstruction(SV);
2655 }
2656
2657 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2658   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2659
2660   Assert(isa<PointerType>(TargetTy),
2661          "GEP base pointer is not a vector or a vector of pointers", &GEP);
2662   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2663   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2664   Type *ElTy =
2665       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2666   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2667
2668   Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2669              GEP.getResultElementType() == ElTy,
2670          "GEP is not of right type for indices!", &GEP, ElTy);
2671
2672   if (GEP.getType()->isVectorTy()) {
2673     // Additional checks for vector GEPs.
2674     unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2675     if (GEP.getPointerOperandType()->isVectorTy())
2676       Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2677              "Vector GEP result width doesn't match operand's", &GEP);
2678     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2679       Type *IndexTy = Idxs[i]->getType();
2680       if (IndexTy->isVectorTy()) {
2681         unsigned IndexWidth = IndexTy->getVectorNumElements();
2682         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2683       }
2684       Assert(IndexTy->getScalarType()->isIntegerTy(),
2685              "All GEP indices should be of integer type");
2686     }
2687   }
2688   visitInstruction(GEP);
2689 }
2690
2691 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2692   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2693 }
2694
2695 void Verifier::visitRangeMetadata(Instruction& I,
2696                                   MDNode* Range, Type* Ty) {
2697   assert(Range &&
2698          Range == I.getMetadata(LLVMContext::MD_range) &&
2699          "precondition violation");
2700
2701   unsigned NumOperands = Range->getNumOperands();
2702   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2703   unsigned NumRanges = NumOperands / 2;
2704   Assert(NumRanges >= 1, "It should have at least one range!", Range);
2705
2706   ConstantRange LastRange(1); // Dummy initial value
2707   for (unsigned i = 0; i < NumRanges; ++i) {
2708     ConstantInt *Low =
2709         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2710     Assert(Low, "The lower limit must be an integer!", Low);
2711     ConstantInt *High =
2712         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2713     Assert(High, "The upper limit must be an integer!", High);
2714     Assert(High->getType() == Low->getType() && High->getType() == Ty,
2715            "Range types must match instruction type!", &I);
2716
2717     APInt HighV = High->getValue();
2718     APInt LowV = Low->getValue();
2719     ConstantRange CurRange(LowV, HighV);
2720     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2721            "Range must not be empty!", Range);
2722     if (i != 0) {
2723       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2724              "Intervals are overlapping", Range);
2725       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2726              Range);
2727       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2728              Range);
2729     }
2730     LastRange = ConstantRange(LowV, HighV);
2731   }
2732   if (NumRanges > 2) {
2733     APInt FirstLow =
2734         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2735     APInt FirstHigh =
2736         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2737     ConstantRange FirstRange(FirstLow, FirstHigh);
2738     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2739            "Intervals are overlapping", Range);
2740     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2741            Range);
2742   }
2743 }
2744
2745 void Verifier::checkAtomicMemAccessSize(const Module *M, Type *Ty,
2746                                         const Instruction *I) {
2747   unsigned Size = M->getDataLayout().getTypeSizeInBits(Ty);
2748   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
2749   Assert(!(Size & (Size - 1)),
2750          "atomic memory access' operand must have a power-of-two size", Ty, I);
2751 }
2752
2753 void Verifier::visitLoadInst(LoadInst &LI) {
2754   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2755   Assert(PTy, "Load operand must be a pointer.", &LI);
2756   Type *ElTy = LI.getType();
2757   Assert(LI.getAlignment() <= Value::MaximumAlignment,
2758          "huge alignment values are unsupported", &LI);
2759   if (LI.isAtomic()) {
2760     Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2761            "Load cannot have Release ordering", &LI);
2762     Assert(LI.getAlignment() != 0,
2763            "Atomic load must specify explicit alignment", &LI);
2764     Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2765                ElTy->isFloatingPointTy(),
2766            "atomic load operand must have integer, pointer, or floating point "
2767            "type!",
2768            ElTy, &LI);
2769     checkAtomicMemAccessSize(M, ElTy, &LI);
2770   } else {
2771     Assert(LI.getSynchScope() == CrossThread,
2772            "Non-atomic load cannot have SynchronizationScope specified", &LI);
2773   }
2774
2775   visitInstruction(LI);
2776 }
2777
2778 void Verifier::visitStoreInst(StoreInst &SI) {
2779   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2780   Assert(PTy, "Store operand must be a pointer.", &SI);
2781   Type *ElTy = PTy->getElementType();
2782   Assert(ElTy == SI.getOperand(0)->getType(),
2783          "Stored value type does not match pointer operand type!", &SI, ElTy);
2784   Assert(SI.getAlignment() <= Value::MaximumAlignment,
2785          "huge alignment values are unsupported", &SI);
2786   if (SI.isAtomic()) {
2787     Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2788            "Store cannot have Acquire ordering", &SI);
2789     Assert(SI.getAlignment() != 0,
2790            "Atomic store must specify explicit alignment", &SI);
2791     Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2792                ElTy->isFloatingPointTy(),
2793            "atomic store operand must have integer, pointer, or floating point "
2794            "type!",
2795            ElTy, &SI);
2796     checkAtomicMemAccessSize(M, ElTy, &SI);
2797   } else {
2798     Assert(SI.getSynchScope() == CrossThread,
2799            "Non-atomic store cannot have SynchronizationScope specified", &SI);
2800   }
2801   visitInstruction(SI);
2802 }
2803
2804 void Verifier::visitAllocaInst(AllocaInst &AI) {
2805   SmallPtrSet<Type*, 4> Visited;
2806   PointerType *PTy = AI.getType();
2807   Assert(PTy->getAddressSpace() == 0,
2808          "Allocation instruction pointer not in the generic address space!",
2809          &AI);
2810   Assert(AI.getAllocatedType()->isSized(&Visited),
2811          "Cannot allocate unsized type", &AI);
2812   Assert(AI.getArraySize()->getType()->isIntegerTy(),
2813          "Alloca array size must have integer type", &AI);
2814   Assert(AI.getAlignment() <= Value::MaximumAlignment,
2815          "huge alignment values are unsupported", &AI);
2816
2817   visitInstruction(AI);
2818 }
2819
2820 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2821
2822   // FIXME: more conditions???
2823   Assert(CXI.getSuccessOrdering() != NotAtomic,
2824          "cmpxchg instructions must be atomic.", &CXI);
2825   Assert(CXI.getFailureOrdering() != NotAtomic,
2826          "cmpxchg instructions must be atomic.", &CXI);
2827   Assert(CXI.getSuccessOrdering() != Unordered,
2828          "cmpxchg instructions cannot be unordered.", &CXI);
2829   Assert(CXI.getFailureOrdering() != Unordered,
2830          "cmpxchg instructions cannot be unordered.", &CXI);
2831   Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2832          "cmpxchg instructions be at least as constrained on success as fail",
2833          &CXI);
2834   Assert(CXI.getFailureOrdering() != Release &&
2835              CXI.getFailureOrdering() != AcquireRelease,
2836          "cmpxchg failure ordering cannot include release semantics", &CXI);
2837
2838   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2839   Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2840   Type *ElTy = PTy->getElementType();
2841   Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2842          ElTy);
2843   checkAtomicMemAccessSize(M, ElTy, &CXI);
2844   Assert(ElTy == CXI.getOperand(1)->getType(),
2845          "Expected value type does not match pointer operand type!", &CXI,
2846          ElTy);
2847   Assert(ElTy == CXI.getOperand(2)->getType(),
2848          "Stored value type does not match pointer operand type!", &CXI, ElTy);
2849   visitInstruction(CXI);
2850 }
2851
2852 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2853   Assert(RMWI.getOrdering() != NotAtomic,
2854          "atomicrmw instructions must be atomic.", &RMWI);
2855   Assert(RMWI.getOrdering() != Unordered,
2856          "atomicrmw instructions cannot be unordered.", &RMWI);
2857   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2858   Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2859   Type *ElTy = PTy->getElementType();
2860   Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2861          &RMWI, ElTy);
2862   checkAtomicMemAccessSize(M, ElTy, &RMWI);
2863   Assert(ElTy == RMWI.getOperand(1)->getType(),
2864          "Argument value type does not match pointer operand type!", &RMWI,
2865          ElTy);
2866   Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2867              RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2868          "Invalid binary operation!", &RMWI);
2869   visitInstruction(RMWI);
2870 }
2871
2872 void Verifier::visitFenceInst(FenceInst &FI) {
2873   const AtomicOrdering Ordering = FI.getOrdering();
2874   Assert(Ordering == Acquire || Ordering == Release ||
2875              Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2876          "fence instructions may only have "
2877          "acquire, release, acq_rel, or seq_cst ordering.",
2878          &FI);
2879   visitInstruction(FI);
2880 }
2881
2882 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2883   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2884                                           EVI.getIndices()) == EVI.getType(),
2885          "Invalid ExtractValueInst operands!", &EVI);
2886
2887   visitInstruction(EVI);
2888 }
2889
2890 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2891   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2892                                           IVI.getIndices()) ==
2893              IVI.getOperand(1)->getType(),
2894          "Invalid InsertValueInst operands!", &IVI);
2895
2896   visitInstruction(IVI);
2897 }
2898
2899 static Value *getParentPad(Value *EHPad) {
2900   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
2901     return FPI->getParentPad();
2902
2903   return cast<CatchSwitchInst>(EHPad)->getParentPad();
2904 }
2905
2906 void Verifier::visitEHPadPredecessors(Instruction &I) {
2907   assert(I.isEHPad());
2908
2909   BasicBlock *BB = I.getParent();
2910   Function *F = BB->getParent();
2911
2912   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2913
2914   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2915     // The landingpad instruction defines its parent as a landing pad block. The
2916     // landing pad block may be branched to only by the unwind edge of an
2917     // invoke.
2918     for (BasicBlock *PredBB : predecessors(BB)) {
2919       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2920       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2921              "Block containing LandingPadInst must be jumped to "
2922              "only by the unwind edge of an invoke.",
2923              LPI);
2924     }
2925     return;
2926   }
2927   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2928     if (!pred_empty(BB))
2929       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
2930              "Block containg CatchPadInst must be jumped to "
2931              "only by its catchswitch.",
2932              CPI);
2933     return;
2934   }
2935
2936   // Verify that each pred has a legal terminator with a legal to/from EH
2937   // pad relationship.
2938   Instruction *ToPad = &I;
2939   Value *ToPadParent = getParentPad(ToPad);
2940   for (BasicBlock *PredBB : predecessors(BB)) {
2941     TerminatorInst *TI = PredBB->getTerminator();
2942     Value *FromPad;
2943     if (auto *II = dyn_cast<InvokeInst>(TI)) {
2944       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
2945              "EH pad must be jumped to via an unwind edge", ToPad, II);
2946       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
2947         FromPad = Bundle->Inputs[0];
2948       else
2949         FromPad = ConstantTokenNone::get(II->getContext());
2950     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2951       FromPad = CRI->getCleanupPad();
2952       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
2953     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
2954       FromPad = CSI;
2955     } else {
2956       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
2957     }
2958
2959     // The edge may exit from zero or more nested pads.
2960     for (;; FromPad = getParentPad(FromPad)) {
2961       Assert(FromPad != ToPad,
2962              "EH pad cannot handle exceptions raised within it", FromPad, TI);
2963       if (FromPad == ToPadParent) {
2964         // This is a legal unwind edge.
2965         break;
2966       }
2967       Assert(!isa<ConstantTokenNone>(FromPad),
2968              "A single unwind edge may only enter one EH pad", TI);
2969     }
2970   }
2971 }
2972
2973 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2974   // The landingpad instruction is ill-formed if it doesn't have any clauses and
2975   // isn't a cleanup.
2976   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2977          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2978
2979   visitEHPadPredecessors(LPI);
2980
2981   if (!LandingPadResultTy)
2982     LandingPadResultTy = LPI.getType();
2983   else
2984     Assert(LandingPadResultTy == LPI.getType(),
2985            "The landingpad instruction should have a consistent result type "
2986            "inside a function.",
2987            &LPI);
2988
2989   Function *F = LPI.getParent()->getParent();
2990   Assert(F->hasPersonalityFn(),
2991          "LandingPadInst needs to be in a function with a personality.", &LPI);
2992
2993   // The landingpad instruction must be the first non-PHI instruction in the
2994   // block.
2995   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2996          "LandingPadInst not the first non-PHI instruction in the block.",
2997          &LPI);
2998
2999   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
3000     Constant *Clause = LPI.getClause(i);
3001     if (LPI.isCatch(i)) {
3002       Assert(isa<PointerType>(Clause->getType()),
3003              "Catch operand does not have pointer type!", &LPI);
3004     } else {
3005       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3006       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3007              "Filter operand is not an array of constants!", &LPI);
3008     }
3009   }
3010
3011   visitInstruction(LPI);
3012 }
3013
3014 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
3015   visitEHPadPredecessors(CPI);
3016
3017   BasicBlock *BB = CPI.getParent();
3018
3019   Function *F = BB->getParent();
3020   Assert(F->hasPersonalityFn(),
3021          "CatchPadInst needs to be in a function with a personality.", &CPI);
3022
3023   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3024          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3025          CPI.getParentPad());
3026
3027   // The catchpad instruction must be the first non-PHI instruction in the
3028   // block.
3029   Assert(BB->getFirstNonPHI() == &CPI,
3030          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
3031
3032   visitFuncletPadInst(CPI);
3033 }
3034
3035 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3036   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3037          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3038          CatchReturn.getOperand(0));
3039
3040   visitTerminatorInst(CatchReturn);
3041 }
3042
3043 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3044   visitEHPadPredecessors(CPI);
3045
3046   BasicBlock *BB = CPI.getParent();
3047
3048   Function *F = BB->getParent();
3049   Assert(F->hasPersonalityFn(),
3050          "CleanupPadInst needs to be in a function with a personality.", &CPI);
3051
3052   // The cleanuppad instruction must be the first non-PHI instruction in the
3053   // block.
3054   Assert(BB->getFirstNonPHI() == &CPI,
3055          "CleanupPadInst not the first non-PHI instruction in the block.",
3056          &CPI);
3057
3058   auto *ParentPad = CPI.getParentPad();
3059   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3060          "CleanupPadInst has an invalid parent.", &CPI);
3061
3062   visitFuncletPadInst(CPI);
3063 }
3064
3065 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
3066   User *FirstUser = nullptr;
3067   Value *FirstUnwindPad = nullptr;
3068   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
3069   while (!Worklist.empty()) {
3070     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
3071     Value *UnresolvedAncestorPad = nullptr;
3072     for (User *U : CurrentPad->users()) {
3073       BasicBlock *UnwindDest;
3074       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3075         UnwindDest = CRI->getUnwindDest();
3076       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3077         // We allow catchswitch unwind to caller to nest
3078         // within an outer pad that unwinds somewhere else,
3079         // because catchswitch doesn't have a nounwind variant.
3080         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3081         if (CSI->unwindsToCaller())
3082           continue;
3083         UnwindDest = CSI->getUnwindDest();
3084       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
3085         UnwindDest = II->getUnwindDest();
3086       } else if (isa<CallInst>(U)) {
3087         // Calls which don't unwind may be found inside funclet
3088         // pads that unwind somewhere else.  We don't *require*
3089         // such calls to be annotated nounwind.
3090         continue;
3091       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3092         // The unwind dest for a cleanup can only be found by
3093         // recursive search.  Add it to the worklist, and we'll
3094         // search for its first use that determines where it unwinds.
3095         Worklist.push_back(CPI);
3096         continue;
3097       } else {
3098         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
3099         continue;
3100       }
3101
3102       Value *UnwindPad;
3103       bool ExitsFPI;
3104       if (UnwindDest) {
3105         UnwindPad = UnwindDest->getFirstNonPHI();
3106         Value *UnwindParent = getParentPad(UnwindPad);
3107         // Ignore unwind edges that don't exit CurrentPad.
3108         if (UnwindParent == CurrentPad)
3109           continue;
3110         // Determine whether the original funclet pad is exited,
3111         // and if we are scanning nested pads determine how many
3112         // of them are exited so we can stop searching their
3113         // children.
3114         Value *ExitedPad = CurrentPad;
3115         ExitsFPI = false;
3116         do {
3117           if (ExitedPad == &FPI) {
3118             ExitsFPI = true;
3119             // Now we can resolve any ancestors of CurrentPad up to
3120             // FPI, but not including FPI since we need to make sure
3121             // to check all direct users of FPI for consistency.
3122             UnresolvedAncestorPad = &FPI;
3123             break;
3124           }
3125           Value *ExitedParent = getParentPad(ExitedPad);
3126           if (ExitedParent == UnwindParent) {
3127             // ExitedPad is the ancestor-most pad which this unwind
3128             // edge exits, so we can resolve up to it, meaning that
3129             // ExitedParent is the first ancestor still unresolved.
3130             UnresolvedAncestorPad = ExitedParent;
3131             break;
3132           }
3133           ExitedPad = ExitedParent;
3134         } while (!isa<ConstantTokenNone>(ExitedPad));
3135       } else {
3136         // Unwinding to caller exits all pads.
3137         UnwindPad = ConstantTokenNone::get(FPI.getContext());
3138         ExitsFPI = true;
3139         UnresolvedAncestorPad = &FPI;
3140       }
3141
3142       if (ExitsFPI) {
3143         // This unwind edge exits FPI.  Make sure it agrees with other
3144         // such edges.
3145         if (FirstUser) {
3146           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
3147                                               "pad must have the same unwind "
3148                                               "dest",
3149                  &FPI, U, FirstUser);
3150         } else {
3151           FirstUser = U;
3152           FirstUnwindPad = UnwindPad;
3153         }
3154       }
3155       // Make sure we visit all uses of FPI, but for nested pads stop as
3156       // soon as we know where they unwind to.
3157       if (CurrentPad != &FPI)
3158         break;
3159     }
3160     if (UnresolvedAncestorPad) {
3161       if (CurrentPad == UnresolvedAncestorPad) {
3162         // When CurrentPad is FPI itself, we don't mark it as resolved even if
3163         // we've found an unwind edge that exits it, because we need to verify
3164         // all direct uses of FPI.
3165         assert(CurrentPad == &FPI);
3166         continue;
3167       }
3168       // Pop off the worklist any nested pads that we've found an unwind
3169       // destination for.  The pads on the worklist are the uncles,
3170       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
3171       // for all ancestors of CurrentPad up to but not including
3172       // UnresolvedAncestorPad.
3173       Value *ResolvedPad = CurrentPad;
3174       while (!Worklist.empty()) {
3175         Value *UnclePad = Worklist.back();
3176         Value *AncestorPad = getParentPad(UnclePad);
3177         // Walk ResolvedPad up the ancestor list until we either find the
3178         // uncle's parent or the last resolved ancestor.
3179         while (ResolvedPad != AncestorPad) {
3180           Value *ResolvedParent = getParentPad(ResolvedPad);
3181           if (ResolvedParent == UnresolvedAncestorPad) {
3182             break;
3183           }
3184           ResolvedPad = ResolvedParent;
3185         }
3186         // If the resolved ancestor search didn't find the uncle's parent,
3187         // then the uncle is not yet resolved.
3188         if (ResolvedPad != AncestorPad)
3189           break;
3190         // This uncle is resolved, so pop it from the worklist.
3191         Worklist.pop_back();
3192       }
3193     }
3194   }
3195
3196   if (FirstUnwindPad) {
3197     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
3198       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3199       Value *SwitchUnwindPad;
3200       if (SwitchUnwindDest)
3201         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
3202       else
3203         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
3204       Assert(SwitchUnwindPad == FirstUnwindPad,
3205              "Unwind edges out of a catch must have the same unwind dest as "
3206              "the parent catchswitch",
3207              &FPI, FirstUser, CatchSwitch);
3208     }
3209   }
3210
3211   visitInstruction(FPI);
3212 }
3213
3214 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
3215   visitEHPadPredecessors(CatchSwitch);
3216
3217   BasicBlock *BB = CatchSwitch.getParent();
3218
3219   Function *F = BB->getParent();
3220   Assert(F->hasPersonalityFn(),
3221          "CatchSwitchInst needs to be in a function with a personality.",
3222          &CatchSwitch);
3223
3224   // The catchswitch instruction must be the first non-PHI instruction in the
3225   // block.
3226   Assert(BB->getFirstNonPHI() == &CatchSwitch,
3227          "CatchSwitchInst not the first non-PHI instruction in the block.",
3228          &CatchSwitch);
3229
3230   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
3231     Instruction *I = UnwindDest->getFirstNonPHI();
3232     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3233            "CatchSwitchInst must unwind to an EH block which is not a "
3234            "landingpad.",
3235            &CatchSwitch);
3236   }
3237
3238   auto *ParentPad = CatchSwitch.getParentPad();
3239   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3240          "CatchSwitchInst has an invalid parent.", ParentPad);
3241
3242   Assert(CatchSwitch.getNumHandlers() != 0,
3243          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3244
3245   for (BasicBlock *Handler : CatchSwitch.handlers()) {
3246     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3247            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
3248   }
3249
3250   visitTerminatorInst(CatchSwitch);
3251 }
3252
3253 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3254   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3255          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3256          CRI.getOperand(0));
3257
3258   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3259     Instruction *I = UnwindDest->getFirstNonPHI();
3260     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3261            "CleanupReturnInst must unwind to an EH block which is not a "
3262            "landingpad.",
3263            &CRI);
3264   }
3265
3266   visitTerminatorInst(CRI);
3267 }
3268
3269 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3270   Instruction *Op = cast<Instruction>(I.getOperand(i));
3271   // If the we have an invalid invoke, don't try to compute the dominance.
3272   // We already reject it in the invoke specific checks and the dominance
3273   // computation doesn't handle multiple edges.
3274   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3275     if (II->getNormalDest() == II->getUnwindDest())
3276       return;
3277   }
3278
3279   const Use &U = I.getOperandUse(i);
3280   Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3281          "Instruction does not dominate all uses!", Op, &I);
3282 }
3283
3284 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3285   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3286          "apply only to pointer types", &I);
3287   Assert(isa<LoadInst>(I),
3288          "dereferenceable, dereferenceable_or_null apply only to load"
3289          " instructions, use attributes for calls or invokes", &I);
3290   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3291          "take one operand!", &I);
3292   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3293   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3294          "dereferenceable_or_null metadata value must be an i64!", &I);
3295 }
3296
3297 /// verifyInstruction - Verify that an instruction is well formed.
3298 ///
3299 void Verifier::visitInstruction(Instruction &I) {
3300   BasicBlock *BB = I.getParent();
3301   Assert(BB, "Instruction not embedded in basic block!", &I);
3302
3303   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
3304     for (User *U : I.users()) {
3305       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3306              "Only PHI nodes may reference their own value!", &I);
3307     }
3308   }
3309
3310   // Check that void typed values don't have names
3311   Assert(!I.getType()->isVoidTy() || !I.hasName(),
3312          "Instruction has a name, but provides a void value!", &I);
3313
3314   // Check that the return value of the instruction is either void or a legal
3315   // value type.
3316   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3317          "Instruction returns a non-scalar type!", &I);
3318
3319   // Check that the instruction doesn't produce metadata. Calls are already
3320   // checked against the callee type.
3321   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3322          "Invalid use of metadata!", &I);
3323
3324   // Check that all uses of the instruction, if they are instructions
3325   // themselves, actually have parent basic blocks.  If the use is not an
3326   // instruction, it is an error!
3327   for (Use &U : I.uses()) {
3328     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3329       Assert(Used->getParent() != nullptr,
3330              "Instruction referencing"
3331              " instruction not embedded in a basic block!",
3332              &I, Used);
3333     else {
3334       CheckFailed("Use of instruction is not an instruction!", U);
3335       return;
3336     }
3337   }
3338
3339   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3340     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3341
3342     // Check to make sure that only first-class-values are operands to
3343     // instructions.
3344     if (!I.getOperand(i)->getType()->isFirstClassType()) {
3345       Assert(0, "Instruction operands must be first-class values!", &I);
3346     }
3347
3348     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3349       // Check to make sure that the "address of" an intrinsic function is never
3350       // taken.
3351       Assert(
3352           !F->isIntrinsic() ||
3353               i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3354           "Cannot take the address of an intrinsic!", &I);
3355       Assert(
3356           !F->isIntrinsic() || isa<CallInst>(I) ||
3357               F->getIntrinsicID() == Intrinsic::donothing ||
3358               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3359               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3360               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3361           "Cannot invoke an intrinsinc other than"
3362           " donothing or patchpoint",
3363           &I);
3364       Assert(F->getParent() == M, "Referencing function in another module!",
3365              &I, M, F, F->getParent());
3366     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3367       Assert(OpBB->getParent() == BB->getParent(),
3368              "Referring to a basic block in another function!", &I);
3369     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3370       Assert(OpArg->getParent() == BB->getParent(),
3371              "Referring to an argument in another function!", &I);
3372     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3373       Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent());
3374     } else if (isa<Instruction>(I.getOperand(i))) {
3375       verifyDominatesUse(I, i);
3376     } else if (isa<InlineAsm>(I.getOperand(i))) {
3377       Assert((i + 1 == e && isa<CallInst>(I)) ||
3378                  (i + 3 == e && isa<InvokeInst>(I)),
3379              "Cannot take the address of an inline asm!", &I);
3380     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3381       if (CE->getType()->isPtrOrPtrVectorTy()) {
3382         // If we have a ConstantExpr pointer, we need to see if it came from an
3383         // illegal bitcast (inttoptr <constant int> )
3384         visitConstantExprsRecursively(CE);
3385       }
3386     }
3387   }
3388
3389   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3390     Assert(I.getType()->isFPOrFPVectorTy(),
3391            "fpmath requires a floating point result!", &I);
3392     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3393     if (ConstantFP *CFP0 =
3394             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3395       APFloat Accuracy = CFP0->getValueAPF();
3396       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3397              "fpmath accuracy not a positive number!", &I);
3398     } else {
3399       Assert(false, "invalid fpmath accuracy!", &I);
3400     }
3401   }
3402
3403   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3404     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3405            "Ranges are only for loads, calls and invokes!", &I);
3406     visitRangeMetadata(I, Range, I.getType());
3407   }
3408
3409   if (I.getMetadata(LLVMContext::MD_nonnull)) {
3410     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3411            &I);
3412     Assert(isa<LoadInst>(I),
3413            "nonnull applies only to load instructions, use attributes"
3414            " for calls or invokes",
3415            &I);
3416   }
3417
3418   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3419     visitDereferenceableMetadata(I, MD);
3420
3421   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3422     visitDereferenceableMetadata(I, MD);
3423
3424   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3425     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3426            &I);
3427     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3428            "use attributes for calls or invokes", &I);
3429     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3430     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3431     Assert(CI && CI->getType()->isIntegerTy(64),
3432            "align metadata value must be an i64!", &I);
3433     uint64_t Align = CI->getZExtValue();
3434     Assert(isPowerOf2_64(Align),
3435            "align metadata value must be a power of 2!", &I);
3436     Assert(Align <= Value::MaximumAlignment,
3437            "alignment is larger that implementation defined limit", &I);
3438   }
3439
3440   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3441     Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3442     visitMDNode(*N);
3443   }
3444
3445   InstsInThisBlock.insert(&I);
3446 }
3447
3448 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3449 /// intrinsic argument or return value) matches the type constraints specified
3450 /// by the .td file (e.g. an "any integer" argument really is an integer).
3451 ///
3452 /// This return true on error but does not print a message.
3453 bool Verifier::VerifyIntrinsicType(Type *Ty,
3454                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
3455                                    SmallVectorImpl<Type*> &ArgTys) {
3456   using namespace Intrinsic;
3457
3458   // If we ran out of descriptors, there are too many arguments.
3459   if (Infos.empty()) return true;
3460   IITDescriptor D = Infos.front();
3461   Infos = Infos.slice(1);
3462
3463   switch (D.Kind) {
3464   case IITDescriptor::Void: return !Ty->isVoidTy();
3465   case IITDescriptor::VarArg: return true;
3466   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
3467   case IITDescriptor::Token: return !Ty->isTokenTy();
3468   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3469   case IITDescriptor::Half: return !Ty->isHalfTy();
3470   case IITDescriptor::Float: return !Ty->isFloatTy();
3471   case IITDescriptor::Double: return !Ty->isDoubleTy();
3472   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3473   case IITDescriptor::Vector: {
3474     VectorType *VT = dyn_cast<VectorType>(Ty);
3475     return !VT || VT->getNumElements() != D.Vector_Width ||
3476            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3477   }
3478   case IITDescriptor::Pointer: {
3479     PointerType *PT = dyn_cast<PointerType>(Ty);
3480     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3481            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3482   }
3483
3484   case IITDescriptor::Struct: {
3485     StructType *ST = dyn_cast<StructType>(Ty);
3486     if (!ST || ST->getNumElements() != D.Struct_NumElements)
3487       return true;
3488
3489     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3490       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3491         return true;
3492     return false;
3493   }
3494
3495   case IITDescriptor::Argument:
3496     // Two cases here - If this is the second occurrence of an argument, verify
3497     // that the later instance matches the previous instance.
3498     if (D.getArgumentNumber() < ArgTys.size())
3499       return Ty != ArgTys[D.getArgumentNumber()];
3500
3501     // Otherwise, if this is the first instance of an argument, record it and
3502     // verify the "Any" kind.
3503     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3504     ArgTys.push_back(Ty);
3505
3506     switch (D.getArgumentKind()) {
3507     case IITDescriptor::AK_Any:        return false; // Success
3508     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3509     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
3510     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
3511     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3512     }
3513     llvm_unreachable("all argument kinds not covered");
3514
3515   case IITDescriptor::ExtendArgument: {
3516     // This may only be used when referring to a previous vector argument.
3517     if (D.getArgumentNumber() >= ArgTys.size())
3518       return true;
3519
3520     Type *NewTy = ArgTys[D.getArgumentNumber()];
3521     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3522       NewTy = VectorType::getExtendedElementVectorType(VTy);
3523     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3524       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3525     else
3526       return true;
3527
3528     return Ty != NewTy;
3529   }
3530   case IITDescriptor::TruncArgument: {
3531     // This may only be used when referring to a previous vector argument.
3532     if (D.getArgumentNumber() >= ArgTys.size())
3533       return true;
3534
3535     Type *NewTy = ArgTys[D.getArgumentNumber()];
3536     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3537       NewTy = VectorType::getTruncatedElementVectorType(VTy);
3538     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3539       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3540     else
3541       return true;
3542
3543     return Ty != NewTy;
3544   }
3545   case IITDescriptor::HalfVecArgument:
3546     // This may only be used when referring to a previous vector argument.
3547     return D.getArgumentNumber() >= ArgTys.size() ||
3548            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3549            VectorType::getHalfElementsVectorType(
3550                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3551   case IITDescriptor::SameVecWidthArgument: {
3552     if (D.getArgumentNumber() >= ArgTys.size())
3553       return true;
3554     VectorType * ReferenceType =
3555       dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3556     VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3557     if (!ThisArgType || !ReferenceType || 
3558         (ReferenceType->getVectorNumElements() !=
3559          ThisArgType->getVectorNumElements()))
3560       return true;
3561     return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3562                                Infos, ArgTys);
3563   }
3564   case IITDescriptor::PtrToArgument: {
3565     if (D.getArgumentNumber() >= ArgTys.size())
3566       return true;
3567     Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3568     PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3569     return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3570   }
3571   case IITDescriptor::VecOfPtrsToElt: {
3572     if (D.getArgumentNumber() >= ArgTys.size())
3573       return true;
3574     VectorType * ReferenceType =
3575       dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3576     VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3577     if (!ThisArgVecTy || !ReferenceType || 
3578         (ReferenceType->getVectorNumElements() !=
3579          ThisArgVecTy->getVectorNumElements()))
3580       return true;
3581     PointerType *ThisArgEltTy =
3582       dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3583     if (!ThisArgEltTy)
3584       return true;
3585     return ThisArgEltTy->getElementType() !=
3586            ReferenceType->getVectorElementType();
3587   }
3588   }
3589   llvm_unreachable("unhandled");
3590 }
3591
3592 /// \brief Verify if the intrinsic has variable arguments.
3593 /// This method is intended to be called after all the fixed arguments have been
3594 /// verified first.
3595 ///
3596 /// This method returns true on error and does not print an error message.
3597 bool
3598 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3599                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3600   using namespace Intrinsic;
3601
3602   // If there are no descriptors left, then it can't be a vararg.
3603   if (Infos.empty())
3604     return isVarArg;
3605
3606   // There should be only one descriptor remaining at this point.
3607   if (Infos.size() != 1)
3608     return true;
3609
3610   // Check and verify the descriptor.
3611   IITDescriptor D = Infos.front();
3612   Infos = Infos.slice(1);
3613   if (D.Kind == IITDescriptor::VarArg)
3614     return !isVarArg;
3615
3616   return true;
3617 }
3618
3619 /// Allow intrinsics to be verified in different ways.
3620 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3621   Function *IF = CS.getCalledFunction();
3622   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3623          IF);
3624
3625   // Verify that the intrinsic prototype lines up with what the .td files
3626   // describe.
3627   FunctionType *IFTy = IF->getFunctionType();
3628   bool IsVarArg = IFTy->isVarArg();
3629
3630   SmallVector<Intrinsic::IITDescriptor, 8> Table;
3631   getIntrinsicInfoTableEntries(ID, Table);
3632   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3633
3634   SmallVector<Type *, 4> ArgTys;
3635   Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3636          "Intrinsic has incorrect return type!", IF);
3637   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3638     Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3639            "Intrinsic has incorrect argument type!", IF);
3640
3641   // Verify if the intrinsic call matches the vararg property.
3642   if (IsVarArg)
3643     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3644            "Intrinsic was not defined with variable arguments!", IF);
3645   else
3646     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3647            "Callsite was not defined with variable arguments!", IF);
3648
3649   // All descriptors should be absorbed by now.
3650   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3651
3652   // Now that we have the intrinsic ID and the actual argument types (and we
3653   // know they are legal for the intrinsic!) get the intrinsic name through the
3654   // usual means.  This allows us to verify the mangling of argument types into
3655   // the name.
3656   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3657   Assert(ExpectedName == IF->getName(),
3658          "Intrinsic name not mangled correctly for type arguments! "
3659          "Should be: " +
3660              ExpectedName,
3661          IF);
3662
3663   // If the intrinsic takes MDNode arguments, verify that they are either global
3664   // or are local to *this* function.
3665   for (Value *V : CS.args()) 
3666     if (auto *MD = dyn_cast<MetadataAsValue>(V))
3667       visitMetadataAsValue(*MD, CS.getCaller());
3668
3669   switch (ID) {
3670   default:
3671     break;
3672   case Intrinsic::ctlz:  // llvm.ctlz
3673   case Intrinsic::cttz:  // llvm.cttz
3674     Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3675            "is_zero_undef argument of bit counting intrinsics must be a "
3676            "constant int",
3677            CS);
3678     break;
3679   case Intrinsic::dbg_declare: // llvm.dbg.declare
3680     Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3681            "invalid llvm.dbg.declare intrinsic call 1", CS);
3682     visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3683     break;
3684   case Intrinsic::dbg_value: // llvm.dbg.value
3685     visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3686     break;
3687   case Intrinsic::memcpy:
3688   case Intrinsic::memmove:
3689   case Intrinsic::memset: {
3690     ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3691     Assert(AlignCI,
3692            "alignment argument of memory intrinsics must be a constant int",
3693            CS);
3694     const APInt &AlignVal = AlignCI->getValue();
3695     Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3696            "alignment argument of memory intrinsics must be a power of 2", CS);
3697     Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3698            "isvolatile argument of memory intrinsics must be a constant int",
3699            CS);
3700     break;
3701   }
3702   case Intrinsic::gcroot:
3703   case Intrinsic::gcwrite:
3704   case Intrinsic::gcread:
3705     if (ID == Intrinsic::gcroot) {
3706       AllocaInst *AI =
3707         dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3708       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3709       Assert(isa<Constant>(CS.getArgOperand(1)),
3710              "llvm.gcroot parameter #2 must be a constant.", CS);
3711       if (!AI->getAllocatedType()->isPointerTy()) {
3712         Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3713                "llvm.gcroot parameter #1 must either be a pointer alloca, "
3714                "or argument #2 must be a non-null constant.",
3715                CS);
3716       }
3717     }
3718
3719     Assert(CS.getParent()->getParent()->hasGC(),
3720            "Enclosing function does not use GC.", CS);
3721     break;
3722   case Intrinsic::init_trampoline:
3723     Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3724            "llvm.init_trampoline parameter #2 must resolve to a function.",
3725            CS);
3726     break;
3727   case Intrinsic::prefetch:
3728     Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3729                isa<ConstantInt>(CS.getArgOperand(2)) &&
3730                cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3731                cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3732            "invalid arguments to llvm.prefetch", CS);
3733     break;
3734   case Intrinsic::stackprotector:
3735     Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3736            "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3737     break;
3738   case Intrinsic::lifetime_start:
3739   case Intrinsic::lifetime_end:
3740   case Intrinsic::invariant_start:
3741     Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3742            "size argument of memory use markers must be a constant integer",
3743            CS);
3744     break;
3745   case Intrinsic::invariant_end:
3746     Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3747            "llvm.invariant.end parameter #2 must be a constant integer", CS);
3748     break;
3749
3750   case Intrinsic::localescape: {
3751     BasicBlock *BB = CS.getParent();
3752     Assert(BB == &BB->getParent()->front(),
3753            "llvm.localescape used outside of entry block", CS);
3754     Assert(!SawFrameEscape,
3755            "multiple calls to llvm.localescape in one function", CS);
3756     for (Value *Arg : CS.args()) {
3757       if (isa<ConstantPointerNull>(Arg))
3758         continue; // Null values are allowed as placeholders.
3759       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3760       Assert(AI && AI->isStaticAlloca(),
3761              "llvm.localescape only accepts static allocas", CS);
3762     }
3763     FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3764     SawFrameEscape = true;
3765     break;
3766   }
3767   case Intrinsic::localrecover: {
3768     Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3769     Function *Fn = dyn_cast<Function>(FnArg);
3770     Assert(Fn && !Fn->isDeclaration(),
3771            "llvm.localrecover first "
3772            "argument must be function defined in this module",
3773            CS);
3774     auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3775     Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3776            CS);
3777     auto &Entry = FrameEscapeInfo[Fn];
3778     Entry.second = unsigned(
3779         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3780     break;
3781   }
3782
3783   case Intrinsic::experimental_gc_statepoint:
3784     Assert(!CS.isInlineAsm(),
3785            "gc.statepoint support for inline assembly unimplemented", CS);
3786     Assert(CS.getParent()->getParent()->hasGC(),
3787            "Enclosing function does not use GC.", CS);
3788
3789     VerifyStatepoint(CS);
3790     break;
3791   case Intrinsic::experimental_gc_result: {
3792     Assert(CS.getParent()->getParent()->hasGC(),
3793            "Enclosing function does not use GC.", CS);
3794     // Are we tied to a statepoint properly?
3795     CallSite StatepointCS(CS.getArgOperand(0));
3796     const Function *StatepointFn =
3797       StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3798     Assert(StatepointFn && StatepointFn->isDeclaration() &&
3799                StatepointFn->getIntrinsicID() ==
3800                    Intrinsic::experimental_gc_statepoint,
3801            "gc.result operand #1 must be from a statepoint", CS,
3802            CS.getArgOperand(0));
3803
3804     // Assert that result type matches wrapped callee.
3805     const Value *Target = StatepointCS.getArgument(2);
3806     auto *PT = cast<PointerType>(Target->getType());
3807     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3808     Assert(CS.getType() == TargetFuncType->getReturnType(),
3809            "gc.result result type does not match wrapped callee", CS);
3810     break;
3811   }
3812   case Intrinsic::experimental_gc_relocate: {
3813     Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3814
3815     Assert(isa<PointerType>(CS.getType()->getScalarType()),
3816            "gc.relocate must return a pointer or a vector of pointers", CS);
3817
3818     // Check that this relocate is correctly tied to the statepoint
3819
3820     // This is case for relocate on the unwinding path of an invoke statepoint
3821     if (LandingPadInst *LandingPad =
3822           dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
3823
3824       const BasicBlock *InvokeBB =
3825           LandingPad->getParent()->getUniquePredecessor();
3826
3827       // Landingpad relocates should have only one predecessor with invoke
3828       // statepoint terminator
3829       Assert(InvokeBB, "safepoints should have unique landingpads",
3830              LandingPad->getParent());
3831       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3832              InvokeBB);
3833       Assert(isStatepoint(InvokeBB->getTerminator()),
3834              "gc relocate should be linked to a statepoint", InvokeBB);
3835     }
3836     else {
3837       // In all other cases relocate should be tied to the statepoint directly.
3838       // This covers relocates on a normal return path of invoke statepoint and
3839       // relocates of a call statepoint
3840       auto Token = CS.getArgOperand(0);
3841       Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3842              "gc relocate is incorrectly tied to the statepoint", CS, Token);
3843     }
3844
3845     // Verify rest of the relocate arguments
3846
3847     ImmutableCallSite StatepointCS(
3848         cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
3849
3850     // Both the base and derived must be piped through the safepoint
3851     Value* Base = CS.getArgOperand(1);
3852     Assert(isa<ConstantInt>(Base),
3853            "gc.relocate operand #2 must be integer offset", CS);
3854
3855     Value* Derived = CS.getArgOperand(2);
3856     Assert(isa<ConstantInt>(Derived),
3857            "gc.relocate operand #3 must be integer offset", CS);
3858
3859     const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3860     const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3861     // Check the bounds
3862     Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3863            "gc.relocate: statepoint base index out of bounds", CS);
3864     Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3865            "gc.relocate: statepoint derived index out of bounds", CS);
3866
3867     // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3868     // section of the statepoint's argument
3869     Assert(StatepointCS.arg_size() > 0,
3870            "gc.statepoint: insufficient arguments");
3871     Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3872            "gc.statement: number of call arguments must be constant integer");
3873     const unsigned NumCallArgs =
3874         cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3875     Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3876            "gc.statepoint: mismatch in number of call arguments");
3877     Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3878            "gc.statepoint: number of transition arguments must be "
3879            "a constant integer");
3880     const int NumTransitionArgs =
3881         cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3882             ->getZExtValue();
3883     const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3884     Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3885            "gc.statepoint: number of deoptimization arguments must be "
3886            "a constant integer");
3887     const int NumDeoptArgs =
3888       cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3889     const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3890     const int GCParamArgsEnd = StatepointCS.arg_size();
3891     Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3892            "gc.relocate: statepoint base index doesn't fall within the "
3893            "'gc parameters' section of the statepoint call",
3894            CS);
3895     Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3896            "gc.relocate: statepoint derived index doesn't fall within the "
3897            "'gc parameters' section of the statepoint call",
3898            CS);
3899
3900     // Relocated value must be either a pointer type or vector-of-pointer type,
3901     // but gc_relocate does not need to return the same pointer type as the
3902     // relocated pointer. It can be casted to the correct type later if it's
3903     // desired. However, they must have the same address space and 'vectorness'
3904     GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
3905     Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(),
3906            "gc.relocate: relocated value must be a gc pointer", CS);
3907
3908     auto ResultType = CS.getType();
3909     auto DerivedType = Relocate.getDerivedPtr()->getType();
3910     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
3911            "gc.relocate: vector relocates to vector and pointer to pointer", CS);
3912     Assert(ResultType->getPointerAddressSpace() ==
3913            DerivedType->getPointerAddressSpace(),
3914            "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3915     break;
3916   }
3917   case Intrinsic::eh_exceptioncode:
3918   case Intrinsic::eh_exceptionpointer: {
3919     Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3920            "eh.exceptionpointer argument must be a catchpad", CS);
3921     break;
3922   }
3923   };
3924 }
3925
3926 /// \brief Carefully grab the subprogram from a local scope.
3927 ///
3928 /// This carefully grabs the subprogram from a local scope, avoiding the
3929 /// built-in assertions that would typically fire.
3930 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3931   if (!LocalScope)
3932     return nullptr;
3933
3934   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3935     return SP;
3936
3937   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3938     return getSubprogram(LB->getRawScope());
3939
3940   // Just return null; broken scope chains are checked elsewhere.
3941   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3942   return nullptr;
3943 }
3944
3945 template <class DbgIntrinsicTy>
3946 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3947   auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3948   Assert(isa<ValueAsMetadata>(MD) ||
3949              (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3950          "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3951   Assert(isa<DILocalVariable>(DII.getRawVariable()),
3952          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3953          DII.getRawVariable());
3954   Assert(isa<DIExpression>(DII.getRawExpression()),
3955          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3956          DII.getRawExpression());
3957
3958   // Ignore broken !dbg attachments; they're checked elsewhere.
3959   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3960     if (!isa<DILocation>(N))
3961       return;
3962
3963   BasicBlock *BB = DII.getParent();
3964   Function *F = BB ? BB->getParent() : nullptr;
3965
3966   // The scopes for variables and !dbg attachments must agree.
3967   DILocalVariable *Var = DII.getVariable();
3968   DILocation *Loc = DII.getDebugLoc();
3969   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3970          &DII, BB, F);
3971
3972   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3973   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3974   if (!VarSP || !LocSP)
3975     return; // Broken scope chains are checked elsewhere.
3976
3977   Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3978                              " variable and !dbg attachment",
3979          &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3980          Loc->getScope()->getSubprogram());
3981 }
3982
3983 template <class MapTy>
3984 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3985   // Be careful of broken types (checked elsewhere).
3986   const Metadata *RawType = V.getRawType();
3987   while (RawType) {
3988     // Try to get the size directly.
3989     if (auto *T = dyn_cast<DIType>(RawType))
3990       if (uint64_t Size = T->getSizeInBits())
3991         return Size;
3992
3993     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3994       // Look at the base type.
3995       RawType = DT->getRawBaseType();
3996       continue;
3997     }
3998
3999     if (auto *S = dyn_cast<MDString>(RawType)) {
4000       // Don't error on missing types (checked elsewhere).
4001       RawType = Map.lookup(S);
4002       continue;
4003     }
4004
4005     // Missing type or size.
4006     break;
4007   }
4008
4009   // Fail gracefully.
4010   return 0;
4011 }
4012
4013 template <class MapTy>
4014 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
4015                                         const MapTy &TypeRefs) {
4016   DILocalVariable *V;
4017   DIExpression *E;
4018   if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
4019     V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
4020     E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
4021   } else {
4022     auto *DDI = cast<DbgDeclareInst>(&I);
4023     V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
4024     E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
4025   }
4026
4027   // We don't know whether this intrinsic verified correctly.
4028   if (!V || !E || !E->isValid())
4029     return;
4030
4031   // Nothing to do if this isn't a bit piece expression.
4032   if (!E->isBitPiece())
4033     return;
4034
4035   // The frontend helps out GDB by emitting the members of local anonymous
4036   // unions as artificial local variables with shared storage. When SROA splits
4037   // the storage for artificial local variables that are smaller than the entire
4038   // union, the overhang piece will be outside of the allotted space for the
4039   // variable and this check fails.
4040   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4041   if (V->isArtificial())
4042     return;
4043
4044   // If there's no size, the type is broken, but that should be checked
4045   // elsewhere.
4046   uint64_t VarSize = getVariableSize(*V, TypeRefs);
4047   if (!VarSize)
4048     return;
4049
4050   unsigned PieceSize = E->getBitPieceSize();
4051   unsigned PieceOffset = E->getBitPieceOffset();
4052   Assert(PieceSize + PieceOffset <= VarSize,
4053          "piece is larger than or outside of variable", &I, V, E);
4054   Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
4055 }
4056
4057 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
4058   // This is in its own function so we get an error for each bad type ref (not
4059   // just the first).
4060   Assert(false, "unresolved type ref", S, N);
4061 }
4062
4063 void Verifier::verifyTypeRefs() {
4064   auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
4065   if (!CUs)
4066     return;
4067
4068   // Visit all the compile units again to map the type references.
4069   SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
4070   for (auto *CU : CUs->operands())
4071     if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
4072       for (DIType *Op : Ts)
4073         if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
4074           if (auto *S = T->getRawIdentifier()) {
4075             UnresolvedTypeRefs.erase(S);
4076             TypeRefs.insert(std::make_pair(S, T));
4077           }
4078
4079   // Verify debug info intrinsic bit piece expressions.  This needs a second
4080   // pass through the intructions, since we haven't built TypeRefs yet when
4081   // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
4082   // later/now would queue up some that could be later deleted.
4083   for (const Function &F : *M)
4084     for (const BasicBlock &BB : F)
4085       for (const Instruction &I : BB)
4086         if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
4087           verifyBitPieceExpression(*DII, TypeRefs);
4088
4089   // Return early if all typerefs were resolved.
4090   if (UnresolvedTypeRefs.empty())
4091     return;
4092
4093   // Sort the unresolved references by name so the output is deterministic.
4094   typedef std::pair<const MDString *, const MDNode *> TypeRef;
4095   SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
4096                                       UnresolvedTypeRefs.end());
4097   std::sort(Unresolved.begin(), Unresolved.end(),
4098             [](const TypeRef &LHS, const TypeRef &RHS) {
4099     return LHS.first->getString() < RHS.first->getString();
4100   });
4101
4102   // Visit the unresolved refs (printing out the errors).
4103   for (const TypeRef &TR : Unresolved)
4104     visitUnresolvedTypeRef(TR.first, TR.second);
4105 }
4106
4107 //===----------------------------------------------------------------------===//
4108 //  Implement the public interfaces to this file...
4109 //===----------------------------------------------------------------------===//
4110
4111 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
4112   Function &F = const_cast<Function &>(f);
4113   assert(!F.isDeclaration() && "Cannot verify external functions");
4114
4115   raw_null_ostream NullStr;
4116   Verifier V(OS ? *OS : NullStr);
4117
4118   // Note that this function's return value is inverted from what you would
4119   // expect of a function called "verify".
4120   return !V.verify(F);
4121 }
4122
4123 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
4124   raw_null_ostream NullStr;
4125   Verifier V(OS ? *OS : NullStr);
4126
4127   bool Broken = false;
4128   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
4129     if (!I->isDeclaration() && !I->isMaterializable())
4130       Broken |= !V.verify(*I);
4131
4132   // Note that this function's return value is inverted from what you would
4133   // expect of a function called "verify".
4134   return !V.verify(M) || Broken;
4135 }
4136
4137 namespace {
4138 struct VerifierLegacyPass : public FunctionPass {
4139   static char ID;
4140
4141   Verifier V;
4142   bool FatalErrors;
4143
4144   VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
4145     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
4146   }
4147   explicit VerifierLegacyPass(bool FatalErrors)
4148       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
4149     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
4150   }
4151
4152   bool runOnFunction(Function &F) override {
4153     if (!V.verify(F) && FatalErrors)
4154       report_fatal_error("Broken function found, compilation aborted!");
4155
4156     return false;
4157   }
4158
4159   bool doFinalization(Module &M) override {
4160     if (!V.verify(M) && FatalErrors)
4161       report_fatal_error("Broken module found, compilation aborted!");
4162
4163     return false;
4164   }
4165
4166   void getAnalysisUsage(AnalysisUsage &AU) const override {
4167     AU.setPreservesAll();
4168   }
4169 };
4170 }
4171
4172 char VerifierLegacyPass::ID = 0;
4173 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
4174
4175 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
4176   return new VerifierLegacyPass(FatalErrors);
4177 }
4178
4179 PreservedAnalyses VerifierPass::run(Module &M) {
4180   if (verifyModule(M, &dbgs()) && FatalErrors)
4181     report_fatal_error("Broken module found, compilation aborted!");
4182
4183   return PreservedAnalyses::all();
4184 }
4185
4186 PreservedAnalyses VerifierPass::run(Function &F) {
4187   if (verifyFunction(F, &dbgs()) && FatalErrors)
4188     report_fatal_error("Broken function found, compilation aborted!");
4189
4190   return PreservedAnalyses::all();
4191 }