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