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