1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the function verifier interface, that can be used for some
10 // basic correctness checking of input to the system.
11 //
12 // Note that this does not provide full `Java style' security and verifications,
13 // instead it just tries to ensure that code is well-formed.
14 //
15 //  * Both of a binary operator's parameters are of the same type
16 //  * Verify that the indices of mem access instructions match other operands
17 //  * Verify that arithmetic and other things are only performed on first-class
18 //    types.  Verify that shifts & logicals only happen on integrals f.e.
19 //  * All of the constants in a switch statement are of the correct type
20 //  * The code is in valid SSA form
21 //  * It should be illegal to put a label into any other type (like a structure)
22 //    or to return one. [except constant arrays!]
23 //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24 //  * PHI nodes must have an entry for each predecessor, with no extras.
25 //  * PHI nodes must be the first thing in a basic block, all grouped together
26 //  * PHI nodes must have at least one entry
27 //  * All basic blocks should only end with terminator insts, not contain them
28 //  * The entry node to a function must not have predecessors
29 //  * All Instructions must be embedded into a basic block
30 //  * Functions cannot take a void-typed parameter
31 //  * Verify that a function's argument list agrees with it's declared type.
32 //  * It is illegal to specify a name for a void value.
33 //  * It is illegal to have a internal global value with no initializer
34 //  * It is illegal to have a ret instruction that returns a value that does not
35 //    agree with the function return value type.
36 //  * Function call argument types match the function prototype
37 //  * A landing pad is defined by a landingpad instruction, and can be jumped to
38 //    only by the unwind edge of an invoke instruction.
39 //  * A landingpad instruction must be the first non-PHI instruction in the
40 //    block.
41 //  * Landingpad instructions must be in a function with a personality function.
42 //  * All other things that are tested by asserts spread about the code...
43 //
44 //===----------------------------------------------------------------------===//
45 
46 #include "llvm/IR/Verifier.h"
47 #include "llvm/ADT/APFloat.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/ADT/StringMap.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/ADT/ilist.h"
62 #include "llvm/BinaryFormat/Dwarf.h"
63 #include "llvm/IR/Argument.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/BasicBlock.h"
66 #include "llvm/IR/CFG.h"
67 #include "llvm/IR/CallingConv.h"
68 #include "llvm/IR/Comdat.h"
69 #include "llvm/IR/Constant.h"
70 #include "llvm/IR/ConstantRange.h"
71 #include "llvm/IR/Constants.h"
72 #include "llvm/IR/DataLayout.h"
73 #include "llvm/IR/DebugInfo.h"
74 #include "llvm/IR/DebugInfoMetadata.h"
75 #include "llvm/IR/DebugLoc.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalValue.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstVisitor.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/Metadata.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/ModuleSlotTracker.h"
94 #include "llvm/IR/PassManager.h"
95 #include "llvm/IR/Statepoint.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/Use.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/InitializePasses.h"
101 #include "llvm/Pass.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Debug.h"
106 #include "llvm/Support/ErrorHandling.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include <algorithm>
110 #include <cassert>
111 #include <cstdint>
112 #include <memory>
113 #include <string>
114 #include <utility>
115 
116 using namespace llvm;
117 
118 static cl::opt<bool> VerifyNoAliasScopeDomination(
119     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
120     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
121              "scopes are not dominating"));
122 
123 namespace llvm {
124 
125 struct VerifierSupport {
126   raw_ostream *OS;
127   const Module &M;
128   ModuleSlotTracker MST;
129   Triple TT;
130   const DataLayout &DL;
131   LLVMContext &Context;
132 
133   /// Track the brokenness of the module while recursively visiting.
134   bool Broken = false;
135   /// Broken debug info can be "recovered" from by stripping the debug info.
136   bool BrokenDebugInfo = false;
137   /// Whether to treat broken debug info as an error.
138   bool TreatBrokenDebugInfoAsError = true;
139 
140   explicit VerifierSupport(raw_ostream *OS, const Module &M)
141       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
142         Context(M.getContext()) {}
143 
144 private:
145   void Write(const Module *M) {
146     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
147   }
148 
149   void Write(const Value *V) {
150     if (V)
151       Write(*V);
152   }
153 
154   void Write(const Value &V) {
155     if (isa<Instruction>(V)) {
156       V.print(*OS, MST);
157       *OS << '\n';
158     } else {
159       V.printAsOperand(*OS, true, MST);
160       *OS << '\n';
161     }
162   }
163 
164   void Write(const Metadata *MD) {
165     if (!MD)
166       return;
167     MD->print(*OS, MST, &M);
168     *OS << '\n';
169   }
170 
171   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
172     Write(MD.get());
173   }
174 
175   void Write(const NamedMDNode *NMD) {
176     if (!NMD)
177       return;
178     NMD->print(*OS, MST);
179     *OS << '\n';
180   }
181 
182   void Write(Type *T) {
183     if (!T)
184       return;
185     *OS << ' ' << *T;
186   }
187 
188   void Write(const Comdat *C) {
189     if (!C)
190       return;
191     *OS << *C;
192   }
193 
194   void Write(const APInt *AI) {
195     if (!AI)
196       return;
197     *OS << *AI << '\n';
198   }
199 
200   void Write(const unsigned i) { *OS << i << '\n'; }
201 
202   // NOLINTNEXTLINE(readability-identifier-naming)
203   void Write(const Attribute *A) {
204     if (!A)
205       return;
206     *OS << A->getAsString() << '\n';
207   }
208 
209   // NOLINTNEXTLINE(readability-identifier-naming)
210   void Write(const AttributeSet *AS) {
211     if (!AS)
212       return;
213     *OS << AS->getAsString() << '\n';
214   }
215 
216   // NOLINTNEXTLINE(readability-identifier-naming)
217   void Write(const AttributeList *AL) {
218     if (!AL)
219       return;
220     AL->print(*OS);
221   }
222 
223   template <typename T> void Write(ArrayRef<T> Vs) {
224     for (const T &V : Vs)
225       Write(V);
226   }
227 
228   template <typename T1, typename... Ts>
229   void WriteTs(const T1 &V1, const Ts &... Vs) {
230     Write(V1);
231     WriteTs(Vs...);
232   }
233 
234   template <typename... Ts> void WriteTs() {}
235 
236 public:
237   /// A check failed, so printout out the condition and the message.
238   ///
239   /// This provides a nice place to put a breakpoint if you want to see why
240   /// something is not correct.
241   void CheckFailed(const Twine &Message) {
242     if (OS)
243       *OS << Message << '\n';
244     Broken = true;
245   }
246 
247   /// A check failed (with values to print).
248   ///
249   /// This calls the Message-only version so that the above is easier to set a
250   /// breakpoint on.
251   template <typename T1, typename... Ts>
252   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
253     CheckFailed(Message);
254     if (OS)
255       WriteTs(V1, Vs...);
256   }
257 
258   /// A debug info check failed.
259   void DebugInfoCheckFailed(const Twine &Message) {
260     if (OS)
261       *OS << Message << '\n';
262     Broken |= TreatBrokenDebugInfoAsError;
263     BrokenDebugInfo = true;
264   }
265 
266   /// A debug info check failed (with values to print).
267   template <typename T1, typename... Ts>
268   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
269                             const Ts &... Vs) {
270     DebugInfoCheckFailed(Message);
271     if (OS)
272       WriteTs(V1, Vs...);
273   }
274 };
275 
276 } // namespace llvm
277 
278 namespace {
279 
280 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
281   friend class InstVisitor<Verifier>;
282 
283   DominatorTree DT;
284 
285   /// When verifying a basic block, keep track of all of the
286   /// instructions we have seen so far.
287   ///
288   /// This allows us to do efficient dominance checks for the case when an
289   /// instruction has an operand that is an instruction in the same block.
290   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
291 
292   /// Keep track of the metadata nodes that have been checked already.
293   SmallPtrSet<const Metadata *, 32> MDNodes;
294 
295   /// Keep track which DISubprogram is attached to which function.
296   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
297 
298   /// Track all DICompileUnits visited.
299   SmallPtrSet<const Metadata *, 2> CUVisited;
300 
301   /// The result type for a landingpad.
302   Type *LandingPadResultTy;
303 
304   /// Whether we've seen a call to @llvm.localescape in this function
305   /// already.
306   bool SawFrameEscape;
307 
308   /// Whether the current function has a DISubprogram attached to it.
309   bool HasDebugInfo = false;
310 
311   /// The current source language.
312   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
313 
314   /// Whether source was present on the first DIFile encountered in each CU.
315   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
316 
317   /// Stores the count of how many objects were passed to llvm.localescape for a
318   /// given function and the largest index passed to llvm.localrecover.
319   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
320 
321   // Maps catchswitches and cleanuppads that unwind to siblings to the
322   // terminators that indicate the unwind, used to detect cycles therein.
323   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
324 
325   /// Cache of constants visited in search of ConstantExprs.
326   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
327 
328   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
329   SmallVector<const Function *, 4> DeoptimizeDeclarations;
330 
331   /// Cache of attribute lists verified.
332   SmallPtrSet<const void *, 32> AttributeListsVisited;
333 
334   // Verify that this GlobalValue is only used in this module.
335   // This map is used to avoid visiting uses twice. We can arrive at a user
336   // twice, if they have multiple operands. In particular for very large
337   // constant expressions, we can arrive at a particular user many times.
338   SmallPtrSet<const Value *, 32> GlobalValueVisited;
339 
340   // Keeps track of duplicate function argument debug info.
341   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
342 
343   TBAAVerifier TBAAVerifyHelper;
344 
345   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
346 
347   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
348 
349 public:
350   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
351                     const Module &M)
352       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
353         SawFrameEscape(false), TBAAVerifyHelper(this) {
354     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
355   }
356 
357   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
358 
359   bool verify(const Function &F) {
360     assert(F.getParent() == &M &&
361            "An instance of this class only works with a specific module!");
362 
363     // First ensure the function is well-enough formed to compute dominance
364     // information, and directly compute a dominance tree. We don't rely on the
365     // pass manager to provide this as it isolates us from a potentially
366     // out-of-date dominator tree and makes it significantly more complex to run
367     // this code outside of a pass manager.
368     // FIXME: It's really gross that we have to cast away constness here.
369     if (!F.empty())
370       DT.recalculate(const_cast<Function &>(F));
371 
372     for (const BasicBlock &BB : F) {
373       if (!BB.empty() && BB.back().isTerminator())
374         continue;
375 
376       if (OS) {
377         *OS << "Basic Block in function '" << F.getName()
378             << "' does not have terminator!\n";
379         BB.printAsOperand(*OS, true, MST);
380         *OS << "\n";
381       }
382       return false;
383     }
384 
385     Broken = false;
386     // FIXME: We strip const here because the inst visitor strips const.
387     visit(const_cast<Function &>(F));
388     verifySiblingFuncletUnwinds();
389     InstsInThisBlock.clear();
390     DebugFnArgs.clear();
391     LandingPadResultTy = nullptr;
392     SawFrameEscape = false;
393     SiblingFuncletInfo.clear();
394     verifyNoAliasScopeDecl();
395     NoAliasScopeDecls.clear();
396 
397     return !Broken;
398   }
399 
400   /// Verify the module that this instance of \c Verifier was initialized with.
401   bool verify() {
402     Broken = false;
403 
404     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
405     for (const Function &F : M)
406       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
407         DeoptimizeDeclarations.push_back(&F);
408 
409     // Now that we've visited every function, verify that we never asked to
410     // recover a frame index that wasn't escaped.
411     verifyFrameRecoverIndices();
412     for (const GlobalVariable &GV : M.globals())
413       visitGlobalVariable(GV);
414 
415     for (const GlobalAlias &GA : M.aliases())
416       visitGlobalAlias(GA);
417 
418     for (const GlobalIFunc &GI : M.ifuncs())
419       visitGlobalIFunc(GI);
420 
421     for (const NamedMDNode &NMD : M.named_metadata())
422       visitNamedMDNode(NMD);
423 
424     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
425       visitComdat(SMEC.getValue());
426 
427     visitModuleFlags();
428     visitModuleIdents();
429     visitModuleCommandLines();
430 
431     verifyCompileUnits();
432 
433     verifyDeoptimizeCallingConvs();
434     DISubprogramAttachments.clear();
435     return !Broken;
436   }
437 
438 private:
439   /// Whether a metadata node is allowed to be, or contain, a DILocation.
440   enum class AreDebugLocsAllowed { No, Yes };
441 
442   // Verification methods...
443   void visitGlobalValue(const GlobalValue &GV);
444   void visitGlobalVariable(const GlobalVariable &GV);
445   void visitGlobalAlias(const GlobalAlias &GA);
446   void visitGlobalIFunc(const GlobalIFunc &GI);
447   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
448   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
449                            const GlobalAlias &A, const Constant &C);
450   void visitNamedMDNode(const NamedMDNode &NMD);
451   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
452   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
453   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
454   void visitComdat(const Comdat &C);
455   void visitModuleIdents();
456   void visitModuleCommandLines();
457   void visitModuleFlags();
458   void visitModuleFlag(const MDNode *Op,
459                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
460                        SmallVectorImpl<const MDNode *> &Requirements);
461   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
462   void visitFunction(const Function &F);
463   void visitBasicBlock(BasicBlock &BB);
464   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
465   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
466   void visitProfMetadata(Instruction &I, MDNode *MD);
467   void visitAnnotationMetadata(MDNode *Annotation);
468   void visitAliasScopeMetadata(const MDNode *MD);
469   void visitAliasScopeListMetadata(const MDNode *MD);
470 
471   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
472 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
473 #include "llvm/IR/Metadata.def"
474   void visitDIScope(const DIScope &N);
475   void visitDIVariable(const DIVariable &N);
476   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
477   void visitDITemplateParameter(const DITemplateParameter &N);
478 
479   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
480 
481   // InstVisitor overrides...
482   using InstVisitor<Verifier>::visit;
483   void visit(Instruction &I);
484 
485   void visitTruncInst(TruncInst &I);
486   void visitZExtInst(ZExtInst &I);
487   void visitSExtInst(SExtInst &I);
488   void visitFPTruncInst(FPTruncInst &I);
489   void visitFPExtInst(FPExtInst &I);
490   void visitFPToUIInst(FPToUIInst &I);
491   void visitFPToSIInst(FPToSIInst &I);
492   void visitUIToFPInst(UIToFPInst &I);
493   void visitSIToFPInst(SIToFPInst &I);
494   void visitIntToPtrInst(IntToPtrInst &I);
495   void visitPtrToIntInst(PtrToIntInst &I);
496   void visitBitCastInst(BitCastInst &I);
497   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
498   void visitPHINode(PHINode &PN);
499   void visitCallBase(CallBase &Call);
500   void visitUnaryOperator(UnaryOperator &U);
501   void visitBinaryOperator(BinaryOperator &B);
502   void visitICmpInst(ICmpInst &IC);
503   void visitFCmpInst(FCmpInst &FC);
504   void visitExtractElementInst(ExtractElementInst &EI);
505   void visitInsertElementInst(InsertElementInst &EI);
506   void visitShuffleVectorInst(ShuffleVectorInst &EI);
507   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
508   void visitCallInst(CallInst &CI);
509   void visitInvokeInst(InvokeInst &II);
510   void visitGetElementPtrInst(GetElementPtrInst &GEP);
511   void visitLoadInst(LoadInst &LI);
512   void visitStoreInst(StoreInst &SI);
513   void verifyDominatesUse(Instruction &I, unsigned i);
514   void visitInstruction(Instruction &I);
515   void visitTerminator(Instruction &I);
516   void visitBranchInst(BranchInst &BI);
517   void visitReturnInst(ReturnInst &RI);
518   void visitSwitchInst(SwitchInst &SI);
519   void visitIndirectBrInst(IndirectBrInst &BI);
520   void visitCallBrInst(CallBrInst &CBI);
521   void visitSelectInst(SelectInst &SI);
522   void visitUserOp1(Instruction &I);
523   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
524   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
525   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
526   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
527   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
528   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
529   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
530   void visitFenceInst(FenceInst &FI);
531   void visitAllocaInst(AllocaInst &AI);
532   void visitExtractValueInst(ExtractValueInst &EVI);
533   void visitInsertValueInst(InsertValueInst &IVI);
534   void visitEHPadPredecessors(Instruction &I);
535   void visitLandingPadInst(LandingPadInst &LPI);
536   void visitResumeInst(ResumeInst &RI);
537   void visitCatchPadInst(CatchPadInst &CPI);
538   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
539   void visitCleanupPadInst(CleanupPadInst &CPI);
540   void visitFuncletPadInst(FuncletPadInst &FPI);
541   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
542   void visitCleanupReturnInst(CleanupReturnInst &CRI);
543 
544   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
545   void verifySwiftErrorValue(const Value *SwiftErrorVal);
546   void verifyTailCCMustTailAttrs(AttrBuilder Attrs, StringRef Context);
547   void verifyMustTailCall(CallInst &CI);
548   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
549   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
550   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
551   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
552                                     const Value *V);
553   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
554                            const Value *V, bool IsIntrinsic);
555   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
556   template <typename T>
557   void verifyODRTypeAsScopeOperand(const MDNode &MD, T * = nullptr);
558 
559   void visitConstantExprsRecursively(const Constant *EntryC);
560   void visitConstantExpr(const ConstantExpr *CE);
561   void verifyStatepoint(const CallBase &Call);
562   void verifyFrameRecoverIndices();
563   void verifySiblingFuncletUnwinds();
564 
565   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
566   template <typename ValueOrMetadata>
567   void verifyFragmentExpression(const DIVariable &V,
568                                 DIExpression::FragmentInfo Fragment,
569                                 ValueOrMetadata *Desc);
570   void verifyFnArgs(const DbgVariableIntrinsic &I);
571   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
572 
573   /// Module-level debug info verification...
574   void verifyCompileUnits();
575 
576   /// Module-level verification that all @llvm.experimental.deoptimize
577   /// declarations share the same calling convention.
578   void verifyDeoptimizeCallingConvs();
579 
580   void verifyAttachedCallBundle(const CallBase &Call,
581                                 const OperandBundleUse &BU);
582 
583   /// Verify all-or-nothing property of DIFile source attribute within a CU.
584   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
585 
586   /// Verify the llvm.experimental.noalias.scope.decl declarations
587   void verifyNoAliasScopeDecl();
588 };
589 
590 } // end anonymous namespace
591 
592 /// We know that cond should be true, if not print an error message.
593 #define Assert(C, ...) \
594   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
595 
596 /// We know that a debug info condition should be true, if not print
597 /// an error message.
598 #define AssertDI(C, ...) \
599   do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
600 
601 void Verifier::visit(Instruction &I) {
602   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
603     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
604   InstVisitor<Verifier>::visit(I);
605 }
606 
607 // Helper to recursively iterate over indirect users. By
608 // returning false, the callback can ask to stop recursing
609 // further.
610 static void forEachUser(const Value *User,
611                         SmallPtrSet<const Value *, 32> &Visited,
612                         llvm::function_ref<bool(const Value *)> Callback) {
613   if (!Visited.insert(User).second)
614     return;
615   for (const Value *TheNextUser : User->materialized_users())
616     if (Callback(TheNextUser))
617       forEachUser(TheNextUser, Visited, Callback);
618 }
619 
620 void Verifier::visitGlobalValue(const GlobalValue &GV) {
621   Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
622          "Global is external, but doesn't have external or weak linkage!", &GV);
623 
624   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV))
625     Assert(GO->getAlignment() <= Value::MaximumAlignment,
626            "huge alignment values are unsupported", GO);
627   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
628          "Only global variables can have appending linkage!", &GV);
629 
630   if (GV.hasAppendingLinkage()) {
631     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
632     Assert(GVar && GVar->getValueType()->isArrayTy(),
633            "Only global arrays can have appending linkage!", GVar);
634   }
635 
636   if (GV.isDeclarationForLinker())
637     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
638 
639   if (GV.hasDLLImportStorageClass()) {
640     Assert(!GV.isDSOLocal(),
641            "GlobalValue with DLLImport Storage is dso_local!", &GV);
642 
643     Assert((GV.isDeclaration() &&
644             (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
645                GV.hasAvailableExternallyLinkage(),
646            "Global is marked as dllimport, but not external", &GV);
647   }
648 
649   if (GV.isImplicitDSOLocal())
650     Assert(GV.isDSOLocal(),
651            "GlobalValue with local linkage or non-default "
652            "visibility must be dso_local!",
653            &GV);
654 
655   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
656     if (const Instruction *I = dyn_cast<Instruction>(V)) {
657       if (!I->getParent() || !I->getParent()->getParent())
658         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
659                     I);
660       else if (I->getParent()->getParent()->getParent() != &M)
661         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
662                     I->getParent()->getParent(),
663                     I->getParent()->getParent()->getParent());
664       return false;
665     } else if (const Function *F = dyn_cast<Function>(V)) {
666       if (F->getParent() != &M)
667         CheckFailed("Global is used by function in a different module", &GV, &M,
668                     F, F->getParent());
669       return false;
670     }
671     return true;
672   });
673 }
674 
675 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
676   if (GV.hasInitializer()) {
677     Assert(GV.getInitializer()->getType() == GV.getValueType(),
678            "Global variable initializer type does not match global "
679            "variable type!",
680            &GV);
681     // If the global has common linkage, it must have a zero initializer and
682     // cannot be constant.
683     if (GV.hasCommonLinkage()) {
684       Assert(GV.getInitializer()->isNullValue(),
685              "'common' global must have a zero initializer!", &GV);
686       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
687              &GV);
688       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
689     }
690   }
691 
692   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
693                        GV.getName() == "llvm.global_dtors")) {
694     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
695            "invalid linkage for intrinsic global variable", &GV);
696     // Don't worry about emitting an error for it not being an array,
697     // visitGlobalValue will complain on appending non-array.
698     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
699       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
700       PointerType *FuncPtrTy =
701           FunctionType::get(Type::getVoidTy(Context), false)->
702           getPointerTo(DL.getProgramAddressSpace());
703       Assert(STy &&
704                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
705                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
706                  STy->getTypeAtIndex(1) == FuncPtrTy,
707              "wrong type for intrinsic global variable", &GV);
708       Assert(STy->getNumElements() == 3,
709              "the third field of the element type is mandatory, "
710              "specify i8* null to migrate from the obsoleted 2-field form");
711       Type *ETy = STy->getTypeAtIndex(2);
712       Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
713       Assert(ETy->isPointerTy() &&
714                  cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
715              "wrong type for intrinsic global variable", &GV);
716     }
717   }
718 
719   if (GV.hasName() && (GV.getName() == "llvm.used" ||
720                        GV.getName() == "llvm.compiler.used")) {
721     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
722            "invalid linkage for intrinsic global variable", &GV);
723     Type *GVType = GV.getValueType();
724     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
725       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
726       Assert(PTy, "wrong type for intrinsic global variable", &GV);
727       if (GV.hasInitializer()) {
728         const Constant *Init = GV.getInitializer();
729         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
730         Assert(InitArray, "wrong initalizer for intrinsic global variable",
731                Init);
732         for (Value *Op : InitArray->operands()) {
733           Value *V = Op->stripPointerCasts();
734           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
735                      isa<GlobalAlias>(V),
736                  "invalid llvm.used member", V);
737           Assert(V->hasName(), "members of llvm.used must be named", V);
738         }
739       }
740     }
741   }
742 
743   // Visit any debug info attachments.
744   SmallVector<MDNode *, 1> MDs;
745   GV.getMetadata(LLVMContext::MD_dbg, MDs);
746   for (auto *MD : MDs) {
747     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
748       visitDIGlobalVariableExpression(*GVE);
749     else
750       AssertDI(false, "!dbg attachment of global variable must be a "
751                       "DIGlobalVariableExpression");
752   }
753 
754   // Scalable vectors cannot be global variables, since we don't know
755   // the runtime size. If the global is an array containing scalable vectors,
756   // that will be caught by the isValidElementType methods in StructType or
757   // ArrayType instead.
758   Assert(!isa<ScalableVectorType>(GV.getValueType()),
759          "Globals cannot contain scalable vectors", &GV);
760 
761   if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
762     Assert(!STy->containsScalableVectorType(),
763            "Globals cannot contain scalable vectors", &GV);
764 
765   if (!GV.hasInitializer()) {
766     visitGlobalValue(GV);
767     return;
768   }
769 
770   // Walk any aggregate initializers looking for bitcasts between address spaces
771   visitConstantExprsRecursively(GV.getInitializer());
772 
773   visitGlobalValue(GV);
774 }
775 
776 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
777   SmallPtrSet<const GlobalAlias*, 4> Visited;
778   Visited.insert(&GA);
779   visitAliaseeSubExpr(Visited, GA, C);
780 }
781 
782 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
783                                    const GlobalAlias &GA, const Constant &C) {
784   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
785     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
786            &GA);
787 
788     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
789       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
790 
791       Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
792              &GA);
793     } else {
794       // Only continue verifying subexpressions of GlobalAliases.
795       // Do not recurse into global initializers.
796       return;
797     }
798   }
799 
800   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
801     visitConstantExprsRecursively(CE);
802 
803   for (const Use &U : C.operands()) {
804     Value *V = &*U;
805     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
806       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
807     else if (const auto *C2 = dyn_cast<Constant>(V))
808       visitAliaseeSubExpr(Visited, GA, *C2);
809   }
810 }
811 
812 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
813   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
814          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
815          "weak_odr, or external linkage!",
816          &GA);
817   const Constant *Aliasee = GA.getAliasee();
818   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
819   Assert(GA.getType() == Aliasee->getType(),
820          "Alias and aliasee types should match!", &GA);
821 
822   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
823          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
824 
825   visitAliaseeSubExpr(GA, *Aliasee);
826 
827   visitGlobalValue(GA);
828 }
829 
830 void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
831   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
832   // has a Function
833   const Function *Resolver = GI.getResolverFunction();
834   Assert(Resolver, "IFunc must have a Function resolver", &GI);
835 
836   // Check that the immediate resolver operand (prior to any bitcasts) has the
837   // correct type
838   const Type *ResolverTy = GI.getResolver()->getType();
839   const Type *ResolverFuncTy =
840       GlobalIFunc::getResolverFunctionType(GI.getValueType());
841   Assert(ResolverTy == ResolverFuncTy->getPointerTo(),
842          "IFunc resolver has incorrect type", &GI);
843 }
844 
845 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
846   // There used to be various other llvm.dbg.* nodes, but we don't support
847   // upgrading them and we want to reserve the namespace for future uses.
848   if (NMD.getName().startswith("llvm.dbg."))
849     AssertDI(NMD.getName() == "llvm.dbg.cu",
850              "unrecognized named metadata node in the llvm.dbg namespace",
851              &NMD);
852   for (const MDNode *MD : NMD.operands()) {
853     if (NMD.getName() == "llvm.dbg.cu")
854       AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
855 
856     if (!MD)
857       continue;
858 
859     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
860   }
861 }
862 
863 template <typename T>
864 void Verifier::verifyODRTypeAsScopeOperand(const MDNode &MD, T *) {
865   if (isa<T>(MD)) {
866     if (auto *N = dyn_cast_or_null<DICompositeType>(cast<T>(MD).getScope()))
867       // Of all the supported tags for DICompositeType(see visitDICompositeType)
868       // we know that enum type cannot be a scope.
869       AssertDI(N->getTag() != dwarf::DW_TAG_enumeration_type,
870                "enum type is not a scope; check enum type ODR "
871                "violation",
872                N, &MD);
873   }
874 }
875 
876 void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
877   // Only visit each node once.  Metadata can be mutually recursive, so this
878   // avoids infinite recursion here, as well as being an optimization.
879   if (!MDNodes.insert(&MD).second)
880     return;
881 
882   Assert(&MD.getContext() == &Context,
883          "MDNode context does not match Module context!", &MD);
884 
885   // Makes sure when a scope operand is a ODR type, the ODR type uniquing does
886   // not create invalid debug metadata.
887   // TODO: check that the non-ODR-type scope operand is valid.
888   verifyODRTypeAsScopeOperand<DIType>(MD);
889   verifyODRTypeAsScopeOperand<DILocalScope>(MD);
890 
891   switch (MD.getMetadataID()) {
892   default:
893     llvm_unreachable("Invalid MDNode subclass");
894   case Metadata::MDTupleKind:
895     break;
896 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
897   case Metadata::CLASS##Kind:                                                  \
898     visit##CLASS(cast<CLASS>(MD));                                             \
899     break;
900 #include "llvm/IR/Metadata.def"
901   }
902 
903   for (const Metadata *Op : MD.operands()) {
904     if (!Op)
905       continue;
906     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
907            &MD, Op);
908     AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
909              "DILocation not allowed within this metadata node", &MD, Op);
910     if (auto *N = dyn_cast<MDNode>(Op)) {
911       visitMDNode(*N, AllowLocs);
912       continue;
913     }
914     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
915       visitValueAsMetadata(*V, nullptr);
916       continue;
917     }
918   }
919 
920   // Check these last, so we diagnose problems in operands first.
921   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
922   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
923 }
924 
925 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
926   Assert(MD.getValue(), "Expected valid value", &MD);
927   Assert(!MD.getValue()->getType()->isMetadataTy(),
928          "Unexpected metadata round-trip through values", &MD, MD.getValue());
929 
930   auto *L = dyn_cast<LocalAsMetadata>(&MD);
931   if (!L)
932     return;
933 
934   Assert(F, "function-local metadata used outside a function", L);
935 
936   // If this was an instruction, bb, or argument, verify that it is in the
937   // function that we expect.
938   Function *ActualF = nullptr;
939   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
940     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
941     ActualF = I->getParent()->getParent();
942   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
943     ActualF = BB->getParent();
944   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
945     ActualF = A->getParent();
946   assert(ActualF && "Unimplemented function local metadata case!");
947 
948   Assert(ActualF == F, "function-local metadata used in wrong function", L);
949 }
950 
951 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
952   Metadata *MD = MDV.getMetadata();
953   if (auto *N = dyn_cast<MDNode>(MD)) {
954     visitMDNode(*N, AreDebugLocsAllowed::No);
955     return;
956   }
957 
958   // Only visit each node once.  Metadata can be mutually recursive, so this
959   // avoids infinite recursion here, as well as being an optimization.
960   if (!MDNodes.insert(MD).second)
961     return;
962 
963   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
964     visitValueAsMetadata(*V, F);
965 }
966 
967 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
968 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
969 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
970 
971 void Verifier::visitDILocation(const DILocation &N) {
972   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
973            "location requires a valid scope", &N, N.getRawScope());
974   if (auto *IA = N.getRawInlinedAt())
975     AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
976   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
977     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
978 }
979 
980 void Verifier::visitGenericDINode(const GenericDINode &N) {
981   AssertDI(N.getTag(), "invalid tag", &N);
982 }
983 
984 void Verifier::visitDIScope(const DIScope &N) {
985   if (auto *F = N.getRawFile())
986     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
987 }
988 
989 void Verifier::visitDISubrange(const DISubrange &N) {
990   AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
991   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
992   AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
993                N.getRawUpperBound(),
994            "Subrange must contain count or upperBound", &N);
995   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
996            "Subrange can have any one of count or upperBound", &N);
997   auto *CBound = N.getRawCountNode();
998   AssertDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
999                isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1000            "Count must be signed constant or DIVariable or DIExpression", &N);
1001   auto Count = N.getCount();
1002   AssertDI(!Count || !Count.is<ConstantInt *>() ||
1003                Count.get<ConstantInt *>()->getSExtValue() >= -1,
1004            "invalid subrange count", &N);
1005   auto *LBound = N.getRawLowerBound();
1006   AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1007                isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1008            "LowerBound must be signed constant or DIVariable or DIExpression",
1009            &N);
1010   auto *UBound = N.getRawUpperBound();
1011   AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1012                isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1013            "UpperBound must be signed constant or DIVariable or DIExpression",
1014            &N);
1015   auto *Stride = N.getRawStride();
1016   AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1017                isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1018            "Stride must be signed constant or DIVariable or DIExpression", &N);
1019 }
1020 
1021 void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1022   AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1023   AssertDI(N.getRawCountNode() || N.getRawUpperBound(),
1024            "GenericSubrange must contain count or upperBound", &N);
1025   AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1026            "GenericSubrange can have any one of count or upperBound", &N);
1027   auto *CBound = N.getRawCountNode();
1028   AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1029            "Count must be signed constant or DIVariable or DIExpression", &N);
1030   auto *LBound = N.getRawLowerBound();
1031   AssertDI(LBound, "GenericSubrange must contain lowerBound", &N);
1032   AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1033            "LowerBound must be signed constant or DIVariable or DIExpression",
1034            &N);
1035   auto *UBound = N.getRawUpperBound();
1036   AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1037            "UpperBound must be signed constant or DIVariable or DIExpression",
1038            &N);
1039   auto *Stride = N.getRawStride();
1040   AssertDI(Stride, "GenericSubrange must contain stride", &N);
1041   AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1042            "Stride must be signed constant or DIVariable or DIExpression", &N);
1043 }
1044 
1045 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1046   AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1047 }
1048 
1049 void Verifier::visitDIBasicType(const DIBasicType &N) {
1050   AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
1051                N.getTag() == dwarf::DW_TAG_unspecified_type ||
1052                N.getTag() == dwarf::DW_TAG_string_type,
1053            "invalid tag", &N);
1054 }
1055 
1056 void Verifier::visitDIStringType(const DIStringType &N) {
1057   AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1058   AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,
1059             "has conflicting flags", &N);
1060 }
1061 
1062 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1063   // Common scope checks.
1064   visitDIScope(N);
1065 
1066   AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
1067                N.getTag() == dwarf::DW_TAG_pointer_type ||
1068                N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1069                N.getTag() == dwarf::DW_TAG_reference_type ||
1070                N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1071                N.getTag() == dwarf::DW_TAG_const_type ||
1072                N.getTag() == dwarf::DW_TAG_volatile_type ||
1073                N.getTag() == dwarf::DW_TAG_restrict_type ||
1074                N.getTag() == dwarf::DW_TAG_atomic_type ||
1075                N.getTag() == dwarf::DW_TAG_member ||
1076                N.getTag() == dwarf::DW_TAG_inheritance ||
1077                N.getTag() == dwarf::DW_TAG_friend ||
1078                N.getTag() == dwarf::DW_TAG_set_type,
1079            "invalid tag", &N);
1080   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1081     AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1082              N.getRawExtraData());
1083   }
1084 
1085   if (N.getTag() == dwarf::DW_TAG_set_type) {
1086     if (auto *T = N.getRawBaseType()) {
1087       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1088       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1089       AssertDI(
1090           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1091               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1092                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1093                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1094                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1095                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1096           "invalid set base type", &N, T);
1097     }
1098   }
1099 
1100   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1101   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
1102            N.getRawBaseType());
1103 
1104   if (N.getDWARFAddressSpace()) {
1105     AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1106                  N.getTag() == dwarf::DW_TAG_reference_type ||
1107                  N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1108              "DWARF address space only applies to pointer or reference types",
1109              &N);
1110   }
1111 }
1112 
1113 /// Detect mutually exclusive flags.
1114 static bool hasConflictingReferenceFlags(unsigned Flags) {
1115   return ((Flags & DINode::FlagLValueReference) &&
1116           (Flags & DINode::FlagRValueReference)) ||
1117          ((Flags & DINode::FlagTypePassByValue) &&
1118           (Flags & DINode::FlagTypePassByReference));
1119 }
1120 
1121 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1122   auto *Params = dyn_cast<MDTuple>(&RawParams);
1123   AssertDI(Params, "invalid template params", &N, &RawParams);
1124   for (Metadata *Op : Params->operands()) {
1125     AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1126              &N, Params, Op);
1127   }
1128 }
1129 
1130 void Verifier::visitDICompositeType(const DICompositeType &N) {
1131   // Common scope checks.
1132   visitDIScope(N);
1133 
1134   AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
1135                N.getTag() == dwarf::DW_TAG_structure_type ||
1136                N.getTag() == dwarf::DW_TAG_union_type ||
1137                N.getTag() == dwarf::DW_TAG_enumeration_type ||
1138                N.getTag() == dwarf::DW_TAG_class_type ||
1139                N.getTag() == dwarf::DW_TAG_variant_part ||
1140                N.getTag() == dwarf::DW_TAG_namelist,
1141            "invalid tag", &N);
1142 
1143   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1144   AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
1145            N.getRawBaseType());
1146 
1147   AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1148            "invalid composite elements", &N, N.getRawElements());
1149   AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1150            N.getRawVTableHolder());
1151   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1152            "invalid reference flags", &N);
1153   unsigned DIBlockByRefStruct = 1 << 4;
1154   AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,
1155            "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1156 
1157   if (N.isVector()) {
1158     const DINodeArray Elements = N.getElements();
1159     AssertDI(Elements.size() == 1 &&
1160              Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1161              "invalid vector, expected one element of type subrange", &N);
1162   }
1163 
1164   if (auto *Params = N.getRawTemplateParams())
1165     visitTemplateParams(N, *Params);
1166 
1167   if (auto *D = N.getRawDiscriminator()) {
1168     AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1169              "discriminator can only appear on variant part");
1170   }
1171 
1172   if (N.getRawDataLocation()) {
1173     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1174              "dataLocation can only appear in array type");
1175   }
1176 
1177   if (N.getRawAssociated()) {
1178     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1179              "associated can only appear in array type");
1180   }
1181 
1182   if (N.getRawAllocated()) {
1183     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1184              "allocated can only appear in array type");
1185   }
1186 
1187   if (N.getRawRank()) {
1188     AssertDI(N.getTag() == dwarf::DW_TAG_array_type,
1189              "rank can only appear in array type");
1190   }
1191 }
1192 
1193 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1194   AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1195   if (auto *Types = N.getRawTypeArray()) {
1196     AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1197     for (Metadata *Ty : N.getTypeArray()->operands()) {
1198       AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1199     }
1200   }
1201   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1202            "invalid reference flags", &N);
1203 }
1204 
1205 void Verifier::visitDIFile(const DIFile &N) {
1206   AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1207   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1208   if (Checksum) {
1209     AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1210              "invalid checksum kind", &N);
1211     size_t Size;
1212     switch (Checksum->Kind) {
1213     case DIFile::CSK_MD5:
1214       Size = 32;
1215       break;
1216     case DIFile::CSK_SHA1:
1217       Size = 40;
1218       break;
1219     case DIFile::CSK_SHA256:
1220       Size = 64;
1221       break;
1222     }
1223     AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1224     AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1225              "invalid checksum", &N);
1226   }
1227 }
1228 
1229 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1230   AssertDI(N.isDistinct(), "compile units must be distinct", &N);
1231   AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1232 
1233   // Don't bother verifying the compilation directory or producer string
1234   // as those could be empty.
1235   AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1236            N.getRawFile());
1237   AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1238            N.getFile());
1239 
1240   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1241 
1242   verifySourceDebugInfo(N, *N.getFile());
1243 
1244   AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1245            "invalid emission kind", &N);
1246 
1247   if (auto *Array = N.getRawEnumTypes()) {
1248     AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1249     for (Metadata *Op : N.getEnumTypes()->operands()) {
1250       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1251       AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1252                "invalid enum type", &N, N.getEnumTypes(), Op);
1253     }
1254   }
1255   if (auto *Array = N.getRawRetainedTypes()) {
1256     AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1257     for (Metadata *Op : N.getRetainedTypes()->operands()) {
1258       AssertDI(Op && (isa<DIType>(Op) ||
1259                       (isa<DISubprogram>(Op) &&
1260                        !cast<DISubprogram>(Op)->isDefinition())),
1261                "invalid retained type", &N, Op);
1262     }
1263   }
1264   if (auto *Array = N.getRawGlobalVariables()) {
1265     AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1266     for (Metadata *Op : N.getGlobalVariables()->operands()) {
1267       AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
1268                "invalid global variable ref", &N, Op);
1269     }
1270   }
1271   if (auto *Array = N.getRawImportedEntities()) {
1272     AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1273     for (Metadata *Op : N.getImportedEntities()->operands()) {
1274       AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1275                &N, Op);
1276     }
1277   }
1278   if (auto *Array = N.getRawMacros()) {
1279     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1280     for (Metadata *Op : N.getMacros()->operands()) {
1281       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1282     }
1283   }
1284   CUVisited.insert(&N);
1285 }
1286 
1287 void Verifier::visitDISubprogram(const DISubprogram &N) {
1288   AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1289   AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1290   if (auto *F = N.getRawFile())
1291     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1292   else
1293     AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1294   if (auto *T = N.getRawType())
1295     AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1296   AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1297            N.getRawContainingType());
1298   if (auto *Params = N.getRawTemplateParams())
1299     visitTemplateParams(N, *Params);
1300   if (auto *S = N.getRawDeclaration())
1301     AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1302              "invalid subprogram declaration", &N, S);
1303   if (auto *RawNode = N.getRawRetainedNodes()) {
1304     auto *Node = dyn_cast<MDTuple>(RawNode);
1305     AssertDI(Node, "invalid retained nodes list", &N, RawNode);
1306     for (Metadata *Op : Node->operands()) {
1307       AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
1308                "invalid retained nodes, expected DILocalVariable or DILabel",
1309                &N, Node, Op);
1310     }
1311   }
1312   AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1313            "invalid reference flags", &N);
1314 
1315   auto *Unit = N.getRawUnit();
1316   if (N.isDefinition()) {
1317     // Subprogram definitions (not part of the type hierarchy).
1318     AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1319     AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
1320     AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1321     if (N.getFile())
1322       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
1323   } else {
1324     // Subprogram declarations (part of the type hierarchy).
1325     AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1326   }
1327 
1328   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1329     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1330     AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1331     for (Metadata *Op : ThrownTypes->operands())
1332       AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1333                Op);
1334   }
1335 
1336   if (N.areAllCallsDescribed())
1337     AssertDI(N.isDefinition(),
1338              "DIFlagAllCallsDescribed must be attached to a definition");
1339 }
1340 
1341 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1342   AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1343   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1344            "invalid local scope", &N, N.getRawScope());
1345   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1346     AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1347 }
1348 
1349 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1350   visitDILexicalBlockBase(N);
1351 
1352   AssertDI(N.getLine() || !N.getColumn(),
1353            "cannot have column info without line info", &N);
1354 }
1355 
1356 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1357   visitDILexicalBlockBase(N);
1358 }
1359 
1360 void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1361   AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1362   if (auto *S = N.getRawScope())
1363     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1364   if (auto *S = N.getRawDecl())
1365     AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1366 }
1367 
1368 void Verifier::visitDINamespace(const DINamespace &N) {
1369   AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1370   if (auto *S = N.getRawScope())
1371     AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1372 }
1373 
1374 void Verifier::visitDIMacro(const DIMacro &N) {
1375   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1376                N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1377            "invalid macinfo type", &N);
1378   AssertDI(!N.getName().empty(), "anonymous macro", &N);
1379   if (!N.getValue().empty()) {
1380     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1381   }
1382 }
1383 
1384 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1385   AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1386            "invalid macinfo type", &N);
1387   if (auto *F = N.getRawFile())
1388     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1389 
1390   if (auto *Array = N.getRawElements()) {
1391     AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1392     for (Metadata *Op : N.getElements()->operands()) {
1393       AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1394     }
1395   }
1396 }
1397 
1398 void Verifier::visitDIArgList(const DIArgList &N) {
1399   AssertDI(!N.getNumOperands(),
1400            "DIArgList should have no operands other than a list of "
1401            "ValueAsMetadata",
1402            &N);
1403 }
1404 
1405 void Verifier::visitDIModule(const DIModule &N) {
1406   AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1407   AssertDI(!N.getName().empty(), "anonymous module", &N);
1408 }
1409 
1410 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1411   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1412 }
1413 
1414 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1415   visitDITemplateParameter(N);
1416 
1417   AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1418            &N);
1419 }
1420 
1421 void Verifier::visitDITemplateValueParameter(
1422     const DITemplateValueParameter &N) {
1423   visitDITemplateParameter(N);
1424 
1425   AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1426                N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1427                N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1428            "invalid tag", &N);
1429 }
1430 
1431 void Verifier::visitDIVariable(const DIVariable &N) {
1432   if (auto *S = N.getRawScope())
1433     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1434   if (auto *F = N.getRawFile())
1435     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1436 }
1437 
1438 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1439   // Checks common to all variables.
1440   visitDIVariable(N);
1441 
1442   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1443   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1444   // Assert only if the global variable is not an extern
1445   if (N.isDefinition())
1446     AssertDI(N.getType(), "missing global variable type", &N);
1447   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1448     AssertDI(isa<DIDerivedType>(Member),
1449              "invalid static data member declaration", &N, Member);
1450   }
1451 }
1452 
1453 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1454   // Checks common to all variables.
1455   visitDIVariable(N);
1456 
1457   AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1458   AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1459   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1460            "local variable requires a valid scope", &N, N.getRawScope());
1461   if (auto Ty = N.getType())
1462     AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1463 }
1464 
1465 void Verifier::visitDILabel(const DILabel &N) {
1466   if (auto *S = N.getRawScope())
1467     AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1468   if (auto *F = N.getRawFile())
1469     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1470 
1471   AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1472   AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1473            "label requires a valid scope", &N, N.getRawScope());
1474 }
1475 
1476 void Verifier::visitDIExpression(const DIExpression &N) {
1477   AssertDI(N.isValid(), "invalid expression", &N);
1478 }
1479 
1480 void Verifier::visitDIGlobalVariableExpression(
1481     const DIGlobalVariableExpression &GVE) {
1482   AssertDI(GVE.getVariable(), "missing variable");
1483   if (auto *Var = GVE.getVariable())
1484     visitDIGlobalVariable(*Var);
1485   if (auto *Expr = GVE.getExpression()) {
1486     visitDIExpression(*Expr);
1487     if (auto Fragment = Expr->getFragmentInfo())
1488       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1489   }
1490 }
1491 
1492 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1493   AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1494   if (auto *T = N.getRawType())
1495     AssertDI(isType(T), "invalid type ref", &N, T);
1496   if (auto *F = N.getRawFile())
1497     AssertDI(isa<DIFile>(F), "invalid file", &N, F);
1498 }
1499 
1500 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1501   AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1502                N.getTag() == dwarf::DW_TAG_imported_declaration,
1503            "invalid tag", &N);
1504   if (auto *S = N.getRawScope())
1505     AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1506   AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1507            N.getRawEntity());
1508 }
1509 
1510 void Verifier::visitComdat(const Comdat &C) {
1511   // In COFF the Module is invalid if the GlobalValue has private linkage.
1512   // Entities with private linkage don't have entries in the symbol table.
1513   if (TT.isOSBinFormatCOFF())
1514     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1515       Assert(!GV->hasPrivateLinkage(),
1516              "comdat global value has private linkage", GV);
1517 }
1518 
1519 void Verifier::visitModuleIdents() {
1520   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1521   if (!Idents)
1522     return;
1523 
1524   // llvm.ident takes a list of metadata entry. Each entry has only one string.
1525   // Scan each llvm.ident entry and make sure that this requirement is met.
1526   for (const MDNode *N : Idents->operands()) {
1527     Assert(N->getNumOperands() == 1,
1528            "incorrect number of operands in llvm.ident metadata", N);
1529     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1530            ("invalid value for llvm.ident metadata entry operand"
1531             "(the operand should be a string)"),
1532            N->getOperand(0));
1533   }
1534 }
1535 
1536 void Verifier::visitModuleCommandLines() {
1537   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1538   if (!CommandLines)
1539     return;
1540 
1541   // llvm.commandline takes a list of metadata entry. Each entry has only one
1542   // string. Scan each llvm.commandline entry and make sure that this
1543   // requirement is met.
1544   for (const MDNode *N : CommandLines->operands()) {
1545     Assert(N->getNumOperands() == 1,
1546            "incorrect number of operands in llvm.commandline metadata", N);
1547     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1548            ("invalid value for llvm.commandline metadata entry operand"
1549             "(the operand should be a string)"),
1550            N->getOperand(0));
1551   }
1552 }
1553 
1554 void Verifier::visitModuleFlags() {
1555   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1556   if (!Flags) return;
1557 
1558   // Scan each flag, and track the flags and requirements.
1559   DenseMap<const MDString*, const MDNode*> SeenIDs;
1560   SmallVector<const MDNode*, 16> Requirements;
1561   for (const MDNode *MDN : Flags->operands())
1562     visitModuleFlag(MDN, SeenIDs, Requirements);
1563 
1564   // Validate that the requirements in the module are valid.
1565   for (const MDNode *Requirement : Requirements) {
1566     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1567     const Metadata *ReqValue = Requirement->getOperand(1);
1568 
1569     const MDNode *Op = SeenIDs.lookup(Flag);
1570     if (!Op) {
1571       CheckFailed("invalid requirement on flag, flag is not present in module",
1572                   Flag);
1573       continue;
1574     }
1575 
1576     if (Op->getOperand(2) != ReqValue) {
1577       CheckFailed(("invalid requirement on flag, "
1578                    "flag does not have the required value"),
1579                   Flag);
1580       continue;
1581     }
1582   }
1583 }
1584 
1585 void
1586 Verifier::visitModuleFlag(const MDNode *Op,
1587                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
1588                           SmallVectorImpl<const MDNode *> &Requirements) {
1589   // Each module flag should have three arguments, the merge behavior (a
1590   // constant int), the flag ID (an MDString), and the value.
1591   Assert(Op->getNumOperands() == 3,
1592          "incorrect number of operands in module flag", Op);
1593   Module::ModFlagBehavior MFB;
1594   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1595     Assert(
1596         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1597         "invalid behavior operand in module flag (expected constant integer)",
1598         Op->getOperand(0));
1599     Assert(false,
1600            "invalid behavior operand in module flag (unexpected constant)",
1601            Op->getOperand(0));
1602   }
1603   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1604   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1605          Op->getOperand(1));
1606 
1607   // Check the values for behaviors with additional requirements.
1608   switch (MFB) {
1609   case Module::Error:
1610   case Module::Warning:
1611   case Module::Override:
1612     // These behavior types accept any value.
1613     break;
1614 
1615   case Module::Max: {
1616     Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
1617            "invalid value for 'max' module flag (expected constant integer)",
1618            Op->getOperand(2));
1619     break;
1620   }
1621 
1622   case Module::Require: {
1623     // The value should itself be an MDNode with two operands, a flag ID (an
1624     // MDString), and a value.
1625     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1626     Assert(Value && Value->getNumOperands() == 2,
1627            "invalid value for 'require' module flag (expected metadata pair)",
1628            Op->getOperand(2));
1629     Assert(isa<MDString>(Value->getOperand(0)),
1630            ("invalid value for 'require' module flag "
1631             "(first value operand should be a string)"),
1632            Value->getOperand(0));
1633 
1634     // Append it to the list of requirements, to check once all module flags are
1635     // scanned.
1636     Requirements.push_back(Value);
1637     break;
1638   }
1639 
1640   case Module::Append:
1641   case Module::AppendUnique: {
1642     // These behavior types require the operand be an MDNode.
1643     Assert(isa<MDNode>(Op->getOperand(2)),
1644            "invalid value for 'append'-type module flag "
1645            "(expected a metadata node)",
1646            Op->getOperand(2));
1647     break;
1648   }
1649   }
1650 
1651   // Unless this is a "requires" flag, check the ID is unique.
1652   if (MFB != Module::Require) {
1653     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1654     Assert(Inserted,
1655            "module flag identifiers must be unique (or of 'require' type)", ID);
1656   }
1657 
1658   if (ID->getString() == "wchar_size") {
1659     ConstantInt *Value
1660       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1661     Assert(Value, "wchar_size metadata requires constant integer argument");
1662   }
1663 
1664   if (ID->getString() == "Linker Options") {
1665     // If the llvm.linker.options named metadata exists, we assume that the
1666     // bitcode reader has upgraded the module flag. Otherwise the flag might
1667     // have been created by a client directly.
1668     Assert(M.getNamedMetadata("llvm.linker.options"),
1669            "'Linker Options' named metadata no longer supported");
1670   }
1671 
1672   if (ID->getString() == "SemanticInterposition") {
1673     ConstantInt *Value =
1674         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1675     Assert(Value,
1676            "SemanticInterposition metadata requires constant integer argument");
1677   }
1678 
1679   if (ID->getString() == "CG Profile") {
1680     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1681       visitModuleFlagCGProfileEntry(MDO);
1682   }
1683 }
1684 
1685 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1686   auto CheckFunction = [&](const MDOperand &FuncMDO) {
1687     if (!FuncMDO)
1688       return;
1689     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1690     Assert(F && isa<Function>(F->getValue()->stripPointerCasts()),
1691            "expected a Function or null", FuncMDO);
1692   };
1693   auto Node = dyn_cast_or_null<MDNode>(MDO);
1694   Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
1695   CheckFunction(Node->getOperand(0));
1696   CheckFunction(Node->getOperand(1));
1697   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1698   Assert(Count && Count->getType()->isIntegerTy(),
1699          "expected an integer constant", Node->getOperand(2));
1700 }
1701 
1702 void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
1703   for (Attribute A : Attrs) {
1704 
1705     if (A.isStringAttribute()) {
1706 #define GET_ATTR_NAMES
1707 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1708 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1709   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1710     auto V = A.getValueAsString();                                             \
1711     if (!(V.empty() || V == "true" || V == "false"))                           \
1712       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1713                   "");                                                         \
1714   }
1715 
1716 #include "llvm/IR/Attributes.inc"
1717       continue;
1718     }
1719 
1720     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
1721       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1722                   V);
1723       return;
1724     }
1725   }
1726 }
1727 
1728 // VerifyParameterAttrs - Check the given attributes for an argument or return
1729 // value of the specified type.  The value V is printed in error messages.
1730 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1731                                     const Value *V) {
1732   if (!Attrs.hasAttributes())
1733     return;
1734 
1735   verifyAttributeTypes(Attrs, V);
1736 
1737   for (Attribute Attr : Attrs)
1738     Assert(Attr.isStringAttribute() ||
1739            Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
1740            "Attribute '" + Attr.getAsString() +
1741                "' does not apply to parameters",
1742            V);
1743 
1744   if (Attrs.hasAttribute(Attribute::ImmArg)) {
1745     Assert(Attrs.getNumAttributes() == 1,
1746            "Attribute 'immarg' is incompatible with other attributes", V);
1747   }
1748 
1749   // Check for mutually incompatible attributes.  Only inreg is compatible with
1750   // sret.
1751   unsigned AttrCount = 0;
1752   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1753   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1754   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
1755   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1756                Attrs.hasAttribute(Attribute::InReg);
1757   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1758   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
1759   Assert(AttrCount <= 1,
1760          "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1761          "'byref', and 'sret' are incompatible!",
1762          V);
1763 
1764   Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1765            Attrs.hasAttribute(Attribute::ReadOnly)),
1766          "Attributes "
1767          "'inalloca and readonly' are incompatible!",
1768          V);
1769 
1770   Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
1771            Attrs.hasAttribute(Attribute::Returned)),
1772          "Attributes "
1773          "'sret and returned' are incompatible!",
1774          V);
1775 
1776   Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
1777            Attrs.hasAttribute(Attribute::SExt)),
1778          "Attributes "
1779          "'zeroext and signext' are incompatible!",
1780          V);
1781 
1782   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1783            Attrs.hasAttribute(Attribute::ReadOnly)),
1784          "Attributes "
1785          "'readnone and readonly' are incompatible!",
1786          V);
1787 
1788   Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1789            Attrs.hasAttribute(Attribute::WriteOnly)),
1790          "Attributes "
1791          "'readnone and writeonly' are incompatible!",
1792          V);
1793 
1794   Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1795            Attrs.hasAttribute(Attribute::WriteOnly)),
1796          "Attributes "
1797          "'readonly and writeonly' are incompatible!",
1798          V);
1799 
1800   Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
1801            Attrs.hasAttribute(Attribute::AlwaysInline)),
1802          "Attributes "
1803          "'noinline and alwaysinline' are incompatible!",
1804          V);
1805 
1806   AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1807   for (Attribute Attr : Attrs) {
1808     if (!Attr.isStringAttribute() &&
1809         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1810       CheckFailed("Attribute '" + Attr.getAsString() +
1811                   "' applied to incompatible type!", V);
1812       return;
1813     }
1814   }
1815 
1816   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1817     if (Attrs.hasAttribute(Attribute::ByVal)) {
1818       SmallPtrSet<Type *, 4> Visited;
1819       Assert(Attrs.getByValType()->isSized(&Visited),
1820              "Attribute 'byval' does not support unsized types!", V);
1821     }
1822     if (Attrs.hasAttribute(Attribute::ByRef)) {
1823       SmallPtrSet<Type *, 4> Visited;
1824       Assert(Attrs.getByRefType()->isSized(&Visited),
1825              "Attribute 'byref' does not support unsized types!", V);
1826     }
1827     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1828       SmallPtrSet<Type *, 4> Visited;
1829       Assert(Attrs.getInAllocaType()->isSized(&Visited),
1830              "Attribute 'inalloca' does not support unsized types!", V);
1831     }
1832     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1833       SmallPtrSet<Type *, 4> Visited;
1834       Assert(Attrs.getPreallocatedType()->isSized(&Visited),
1835              "Attribute 'preallocated' does not support unsized types!", V);
1836     }
1837     if (!PTy->isOpaque()) {
1838       if (!isa<PointerType>(PTy->getElementType()))
1839         Assert(!Attrs.hasAttribute(Attribute::SwiftError),
1840                "Attribute 'swifterror' only applies to parameters "
1841                "with pointer to pointer type!",
1842                V);
1843       if (Attrs.hasAttribute(Attribute::ByRef)) {
1844         Assert(Attrs.getByRefType() == PTy->getElementType(),
1845                "Attribute 'byref' type does not match parameter!", V);
1846       }
1847 
1848       if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
1849         Assert(Attrs.getByValType() == PTy->getElementType(),
1850                "Attribute 'byval' type does not match parameter!", V);
1851       }
1852 
1853       if (Attrs.hasAttribute(Attribute::Preallocated)) {
1854         Assert(Attrs.getPreallocatedType() == PTy->getElementType(),
1855                "Attribute 'preallocated' type does not match parameter!", V);
1856       }
1857 
1858       if (Attrs.hasAttribute(Attribute::InAlloca)) {
1859         Assert(Attrs.getInAllocaType() == PTy->getElementType(),
1860                "Attribute 'inalloca' type does not match parameter!", V);
1861       }
1862 
1863       if (Attrs.hasAttribute(Attribute::ElementType)) {
1864         Assert(Attrs.getElementType() == PTy->getElementType(),
1865                "Attribute 'elementtype' type does not match parameter!", V);
1866       }
1867     }
1868   }
1869 }
1870 
1871 void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1872                                             const Value *V) {
1873   if (Attrs.hasFnAttr(Attr)) {
1874     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1875     unsigned N;
1876     if (S.getAsInteger(10, N))
1877       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
1878   }
1879 }
1880 
1881 // Check parameter attributes against a function type.
1882 // The value V is printed in error messages.
1883 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1884                                    const Value *V, bool IsIntrinsic) {
1885   if (Attrs.isEmpty())
1886     return;
1887 
1888   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1889     Assert(Attrs.hasParentContext(Context),
1890            "Attribute list does not match Module context!", &Attrs, V);
1891     for (const auto &AttrSet : Attrs) {
1892       Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
1893              "Attribute set does not match Module context!", &AttrSet, V);
1894       for (const auto &A : AttrSet) {
1895         Assert(A.hasParentContext(Context),
1896                "Attribute does not match Module context!", &A, V);
1897       }
1898     }
1899   }
1900 
1901   bool SawNest = false;
1902   bool SawReturned = false;
1903   bool SawSRet = false;
1904   bool SawSwiftSelf = false;
1905   bool SawSwiftAsync = false;
1906   bool SawSwiftError = false;
1907 
1908   // Verify return value attributes.
1909   AttributeSet RetAttrs = Attrs.getRetAttrs();
1910   for (Attribute RetAttr : RetAttrs)
1911     Assert(RetAttr.isStringAttribute() ||
1912            Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
1913            "Attribute '" + RetAttr.getAsString() +
1914                "' does not apply to function return values",
1915            V);
1916 
1917   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
1918 
1919   // Verify parameter attributes.
1920   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1921     Type *Ty = FT->getParamType(i);
1922     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
1923 
1924     if (!IsIntrinsic) {
1925       Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),
1926              "immarg attribute only applies to intrinsics",V);
1927       Assert(!ArgAttrs.hasAttribute(Attribute::ElementType),
1928              "Attribute 'elementtype' can only be applied to intrinsics.", V);
1929     }
1930 
1931     verifyParameterAttrs(ArgAttrs, Ty, V);
1932 
1933     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
1934       Assert(!SawNest, "More than one parameter has attribute nest!", V);
1935       SawNest = true;
1936     }
1937 
1938     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
1939       Assert(!SawReturned, "More than one parameter has attribute returned!",
1940              V);
1941       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1942              "Incompatible argument and return types for 'returned' attribute",
1943              V);
1944       SawReturned = true;
1945     }
1946 
1947     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
1948       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1949       Assert(i == 0 || i == 1,
1950              "Attribute 'sret' is not on first or second parameter!", V);
1951       SawSRet = true;
1952     }
1953 
1954     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
1955       Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
1956       SawSwiftSelf = true;
1957     }
1958 
1959     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
1960       Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
1961       SawSwiftAsync = true;
1962     }
1963 
1964     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
1965       Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
1966              V);
1967       SawSwiftError = true;
1968     }
1969 
1970     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
1971       Assert(i == FT->getNumParams() - 1,
1972              "inalloca isn't on the last parameter!", V);
1973     }
1974   }
1975 
1976   if (!Attrs.hasFnAttrs())
1977     return;
1978 
1979   verifyAttributeTypes(Attrs.getFnAttrs(), V);
1980   for (Attribute FnAttr : Attrs.getFnAttrs())
1981     Assert(FnAttr.isStringAttribute() ||
1982            Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
1983            "Attribute '" + FnAttr.getAsString() +
1984                "' does not apply to functions!",
1985            V);
1986 
1987   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1988            Attrs.hasFnAttr(Attribute::ReadOnly)),
1989          "Attributes 'readnone and readonly' are incompatible!", V);
1990 
1991   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
1992            Attrs.hasFnAttr(Attribute::WriteOnly)),
1993          "Attributes 'readnone and writeonly' are incompatible!", V);
1994 
1995   Assert(!(Attrs.hasFnAttr(Attribute::ReadOnly) &&
1996            Attrs.hasFnAttr(Attribute::WriteOnly)),
1997          "Attributes 'readonly and writeonly' are incompatible!", V);
1998 
1999   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
2000            Attrs.hasFnAttr(Attribute::InaccessibleMemOrArgMemOnly)),
2001          "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
2002          "incompatible!",
2003          V);
2004 
2005   Assert(!(Attrs.hasFnAttr(Attribute::ReadNone) &&
2006            Attrs.hasFnAttr(Attribute::InaccessibleMemOnly)),
2007          "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
2008 
2009   Assert(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2010            Attrs.hasFnAttr(Attribute::AlwaysInline)),
2011          "Attributes 'noinline and alwaysinline' are incompatible!", V);
2012 
2013   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2014     Assert(Attrs.hasFnAttr(Attribute::NoInline),
2015            "Attribute 'optnone' requires 'noinline'!", V);
2016 
2017     Assert(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2018            "Attributes 'optsize and optnone' are incompatible!", V);
2019 
2020     Assert(!Attrs.hasFnAttr(Attribute::MinSize),
2021            "Attributes 'minsize and optnone' are incompatible!", V);
2022   }
2023 
2024   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2025     const GlobalValue *GV = cast<GlobalValue>(V);
2026     Assert(GV->hasGlobalUnnamedAddr(),
2027            "Attribute 'jumptable' requires 'unnamed_addr'", V);
2028   }
2029 
2030   if (Attrs.hasFnAttr(Attribute::AllocSize)) {
2031     std::pair<unsigned, Optional<unsigned>> Args =
2032         Attrs.getFnAttrs().getAllocSizeArgs();
2033 
2034     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2035       if (ParamNo >= FT->getNumParams()) {
2036         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2037         return false;
2038       }
2039 
2040       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2041         CheckFailed("'allocsize' " + Name +
2042                         " argument must refer to an integer parameter",
2043                     V);
2044         return false;
2045       }
2046 
2047       return true;
2048     };
2049 
2050     if (!CheckParam("element size", Args.first))
2051       return;
2052 
2053     if (Args.second && !CheckParam("number of elements", *Args.second))
2054       return;
2055   }
2056 
2057   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2058     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2059     if (VScaleMin == 0)
2060       CheckFailed("'vscale_range' minimum must be greater than 0", V);
2061 
2062     Optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2063     if (VScaleMax && VScaleMin > VScaleMax)
2064       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2065   }
2066 
2067   if (Attrs.hasFnAttr("frame-pointer")) {
2068     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2069     if (FP != "all" && FP != "non-leaf" && FP != "none")
2070       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2071   }
2072 
2073   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2074   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2075   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2076 }
2077 
2078 void Verifier::verifyFunctionMetadata(
2079     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2080   for (const auto &Pair : MDs) {
2081     if (Pair.first == LLVMContext::MD_prof) {
2082       MDNode *MD = Pair.second;
2083       Assert(MD->getNumOperands() >= 2,
2084              "!prof annotations should have no less than 2 operands", MD);
2085 
2086       // Check first operand.
2087       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
2088              MD);
2089       Assert(isa<MDString>(MD->getOperand(0)),
2090              "expected string with name of the !prof annotation", MD);
2091       MDString *MDS = cast<MDString>(MD->getOperand(0));
2092       StringRef ProfName = MDS->getString();
2093       Assert(ProfName.equals("function_entry_count") ||
2094                  ProfName.equals("synthetic_function_entry_count"),
2095              "first operand should be 'function_entry_count'"
2096              " or 'synthetic_function_entry_count'",
2097              MD);
2098 
2099       // Check second operand.
2100       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
2101              MD);
2102       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
2103              "expected integer argument to function_entry_count", MD);
2104     }
2105   }
2106 }
2107 
2108 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2109   if (!ConstantExprVisited.insert(EntryC).second)
2110     return;
2111 
2112   SmallVector<const Constant *, 16> Stack;
2113   Stack.push_back(EntryC);
2114 
2115   while (!Stack.empty()) {
2116     const Constant *C = Stack.pop_back_val();
2117 
2118     // Check this constant expression.
2119     if (const auto *CE = dyn_cast<ConstantExpr>(C))
2120       visitConstantExpr(CE);
2121 
2122     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2123       // Global Values get visited separately, but we do need to make sure
2124       // that the global value is in the correct module
2125       Assert(GV->getParent() == &M, "Referencing global in another module!",
2126              EntryC, &M, GV, GV->getParent());
2127       continue;
2128     }
2129 
2130     // Visit all sub-expressions.
2131     for (const Use &U : C->operands()) {
2132       const auto *OpC = dyn_cast<Constant>(U);
2133       if (!OpC)
2134         continue;
2135       if (!ConstantExprVisited.insert(OpC).second)
2136         continue;
2137       Stack.push_back(OpC);
2138     }
2139   }
2140 }
2141 
2142 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2143   if (CE->getOpcode() == Instruction::BitCast)
2144     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2145                                  CE->getType()),
2146            "Invalid bitcast", CE);
2147 }
2148 
2149 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2150   // There shouldn't be more attribute sets than there are parameters plus the
2151   // function and return value.
2152   return Attrs.getNumAttrSets() <= Params + 2;
2153 }
2154 
2155 /// Verify that statepoint intrinsic is well formed.
2156 void Verifier::verifyStatepoint(const CallBase &Call) {
2157   assert(Call.getCalledFunction() &&
2158          Call.getCalledFunction()->getIntrinsicID() ==
2159              Intrinsic::experimental_gc_statepoint);
2160 
2161   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
2162              !Call.onlyAccessesArgMemory(),
2163          "gc.statepoint must read and write all memory to preserve "
2164          "reordering restrictions required by safepoint semantics",
2165          Call);
2166 
2167   const int64_t NumPatchBytes =
2168       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2169   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2170   Assert(NumPatchBytes >= 0,
2171          "gc.statepoint number of patchable bytes must be "
2172          "positive",
2173          Call);
2174 
2175   const Value *Target = Call.getArgOperand(2);
2176   auto *PT = dyn_cast<PointerType>(Target->getType());
2177   Assert(PT && PT->getElementType()->isFunctionTy(),
2178          "gc.statepoint callee must be of function pointer type", Call, Target);
2179   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
2180 
2181   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2182   Assert(NumCallArgs >= 0,
2183          "gc.statepoint number of arguments to underlying call "
2184          "must be positive",
2185          Call);
2186   const int NumParams = (int)TargetFuncType->getNumParams();
2187   if (TargetFuncType->isVarArg()) {
2188     Assert(NumCallArgs >= NumParams,
2189            "gc.statepoint mismatch in number of vararg call args", Call);
2190 
2191     // TODO: Remove this limitation
2192     Assert(TargetFuncType->getReturnType()->isVoidTy(),
2193            "gc.statepoint doesn't support wrapping non-void "
2194            "vararg functions yet",
2195            Call);
2196   } else
2197     Assert(NumCallArgs == NumParams,
2198            "gc.statepoint mismatch in number of call args", Call);
2199 
2200   const uint64_t Flags
2201     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2202   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2203          "unknown flag used in gc.statepoint flags argument", Call);
2204 
2205   // Verify that the types of the call parameter arguments match
2206   // the type of the wrapped callee.
2207   AttributeList Attrs = Call.getAttributes();
2208   for (int i = 0; i < NumParams; i++) {
2209     Type *ParamType = TargetFuncType->getParamType(i);
2210     Type *ArgType = Call.getArgOperand(5 + i)->getType();
2211     Assert(ArgType == ParamType,
2212            "gc.statepoint call argument does not match wrapped "
2213            "function type",
2214            Call);
2215 
2216     if (TargetFuncType->isVarArg()) {
2217       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2218       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
2219              "Attribute 'sret' cannot be used for vararg call arguments!",
2220              Call);
2221     }
2222   }
2223 
2224   const int EndCallArgsInx = 4 + NumCallArgs;
2225 
2226   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2227   Assert(isa<ConstantInt>(NumTransitionArgsV),
2228          "gc.statepoint number of transition arguments "
2229          "must be constant integer",
2230          Call);
2231   const int NumTransitionArgs =
2232       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2233   Assert(NumTransitionArgs == 0,
2234          "gc.statepoint w/inline transition bundle is deprecated", Call);
2235   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2236 
2237   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2238   Assert(isa<ConstantInt>(NumDeoptArgsV),
2239          "gc.statepoint number of deoptimization arguments "
2240          "must be constant integer",
2241          Call);
2242   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2243   Assert(NumDeoptArgs == 0,
2244          "gc.statepoint w/inline deopt operands is deprecated", Call);
2245 
2246   const int ExpectedNumArgs = 7 + NumCallArgs;
2247   Assert(ExpectedNumArgs == (int)Call.arg_size(),
2248          "gc.statepoint too many arguments", Call);
2249 
2250   // Check that the only uses of this gc.statepoint are gc.result or
2251   // gc.relocate calls which are tied to this statepoint and thus part
2252   // of the same statepoint sequence
2253   for (const User *U : Call.users()) {
2254     const CallInst *UserCall = dyn_cast<const CallInst>(U);
2255     Assert(UserCall, "illegal use of statepoint token", Call, U);
2256     if (!UserCall)
2257       continue;
2258     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2259            "gc.result or gc.relocate are the only value uses "
2260            "of a gc.statepoint",
2261            Call, U);
2262     if (isa<GCResultInst>(UserCall)) {
2263       Assert(UserCall->getArgOperand(0) == &Call,
2264              "gc.result connected to wrong gc.statepoint", Call, UserCall);
2265     } else if (isa<GCRelocateInst>(Call)) {
2266       Assert(UserCall->getArgOperand(0) == &Call,
2267              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2268     }
2269   }
2270 
2271   // Note: It is legal for a single derived pointer to be listed multiple
2272   // times.  It's non-optimal, but it is legal.  It can also happen after
2273   // insertion if we strip a bitcast away.
2274   // Note: It is really tempting to check that each base is relocated and
2275   // that a derived pointer is never reused as a base pointer.  This turns
2276   // out to be problematic since optimizations run after safepoint insertion
2277   // can recognize equality properties that the insertion logic doesn't know
2278   // about.  See example statepoint.ll in the verifier subdirectory
2279 }
2280 
2281 void Verifier::verifyFrameRecoverIndices() {
2282   for (auto &Counts : FrameEscapeInfo) {
2283     Function *F = Counts.first;
2284     unsigned EscapedObjectCount = Counts.second.first;
2285     unsigned MaxRecoveredIndex = Counts.second.second;
2286     Assert(MaxRecoveredIndex <= EscapedObjectCount,
2287            "all indices passed to llvm.localrecover must be less than the "
2288            "number of arguments passed to llvm.localescape in the parent "
2289            "function",
2290            F);
2291   }
2292 }
2293 
2294 static Instruction *getSuccPad(Instruction *Terminator) {
2295   BasicBlock *UnwindDest;
2296   if (auto *II = dyn_cast<InvokeInst>(Terminator))
2297     UnwindDest = II->getUnwindDest();
2298   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2299     UnwindDest = CSI->getUnwindDest();
2300   else
2301     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2302   return UnwindDest->getFirstNonPHI();
2303 }
2304 
2305 void Verifier::verifySiblingFuncletUnwinds() {
2306   SmallPtrSet<Instruction *, 8> Visited;
2307   SmallPtrSet<Instruction *, 8> Active;
2308   for (const auto &Pair : SiblingFuncletInfo) {
2309     Instruction *PredPad = Pair.first;
2310     if (Visited.count(PredPad))
2311       continue;
2312     Active.insert(PredPad);
2313     Instruction *Terminator = Pair.second;
2314     do {
2315       Instruction *SuccPad = getSuccPad(Terminator);
2316       if (Active.count(SuccPad)) {
2317         // Found a cycle; report error
2318         Instruction *CyclePad = SuccPad;
2319         SmallVector<Instruction *, 8> CycleNodes;
2320         do {
2321           CycleNodes.push_back(CyclePad);
2322           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2323           if (CycleTerminator != CyclePad)
2324             CycleNodes.push_back(CycleTerminator);
2325           CyclePad = getSuccPad(CycleTerminator);
2326         } while (CyclePad != SuccPad);
2327         Assert(false, "EH pads can't handle each other's exceptions",
2328                ArrayRef<Instruction *>(CycleNodes));
2329       }
2330       // Don't re-walk a node we've already checked
2331       if (!Visited.insert(SuccPad).second)
2332         break;
2333       // Walk to this successor if it has a map entry.
2334       PredPad = SuccPad;
2335       auto TermI = SiblingFuncletInfo.find(PredPad);
2336       if (TermI == SiblingFuncletInfo.end())
2337         break;
2338       Terminator = TermI->second;
2339       Active.insert(PredPad);
2340     } while (true);
2341     // Each node only has one successor, so we've walked all the active
2342     // nodes' successors.
2343     Active.clear();
2344   }
2345 }
2346 
2347 // visitFunction - Verify that a function is ok.
2348 //
2349 void Verifier::visitFunction(const Function &F) {
2350   visitGlobalValue(F);
2351 
2352   // Check function arguments.
2353   FunctionType *FT = F.getFunctionType();
2354   unsigned NumArgs = F.arg_size();
2355 
2356   Assert(&Context == &F.getContext(),
2357          "Function context does not match Module context!", &F);
2358 
2359   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2360   Assert(FT->getNumParams() == NumArgs,
2361          "# formal arguments must match # of arguments for function type!", &F,
2362          FT);
2363   Assert(F.getReturnType()->isFirstClassType() ||
2364              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2365          "Functions cannot return aggregate values!", &F);
2366 
2367   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2368          "Invalid struct return type!", &F);
2369 
2370   AttributeList Attrs = F.getAttributes();
2371 
2372   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
2373          "Attribute after last parameter!", &F);
2374 
2375   bool IsIntrinsic = F.isIntrinsic();
2376 
2377   // Check function attributes.
2378   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic);
2379 
2380   // On function declarations/definitions, we do not support the builtin
2381   // attribute. We do not check this in VerifyFunctionAttrs since that is
2382   // checking for Attributes that can/can not ever be on functions.
2383   Assert(!Attrs.hasFnAttr(Attribute::Builtin),
2384          "Attribute 'builtin' can only be applied to a callsite.", &F);
2385 
2386   Assert(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2387          "Attribute 'elementtype' can only be applied to a callsite.", &F);
2388 
2389   // Check that this function meets the restrictions on this calling convention.
2390   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2391   // restrictions can be lifted.
2392   switch (F.getCallingConv()) {
2393   default:
2394   case CallingConv::C:
2395     break;
2396   case CallingConv::X86_INTR: {
2397     Assert(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2398            "Calling convention parameter requires byval", &F);
2399     break;
2400   }
2401   case CallingConv::AMDGPU_KERNEL:
2402   case CallingConv::SPIR_KERNEL:
2403     Assert(F.getReturnType()->isVoidTy(),
2404            "Calling convention requires void return type", &F);
2405     LLVM_FALLTHROUGH;
2406   case CallingConv::AMDGPU_VS:
2407   case CallingConv::AMDGPU_HS:
2408   case CallingConv::AMDGPU_GS:
2409   case CallingConv::AMDGPU_PS:
2410   case CallingConv::AMDGPU_CS:
2411     Assert(!F.hasStructRetAttr(),
2412            "Calling convention does not allow sret", &F);
2413     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2414       const unsigned StackAS = DL.getAllocaAddrSpace();
2415       unsigned i = 0;
2416       for (const Argument &Arg : F.args()) {
2417         Assert(!Attrs.hasParamAttr(i, Attribute::ByVal),
2418                "Calling convention disallows byval", &F);
2419         Assert(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2420                "Calling convention disallows preallocated", &F);
2421         Assert(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2422                "Calling convention disallows inalloca", &F);
2423 
2424         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2425           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2426           // value here.
2427           Assert(Arg.getType()->getPointerAddressSpace() != StackAS,
2428                  "Calling convention disallows stack byref", &F);
2429         }
2430 
2431         ++i;
2432       }
2433     }
2434 
2435     LLVM_FALLTHROUGH;
2436   case CallingConv::Fast:
2437   case CallingConv::Cold:
2438   case CallingConv::Intel_OCL_BI:
2439   case CallingConv::PTX_Kernel:
2440   case CallingConv::PTX_Device:
2441     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
2442                           "perfect forwarding!",
2443            &F);
2444     break;
2445   }
2446 
2447   // Check that the argument values match the function type for this function...
2448   unsigned i = 0;
2449   for (const Argument &Arg : F.args()) {
2450     Assert(Arg.getType() == FT->getParamType(i),
2451            "Argument value does not match function argument type!", &Arg,
2452            FT->getParamType(i));
2453     Assert(Arg.getType()->isFirstClassType(),
2454            "Function arguments must have first-class types!", &Arg);
2455     if (!IsIntrinsic) {
2456       Assert(!Arg.getType()->isMetadataTy(),
2457              "Function takes metadata but isn't an intrinsic", &Arg, &F);
2458       Assert(!Arg.getType()->isTokenTy(),
2459              "Function takes token but isn't an intrinsic", &Arg, &F);
2460       Assert(!Arg.getType()->isX86_AMXTy(),
2461              "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
2462     }
2463 
2464     // Check that swifterror argument is only used by loads and stores.
2465     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2466       verifySwiftErrorValue(&Arg);
2467     }
2468     ++i;
2469   }
2470 
2471   if (!IsIntrinsic) {
2472     Assert(!F.getReturnType()->isTokenTy(),
2473            "Function returns a token but isn't an intrinsic", &F);
2474     Assert(!F.getReturnType()->isX86_AMXTy(),
2475            "Function returns a x86_amx but isn't an intrinsic", &F);
2476   }
2477 
2478   // Get the function metadata attachments.
2479   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2480   F.getAllMetadata(MDs);
2481   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2482   verifyFunctionMetadata(MDs);
2483 
2484   // Check validity of the personality function
2485   if (F.hasPersonalityFn()) {
2486     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2487     if (Per)
2488       Assert(Per->getParent() == F.getParent(),
2489              "Referencing personality function in another module!",
2490              &F, F.getParent(), Per, Per->getParent());
2491   }
2492 
2493   if (F.isMaterializable()) {
2494     // Function has a body somewhere we can't see.
2495     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2496            MDs.empty() ? nullptr : MDs.front().second);
2497   } else if (F.isDeclaration()) {
2498     for (const auto &I : MDs) {
2499       // This is used for call site debug information.
2500       AssertDI(I.first != LLVMContext::MD_dbg ||
2501                    !cast<DISubprogram>(I.second)->isDistinct(),
2502                "function declaration may only have a unique !dbg attachment",
2503                &F);
2504       Assert(I.first != LLVMContext::MD_prof,
2505              "function declaration may not have a !prof attachment", &F);
2506 
2507       // Verify the metadata itself.
2508       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2509     }
2510     Assert(!F.hasPersonalityFn(),
2511            "Function declaration shouldn't have a personality routine", &F);
2512   } else {
2513     // Verify that this function (which has a body) is not named "llvm.*".  It
2514     // is not legal to define intrinsics.
2515     Assert(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
2516 
2517     // Check the entry node
2518     const BasicBlock *Entry = &F.getEntryBlock();
2519     Assert(pred_empty(Entry),
2520            "Entry block to function must not have predecessors!", Entry);
2521 
2522     // The address of the entry block cannot be taken, unless it is dead.
2523     if (Entry->hasAddressTaken()) {
2524       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2525              "blockaddress may not be used with the entry block!", Entry);
2526     }
2527 
2528     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2529     // Visit metadata attachments.
2530     for (const auto &I : MDs) {
2531       // Verify that the attachment is legal.
2532       auto AllowLocs = AreDebugLocsAllowed::No;
2533       switch (I.first) {
2534       default:
2535         break;
2536       case LLVMContext::MD_dbg: {
2537         ++NumDebugAttachments;
2538         AssertDI(NumDebugAttachments == 1,
2539                  "function must have a single !dbg attachment", &F, I.second);
2540         AssertDI(isa<DISubprogram>(I.second),
2541                  "function !dbg attachment must be a subprogram", &F, I.second);
2542         AssertDI(cast<DISubprogram>(I.second)->isDistinct(),
2543                  "function definition may only have a distinct !dbg attachment",
2544                  &F);
2545 
2546         auto *SP = cast<DISubprogram>(I.second);
2547         const Function *&AttachedTo = DISubprogramAttachments[SP];
2548         AssertDI(!AttachedTo || AttachedTo == &F,
2549                  "DISubprogram attached to more than one function", SP, &F);
2550         AttachedTo = &F;
2551         AllowLocs = AreDebugLocsAllowed::Yes;
2552         break;
2553       }
2554       case LLVMContext::MD_prof:
2555         ++NumProfAttachments;
2556         Assert(NumProfAttachments == 1,
2557                "function must have a single !prof attachment", &F, I.second);
2558         break;
2559       }
2560 
2561       // Verify the metadata itself.
2562       visitMDNode(*I.second, AllowLocs);
2563     }
2564   }
2565 
2566   // If this function is actually an intrinsic, verify that it is only used in
2567   // direct call/invokes, never having its "address taken".
2568   // Only do this if the module is materialized, otherwise we don't have all the
2569   // uses.
2570   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2571     const User *U;
2572     if (F.hasAddressTaken(&U, false, true, false,
2573                           /*IgnoreARCAttachedCall=*/true))
2574       Assert(false, "Invalid user of intrinsic instruction!", U);
2575   }
2576 
2577   // Check intrinsics' signatures.
2578   switch (F.getIntrinsicID()) {
2579   case Intrinsic::experimental_gc_get_pointer_base: {
2580     FunctionType *FT = F.getFunctionType();
2581     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2582     Assert(isa<PointerType>(F.getReturnType()),
2583            "gc.get.pointer.base must return a pointer", F);
2584     Assert(FT->getParamType(0) == F.getReturnType(),
2585            "gc.get.pointer.base operand and result must be of the same type",
2586            F);
2587     break;
2588   }
2589   case Intrinsic::experimental_gc_get_pointer_offset: {
2590     FunctionType *FT = F.getFunctionType();
2591     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2592     Assert(isa<PointerType>(FT->getParamType(0)),
2593            "gc.get.pointer.offset operand must be a pointer", F);
2594     Assert(F.getReturnType()->isIntegerTy(),
2595            "gc.get.pointer.offset must return integer", F);
2596     break;
2597   }
2598   }
2599 
2600   auto *N = F.getSubprogram();
2601   HasDebugInfo = (N != nullptr);
2602   if (!HasDebugInfo)
2603     return;
2604 
2605   // Check that all !dbg attachments lead to back to N.
2606   //
2607   // FIXME: Check this incrementally while visiting !dbg attachments.
2608   // FIXME: Only check when N is the canonical subprogram for F.
2609   SmallPtrSet<const MDNode *, 32> Seen;
2610   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2611     // Be careful about using DILocation here since we might be dealing with
2612     // broken code (this is the Verifier after all).
2613     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2614     if (!DL)
2615       return;
2616     if (!Seen.insert(DL).second)
2617       return;
2618 
2619     Metadata *Parent = DL->getRawScope();
2620     AssertDI(Parent && isa<DILocalScope>(Parent),
2621              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
2622              Parent);
2623 
2624     DILocalScope *Scope = DL->getInlinedAtScope();
2625     Assert(Scope, "Failed to find DILocalScope", DL);
2626 
2627     if (!Seen.insert(Scope).second)
2628       return;
2629 
2630     DISubprogram *SP = Scope->getSubprogram();
2631 
2632     // Scope and SP could be the same MDNode and we don't want to skip
2633     // validation in that case
2634     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2635       return;
2636 
2637     AssertDI(SP->describes(&F),
2638              "!dbg attachment points at wrong subprogram for function", N, &F,
2639              &I, DL, Scope, SP);
2640   };
2641   for (auto &BB : F)
2642     for (auto &I : BB) {
2643       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2644       // The llvm.loop annotations also contain two DILocations.
2645       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2646         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2647           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2648       if (BrokenDebugInfo)
2649         return;
2650     }
2651 }
2652 
2653 // verifyBasicBlock - Verify that a basic block is well formed...
2654 //
2655 void Verifier::visitBasicBlock(BasicBlock &BB) {
2656   InstsInThisBlock.clear();
2657 
2658   // Ensure that basic blocks have terminators!
2659   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2660 
2661   // Check constraints that this basic block imposes on all of the PHI nodes in
2662   // it.
2663   if (isa<PHINode>(BB.front())) {
2664     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
2665     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
2666     llvm::sort(Preds);
2667     for (const PHINode &PN : BB.phis()) {
2668       Assert(PN.getNumIncomingValues() == Preds.size(),
2669              "PHINode should have one entry for each predecessor of its "
2670              "parent basic block!",
2671              &PN);
2672 
2673       // Get and sort all incoming values in the PHI node...
2674       Values.clear();
2675       Values.reserve(PN.getNumIncomingValues());
2676       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2677         Values.push_back(
2678             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2679       llvm::sort(Values);
2680 
2681       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2682         // Check to make sure that if there is more than one entry for a
2683         // particular basic block in this PHI node, that the incoming values are
2684         // all identical.
2685         //
2686         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2687                    Values[i].second == Values[i - 1].second,
2688                "PHI node has multiple entries for the same basic block with "
2689                "different incoming values!",
2690                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2691 
2692         // Check to make sure that the predecessors and PHI node entries are
2693         // matched up.
2694         Assert(Values[i].first == Preds[i],
2695                "PHI node entries do not match predecessors!", &PN,
2696                Values[i].first, Preds[i]);
2697       }
2698     }
2699   }
2700 
2701   // Check that all instructions have their parent pointers set up correctly.
2702   for (auto &I : BB)
2703   {
2704     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2705   }
2706 }
2707 
2708 void Verifier::visitTerminator(Instruction &I) {
2709   // Ensure that terminators only exist at the end of the basic block.
2710   Assert(&I == I.getParent()->getTerminator(),
2711          "Terminator found in the middle of a basic block!", I.getParent());
2712   visitInstruction(I);
2713 }
2714 
2715 void Verifier::visitBranchInst(BranchInst &BI) {
2716   if (BI.isConditional()) {
2717     Assert(BI.getCondition()->getType()->isIntegerTy(1),
2718            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2719   }
2720   visitTerminator(BI);
2721 }
2722 
2723 void Verifier::visitReturnInst(ReturnInst &RI) {
2724   Function *F = RI.getParent()->getParent();
2725   unsigned N = RI.getNumOperands();
2726   if (F->getReturnType()->isVoidTy())
2727     Assert(N == 0,
2728            "Found return instr that returns non-void in Function of void "
2729            "return type!",
2730            &RI, F->getReturnType());
2731   else
2732     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2733            "Function return type does not match operand "
2734            "type of return inst!",
2735            &RI, F->getReturnType());
2736 
2737   // Check to make sure that the return value has necessary properties for
2738   // terminators...
2739   visitTerminator(RI);
2740 }
2741 
2742 void Verifier::visitSwitchInst(SwitchInst &SI) {
2743   Assert(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
2744   // Check to make sure that all of the constants in the switch instruction
2745   // have the same type as the switched-on value.
2746   Type *SwitchTy = SI.getCondition()->getType();
2747   SmallPtrSet<ConstantInt*, 32> Constants;
2748   for (auto &Case : SI.cases()) {
2749     Assert(Case.getCaseValue()->getType() == SwitchTy,
2750            "Switch constants must all be same type as switch value!", &SI);
2751     Assert(Constants.insert(Case.getCaseValue()).second,
2752            "Duplicate integer as switch case", &SI, Case.getCaseValue());
2753   }
2754 
2755   visitTerminator(SI);
2756 }
2757 
2758 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2759   Assert(BI.getAddress()->getType()->isPointerTy(),
2760          "Indirectbr operand must have pointer type!", &BI);
2761   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2762     Assert(BI.getDestination(i)->getType()->isLabelTy(),
2763            "Indirectbr destinations must all have pointer type!", &BI);
2764 
2765   visitTerminator(BI);
2766 }
2767 
2768 void Verifier::visitCallBrInst(CallBrInst &CBI) {
2769   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
2770          &CBI);
2771   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2772   Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed");
2773   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
2774     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
2775            "Callbr successors must all have pointer type!", &CBI);
2776   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
2777     Assert(i >= CBI.arg_size() || !isa<BasicBlock>(CBI.getOperand(i)),
2778            "Using an unescaped label as a callbr argument!", &CBI);
2779     if (isa<BasicBlock>(CBI.getOperand(i)))
2780       for (unsigned j = i + 1; j != e; ++j)
2781         Assert(CBI.getOperand(i) != CBI.getOperand(j),
2782                "Duplicate callbr destination!", &CBI);
2783   }
2784   {
2785     SmallPtrSet<BasicBlock *, 4> ArgBBs;
2786     for (Value *V : CBI.args())
2787       if (auto *BA = dyn_cast<BlockAddress>(V))
2788         ArgBBs.insert(BA->getBasicBlock());
2789     for (BasicBlock *BB : CBI.getIndirectDests())
2790       Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI);
2791   }
2792 
2793   visitTerminator(CBI);
2794 }
2795 
2796 void Verifier::visitSelectInst(SelectInst &SI) {
2797   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2798                                          SI.getOperand(2)),
2799          "Invalid operands for select instruction!", &SI);
2800 
2801   Assert(SI.getTrueValue()->getType() == SI.getType(),
2802          "Select values must have same type as select instruction!", &SI);
2803   visitInstruction(SI);
2804 }
2805 
2806 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2807 /// a pass, if any exist, it's an error.
2808 ///
2809 void Verifier::visitUserOp1(Instruction &I) {
2810   Assert(false, "User-defined operators should not live outside of a pass!", &I);
2811 }
2812 
2813 void Verifier::visitTruncInst(TruncInst &I) {
2814   // Get the source and destination types
2815   Type *SrcTy = I.getOperand(0)->getType();
2816   Type *DestTy = I.getType();
2817 
2818   // Get the size of the types in bits, we'll need this later
2819   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2820   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2821 
2822   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2823   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2824   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2825          "trunc source and destination must both be a vector or neither", &I);
2826   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2827 
2828   visitInstruction(I);
2829 }
2830 
2831 void Verifier::visitZExtInst(ZExtInst &I) {
2832   // Get the source and destination types
2833   Type *SrcTy = I.getOperand(0)->getType();
2834   Type *DestTy = I.getType();
2835 
2836   // Get the size of the types in bits, we'll need this later
2837   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2838   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2839   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2840          "zext source and destination must both be a vector or neither", &I);
2841   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2842   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2843 
2844   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2845 
2846   visitInstruction(I);
2847 }
2848 
2849 void Verifier::visitSExtInst(SExtInst &I) {
2850   // Get the source and destination types
2851   Type *SrcTy = I.getOperand(0)->getType();
2852   Type *DestTy = I.getType();
2853 
2854   // Get the size of the types in bits, we'll need this later
2855   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2856   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2857 
2858   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2859   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2860   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2861          "sext source and destination must both be a vector or neither", &I);
2862   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2863 
2864   visitInstruction(I);
2865 }
2866 
2867 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2868   // Get the source and destination types
2869   Type *SrcTy = I.getOperand(0)->getType();
2870   Type *DestTy = I.getType();
2871   // Get the size of the types in bits, we'll need this later
2872   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2873   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2874 
2875   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2876   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2877   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2878          "fptrunc source and destination must both be a vector or neither", &I);
2879   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2880 
2881   visitInstruction(I);
2882 }
2883 
2884 void Verifier::visitFPExtInst(FPExtInst &I) {
2885   // Get the source and destination types
2886   Type *SrcTy = I.getOperand(0)->getType();
2887   Type *DestTy = I.getType();
2888 
2889   // Get the size of the types in bits, we'll need this later
2890   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2891   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2892 
2893   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2894   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2895   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2896          "fpext source and destination must both be a vector or neither", &I);
2897   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2898 
2899   visitInstruction(I);
2900 }
2901 
2902 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2903   // Get the source and destination types
2904   Type *SrcTy = I.getOperand(0)->getType();
2905   Type *DestTy = I.getType();
2906 
2907   bool SrcVec = SrcTy->isVectorTy();
2908   bool DstVec = DestTy->isVectorTy();
2909 
2910   Assert(SrcVec == DstVec,
2911          "UIToFP source and dest must both be vector or scalar", &I);
2912   Assert(SrcTy->isIntOrIntVectorTy(),
2913          "UIToFP source must be integer or integer vector", &I);
2914   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2915          &I);
2916 
2917   if (SrcVec && DstVec)
2918     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2919                cast<VectorType>(DestTy)->getElementCount(),
2920            "UIToFP source and dest vector length mismatch", &I);
2921 
2922   visitInstruction(I);
2923 }
2924 
2925 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2926   // Get the source and destination types
2927   Type *SrcTy = I.getOperand(0)->getType();
2928   Type *DestTy = I.getType();
2929 
2930   bool SrcVec = SrcTy->isVectorTy();
2931   bool DstVec = DestTy->isVectorTy();
2932 
2933   Assert(SrcVec == DstVec,
2934          "SIToFP source and dest must both be vector or scalar", &I);
2935   Assert(SrcTy->isIntOrIntVectorTy(),
2936          "SIToFP source must be integer or integer vector", &I);
2937   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2938          &I);
2939 
2940   if (SrcVec && DstVec)
2941     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2942                cast<VectorType>(DestTy)->getElementCount(),
2943            "SIToFP source and dest vector length mismatch", &I);
2944 
2945   visitInstruction(I);
2946 }
2947 
2948 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2949   // Get the source and destination types
2950   Type *SrcTy = I.getOperand(0)->getType();
2951   Type *DestTy = I.getType();
2952 
2953   bool SrcVec = SrcTy->isVectorTy();
2954   bool DstVec = DestTy->isVectorTy();
2955 
2956   Assert(SrcVec == DstVec,
2957          "FPToUI source and dest must both be vector or scalar", &I);
2958   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2959          &I);
2960   Assert(DestTy->isIntOrIntVectorTy(),
2961          "FPToUI result must be integer or integer vector", &I);
2962 
2963   if (SrcVec && DstVec)
2964     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2965                cast<VectorType>(DestTy)->getElementCount(),
2966            "FPToUI source and dest vector length mismatch", &I);
2967 
2968   visitInstruction(I);
2969 }
2970 
2971 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2972   // Get the source and destination types
2973   Type *SrcTy = I.getOperand(0)->getType();
2974   Type *DestTy = I.getType();
2975 
2976   bool SrcVec = SrcTy->isVectorTy();
2977   bool DstVec = DestTy->isVectorTy();
2978 
2979   Assert(SrcVec == DstVec,
2980          "FPToSI source and dest must both be vector or scalar", &I);
2981   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2982          &I);
2983   Assert(DestTy->isIntOrIntVectorTy(),
2984          "FPToSI result must be integer or integer vector", &I);
2985 
2986   if (SrcVec && DstVec)
2987     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2988                cast<VectorType>(DestTy)->getElementCount(),
2989            "FPToSI source and dest vector length mismatch", &I);
2990 
2991   visitInstruction(I);
2992 }
2993 
2994 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2995   // Get the source and destination types
2996   Type *SrcTy = I.getOperand(0)->getType();
2997   Type *DestTy = I.getType();
2998 
2999   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
3000 
3001   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3002   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3003          &I);
3004 
3005   if (SrcTy->isVectorTy()) {
3006     auto *VSrc = cast<VectorType>(SrcTy);
3007     auto *VDest = cast<VectorType>(DestTy);
3008     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3009            "PtrToInt Vector width mismatch", &I);
3010   }
3011 
3012   visitInstruction(I);
3013 }
3014 
3015 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3016   // Get the source and destination types
3017   Type *SrcTy = I.getOperand(0)->getType();
3018   Type *DestTy = I.getType();
3019 
3020   Assert(SrcTy->isIntOrIntVectorTy(),
3021          "IntToPtr source must be an integral", &I);
3022   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3023 
3024   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3025          &I);
3026   if (SrcTy->isVectorTy()) {
3027     auto *VSrc = cast<VectorType>(SrcTy);
3028     auto *VDest = cast<VectorType>(DestTy);
3029     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3030            "IntToPtr Vector width mismatch", &I);
3031   }
3032   visitInstruction(I);
3033 }
3034 
3035 void Verifier::visitBitCastInst(BitCastInst &I) {
3036   Assert(
3037       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3038       "Invalid bitcast", &I);
3039   visitInstruction(I);
3040 }
3041 
3042 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3043   Type *SrcTy = I.getOperand(0)->getType();
3044   Type *DestTy = I.getType();
3045 
3046   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3047          &I);
3048   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3049          &I);
3050   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
3051          "AddrSpaceCast must be between different address spaces", &I);
3052   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3053     Assert(SrcVTy->getElementCount() ==
3054                cast<VectorType>(DestTy)->getElementCount(),
3055            "AddrSpaceCast vector pointer number of elements mismatch", &I);
3056   visitInstruction(I);
3057 }
3058 
3059 /// visitPHINode - Ensure that a PHI node is well formed.
3060 ///
3061 void Verifier::visitPHINode(PHINode &PN) {
3062   // Ensure that the PHI nodes are all grouped together at the top of the block.
3063   // This can be tested by checking whether the instruction before this is
3064   // either nonexistent (because this is begin()) or is a PHI node.  If not,
3065   // then there is some other instruction before a PHI.
3066   Assert(&PN == &PN.getParent()->front() ||
3067              isa<PHINode>(--BasicBlock::iterator(&PN)),
3068          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3069 
3070   // Check that a PHI doesn't yield a Token.
3071   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3072 
3073   // Check that all of the values of the PHI node have the same type as the
3074   // result, and that the incoming blocks are really basic blocks.
3075   for (Value *IncValue : PN.incoming_values()) {
3076     Assert(PN.getType() == IncValue->getType(),
3077            "PHI node operands are not the same type as the result!", &PN);
3078   }
3079 
3080   // All other PHI node constraints are checked in the visitBasicBlock method.
3081 
3082   visitInstruction(PN);
3083 }
3084 
3085 void Verifier::visitCallBase(CallBase &Call) {
3086   Assert(Call.getCalledOperand()->getType()->isPointerTy(),
3087          "Called function must be a pointer!", Call);
3088   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
3089 
3090   Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
3091          "Called function is not the same type as the call!", Call);
3092 
3093   FunctionType *FTy = Call.getFunctionType();
3094 
3095   // Verify that the correct number of arguments are being passed
3096   if (FTy->isVarArg())
3097     Assert(Call.arg_size() >= FTy->getNumParams(),
3098            "Called function requires more parameters than were provided!",
3099            Call);
3100   else
3101     Assert(Call.arg_size() == FTy->getNumParams(),
3102            "Incorrect number of arguments passed to called function!", Call);
3103 
3104   // Verify that all arguments to the call match the function type.
3105   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3106     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3107            "Call parameter type does not match function signature!",
3108            Call.getArgOperand(i), FTy->getParamType(i), Call);
3109 
3110   AttributeList Attrs = Call.getAttributes();
3111 
3112   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
3113          "Attribute after last parameter!", Call);
3114 
3115   Function *Callee =
3116       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3117   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3118   if (IsIntrinsic)
3119     Assert(Callee->getValueType() == FTy,
3120            "Intrinsic called with incompatible signature", Call);
3121 
3122   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3123     // Don't allow speculatable on call sites, unless the underlying function
3124     // declaration is also speculatable.
3125     Assert(Callee && Callee->isSpeculatable(),
3126            "speculatable attribute may not apply to call sites", Call);
3127   }
3128 
3129   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3130     Assert(Call.getCalledFunction()->getIntrinsicID() ==
3131                Intrinsic::call_preallocated_arg,
3132            "preallocated as a call site attribute can only be on "
3133            "llvm.call.preallocated.arg");
3134   }
3135 
3136   // Verify call attributes.
3137   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
3138 
3139   // Conservatively check the inalloca argument.
3140   // We have a bug if we can find that there is an underlying alloca without
3141   // inalloca.
3142   if (Call.hasInAllocaArgument()) {
3143     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3144     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3145       Assert(AI->isUsedWithInAlloca(),
3146              "inalloca argument for call has mismatched alloca", AI, Call);
3147   }
3148 
3149   // For each argument of the callsite, if it has the swifterror argument,
3150   // make sure the underlying alloca/parameter it comes from has a swifterror as
3151   // well.
3152   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3153     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3154       Value *SwiftErrorArg = Call.getArgOperand(i);
3155       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3156         Assert(AI->isSwiftError(),
3157                "swifterror argument for call has mismatched alloca", AI, Call);
3158         continue;
3159       }
3160       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3161       Assert(ArgI,
3162              "swifterror argument should come from an alloca or parameter",
3163              SwiftErrorArg, Call);
3164       Assert(ArgI->hasSwiftErrorAttr(),
3165              "swifterror argument for call has mismatched parameter", ArgI,
3166              Call);
3167     }
3168 
3169     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3170       // Don't allow immarg on call sites, unless the underlying declaration
3171       // also has the matching immarg.
3172       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3173              "immarg may not apply only to call sites",
3174              Call.getArgOperand(i), Call);
3175     }
3176 
3177     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3178       Value *ArgVal = Call.getArgOperand(i);
3179       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3180              "immarg operand has non-immediate parameter", ArgVal, Call);
3181     }
3182 
3183     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3184       Value *ArgVal = Call.getArgOperand(i);
3185       bool hasOB =
3186           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3187       bool isMustTail = Call.isMustTailCall();
3188       Assert(hasOB != isMustTail,
3189              "preallocated operand either requires a preallocated bundle or "
3190              "the call to be musttail (but not both)",
3191              ArgVal, Call);
3192     }
3193   }
3194 
3195   if (FTy->isVarArg()) {
3196     // FIXME? is 'nest' even legal here?
3197     bool SawNest = false;
3198     bool SawReturned = false;
3199 
3200     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3201       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3202         SawNest = true;
3203       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3204         SawReturned = true;
3205     }
3206 
3207     // Check attributes on the varargs part.
3208     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3209       Type *Ty = Call.getArgOperand(Idx)->getType();
3210       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
3211       verifyParameterAttrs(ArgAttrs, Ty, &Call);
3212 
3213       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3214         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
3215         SawNest = true;
3216       }
3217 
3218       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3219         Assert(!SawReturned, "More than one parameter has attribute returned!",
3220                Call);
3221         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
3222                "Incompatible argument and return types for 'returned' "
3223                "attribute",
3224                Call);
3225         SawReturned = true;
3226       }
3227 
3228       // Statepoint intrinsic is vararg but the wrapped function may be not.
3229       // Allow sret here and check the wrapped function in verifyStatepoint.
3230       if (!Call.getCalledFunction() ||
3231           Call.getCalledFunction()->getIntrinsicID() !=
3232               Intrinsic::experimental_gc_statepoint)
3233         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
3234                "Attribute 'sret' cannot be used for vararg call arguments!",
3235                Call);
3236 
3237       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3238         Assert(Idx == Call.arg_size() - 1,
3239                "inalloca isn't on the last argument!", Call);
3240     }
3241   }
3242 
3243   // Verify that there's no metadata unless it's a direct call to an intrinsic.
3244   if (!IsIntrinsic) {
3245     for (Type *ParamTy : FTy->params()) {
3246       Assert(!ParamTy->isMetadataTy(),
3247              "Function has metadata parameter but isn't an intrinsic", Call);
3248       Assert(!ParamTy->isTokenTy(),
3249              "Function has token parameter but isn't an intrinsic", Call);
3250     }
3251   }
3252 
3253   // Verify that indirect calls don't return tokens.
3254   if (!Call.getCalledFunction()) {
3255     Assert(!FTy->getReturnType()->isTokenTy(),
3256            "Return type cannot be token for indirect call!");
3257     Assert(!FTy->getReturnType()->isX86_AMXTy(),
3258            "Return type cannot be x86_amx for indirect call!");
3259   }
3260 
3261   if (Function *F = Call.getCalledFunction())
3262     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3263       visitIntrinsicCall(ID, Call);
3264 
3265   // Verify that a callsite has at most one "deopt", at most one "funclet", at
3266   // most one "gc-transition", at most one "cfguardtarget",
3267   // and at most one "preallocated" operand bundle.
3268   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3269        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3270        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3271        FoundAttachedCallBundle = false;
3272   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3273     OperandBundleUse BU = Call.getOperandBundleAt(i);
3274     uint32_t Tag = BU.getTagID();
3275     if (Tag == LLVMContext::OB_deopt) {
3276       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
3277       FoundDeoptBundle = true;
3278     } else if (Tag == LLVMContext::OB_gc_transition) {
3279       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
3280              Call);
3281       FoundGCTransitionBundle = true;
3282     } else if (Tag == LLVMContext::OB_funclet) {
3283       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
3284       FoundFuncletBundle = true;
3285       Assert(BU.Inputs.size() == 1,
3286              "Expected exactly one funclet bundle operand", Call);
3287       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
3288              "Funclet bundle operands should correspond to a FuncletPadInst",
3289              Call);
3290     } else if (Tag == LLVMContext::OB_cfguardtarget) {
3291       Assert(!FoundCFGuardTargetBundle,
3292              "Multiple CFGuardTarget operand bundles", Call);
3293       FoundCFGuardTargetBundle = true;
3294       Assert(BU.Inputs.size() == 1,
3295              "Expected exactly one cfguardtarget bundle operand", Call);
3296     } else if (Tag == LLVMContext::OB_preallocated) {
3297       Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3298              Call);
3299       FoundPreallocatedBundle = true;
3300       Assert(BU.Inputs.size() == 1,
3301              "Expected exactly one preallocated bundle operand", Call);
3302       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3303       Assert(Input &&
3304                  Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3305              "\"preallocated\" argument must be a token from "
3306              "llvm.call.preallocated.setup",
3307              Call);
3308     } else if (Tag == LLVMContext::OB_gc_live) {
3309       Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",
3310              Call);
3311       FoundGCLiveBundle = true;
3312     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
3313       Assert(!FoundAttachedCallBundle,
3314              "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3315       FoundAttachedCallBundle = true;
3316       verifyAttachedCallBundle(Call, BU);
3317     }
3318   }
3319 
3320   // Verify that each inlinable callsite of a debug-info-bearing function in a
3321   // debug-info-bearing function has a debug location attached to it. Failure to
3322   // do so causes assertion failures when the inliner sets up inline scope info.
3323   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3324       Call.getCalledFunction()->getSubprogram())
3325     AssertDI(Call.getDebugLoc(),
3326              "inlinable function call in a function with "
3327              "debug info must have a !dbg location",
3328              Call);
3329 
3330   visitInstruction(Call);
3331 }
3332 
3333 void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs,
3334                                          StringRef Context) {
3335   Assert(!Attrs.contains(Attribute::InAlloca),
3336          Twine("inalloca attribute not allowed in ") + Context);
3337   Assert(!Attrs.contains(Attribute::InReg),
3338          Twine("inreg attribute not allowed in ") + Context);
3339   Assert(!Attrs.contains(Attribute::SwiftError),
3340          Twine("swifterror attribute not allowed in ") + Context);
3341   Assert(!Attrs.contains(Attribute::Preallocated),
3342          Twine("preallocated attribute not allowed in ") + Context);
3343   Assert(!Attrs.contains(Attribute::ByRef),
3344          Twine("byref attribute not allowed in ") + Context);
3345 }
3346 
3347 /// Two types are "congruent" if they are identical, or if they are both pointer
3348 /// types with different pointee types and the same address space.
3349 static bool isTypeCongruent(Type *L, Type *R) {
3350   if (L == R)
3351     return true;
3352   PointerType *PL = dyn_cast<PointerType>(L);
3353   PointerType *PR = dyn_cast<PointerType>(R);
3354   if (!PL || !PR)
3355     return false;
3356   return PL->getAddressSpace() == PR->getAddressSpace();
3357 }
3358 
3359 static AttrBuilder getParameterABIAttributes(unsigned I, AttributeList Attrs) {
3360   static const Attribute::AttrKind ABIAttrs[] = {
3361       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3362       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3363       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3364       Attribute::ByRef};
3365   AttrBuilder Copy;
3366   for (auto AK : ABIAttrs) {
3367     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3368     if (Attr.isValid())
3369       Copy.addAttribute(Attr);
3370   }
3371 
3372   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3373   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3374       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3375        Attrs.hasParamAttr(I, Attribute::ByRef)))
3376     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3377   return Copy;
3378 }
3379 
3380 void Verifier::verifyMustTailCall(CallInst &CI) {
3381   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
3382 
3383   Function *F = CI.getParent()->getParent();
3384   FunctionType *CallerTy = F->getFunctionType();
3385   FunctionType *CalleeTy = CI.getFunctionType();
3386   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3387          "cannot guarantee tail call due to mismatched varargs", &CI);
3388   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
3389          "cannot guarantee tail call due to mismatched return types", &CI);
3390 
3391   // - The calling conventions of the caller and callee must match.
3392   Assert(F->getCallingConv() == CI.getCallingConv(),
3393          "cannot guarantee tail call due to mismatched calling conv", &CI);
3394 
3395   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3396   //   or a pointer bitcast followed by a ret instruction.
3397   // - The ret instruction must return the (possibly bitcasted) value
3398   //   produced by the call or void.
3399   Value *RetVal = &CI;
3400   Instruction *Next = CI.getNextNode();
3401 
3402   // Handle the optional bitcast.
3403   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3404     Assert(BI->getOperand(0) == RetVal,
3405            "bitcast following musttail call must use the call", BI);
3406     RetVal = BI;
3407     Next = BI->getNextNode();
3408   }
3409 
3410   // Check the return.
3411   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3412   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
3413          &CI);
3414   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3415              isa<UndefValue>(Ret->getReturnValue()),
3416          "musttail call result must be returned", Ret);
3417 
3418   AttributeList CallerAttrs = F->getAttributes();
3419   AttributeList CalleeAttrs = CI.getAttributes();
3420   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3421       CI.getCallingConv() == CallingConv::Tail) {
3422     StringRef CCName =
3423         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3424 
3425     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3426     //   are allowed in swifttailcc call
3427     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3428       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3429       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3430       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3431     }
3432     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3433       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3434       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3435       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3436     }
3437     // - Varargs functions are not allowed
3438     Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3439                                       " tail call for varargs function");
3440     return;
3441   }
3442 
3443   // - The caller and callee prototypes must match.  Pointer types of
3444   //   parameters or return types may differ in pointee type, but not
3445   //   address space.
3446   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3447     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3448            "cannot guarantee tail call due to mismatched parameter counts",
3449            &CI);
3450     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3451       Assert(
3452           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3453           "cannot guarantee tail call due to mismatched parameter types", &CI);
3454     }
3455   }
3456 
3457   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3458   //   returned, preallocated, and inalloca, must match.
3459   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3460     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3461     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3462     Assert(CallerABIAttrs == CalleeABIAttrs,
3463            "cannot guarantee tail call due to mismatched ABI impacting "
3464            "function attributes",
3465            &CI, CI.getOperand(I));
3466   }
3467 }
3468 
3469 void Verifier::visitCallInst(CallInst &CI) {
3470   visitCallBase(CI);
3471 
3472   if (CI.isMustTailCall())
3473     verifyMustTailCall(CI);
3474 }
3475 
3476 void Verifier::visitInvokeInst(InvokeInst &II) {
3477   visitCallBase(II);
3478 
3479   // Verify that the first non-PHI instruction of the unwind destination is an
3480   // exception handling instruction.
3481   Assert(
3482       II.getUnwindDest()->isEHPad(),
3483       "The unwind destination does not have an exception handling instruction!",
3484       &II);
3485 
3486   visitTerminator(II);
3487 }
3488 
3489 /// visitUnaryOperator - Check the argument to the unary operator.
3490 ///
3491 void Verifier::visitUnaryOperator(UnaryOperator &U) {
3492   Assert(U.getType() == U.getOperand(0)->getType(),
3493          "Unary operators must have same type for"
3494          "operands and result!",
3495          &U);
3496 
3497   switch (U.getOpcode()) {
3498   // Check that floating-point arithmetic operators are only used with
3499   // floating-point operands.
3500   case Instruction::FNeg:
3501     Assert(U.getType()->isFPOrFPVectorTy(),
3502            "FNeg operator only works with float types!", &U);
3503     break;
3504   default:
3505     llvm_unreachable("Unknown UnaryOperator opcode!");
3506   }
3507 
3508   visitInstruction(U);
3509 }
3510 
3511 /// visitBinaryOperator - Check that both arguments to the binary operator are
3512 /// of the same type!
3513 ///
3514 void Verifier::visitBinaryOperator(BinaryOperator &B) {
3515   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3516          "Both operands to a binary operator are not of the same type!", &B);
3517 
3518   switch (B.getOpcode()) {
3519   // Check that integer arithmetic operators are only used with
3520   // integral operands.
3521   case Instruction::Add:
3522   case Instruction::Sub:
3523   case Instruction::Mul:
3524   case Instruction::SDiv:
3525   case Instruction::UDiv:
3526   case Instruction::SRem:
3527   case Instruction::URem:
3528     Assert(B.getType()->isIntOrIntVectorTy(),
3529            "Integer arithmetic operators only work with integral types!", &B);
3530     Assert(B.getType() == B.getOperand(0)->getType(),
3531            "Integer arithmetic operators must have same type "
3532            "for operands and result!",
3533            &B);
3534     break;
3535   // Check that floating-point arithmetic operators are only used with
3536   // floating-point operands.
3537   case Instruction::FAdd:
3538   case Instruction::FSub:
3539   case Instruction::FMul:
3540   case Instruction::FDiv:
3541   case Instruction::FRem:
3542     Assert(B.getType()->isFPOrFPVectorTy(),
3543            "Floating-point arithmetic operators only work with "
3544            "floating-point types!",
3545            &B);
3546     Assert(B.getType() == B.getOperand(0)->getType(),
3547            "Floating-point arithmetic operators must have same type "
3548            "for operands and result!",
3549            &B);
3550     break;
3551   // Check that logical operators are only used with integral operands.
3552   case Instruction::And:
3553   case Instruction::Or:
3554   case Instruction::Xor:
3555     Assert(B.getType()->isIntOrIntVectorTy(),
3556            "Logical operators only work with integral types!", &B);
3557     Assert(B.getType() == B.getOperand(0)->getType(),
3558            "Logical operators must have same type for operands and result!",
3559            &B);
3560     break;
3561   case Instruction::Shl:
3562   case Instruction::LShr:
3563   case Instruction::AShr:
3564     Assert(B.getType()->isIntOrIntVectorTy(),
3565            "Shifts only work with integral types!", &B);
3566     Assert(B.getType() == B.getOperand(0)->getType(),
3567            "Shift return type must be same as operands!", &B);
3568     break;
3569   default:
3570     llvm_unreachable("Unknown BinaryOperator opcode!");
3571   }
3572 
3573   visitInstruction(B);
3574 }
3575 
3576 void Verifier::visitICmpInst(ICmpInst &IC) {
3577   // Check that the operands are the same type
3578   Type *Op0Ty = IC.getOperand(0)->getType();
3579   Type *Op1Ty = IC.getOperand(1)->getType();
3580   Assert(Op0Ty == Op1Ty,
3581          "Both operands to ICmp instruction are not of the same type!", &IC);
3582   // Check that the operands are the right type
3583   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3584          "Invalid operand types for ICmp instruction", &IC);
3585   // Check that the predicate is valid.
3586   Assert(IC.isIntPredicate(),
3587          "Invalid predicate in ICmp instruction!", &IC);
3588 
3589   visitInstruction(IC);
3590 }
3591 
3592 void Verifier::visitFCmpInst(FCmpInst &FC) {
3593   // Check that the operands are the same type
3594   Type *Op0Ty = FC.getOperand(0)->getType();
3595   Type *Op1Ty = FC.getOperand(1)->getType();
3596   Assert(Op0Ty == Op1Ty,
3597          "Both operands to FCmp instruction are not of the same type!", &FC);
3598   // Check that the operands are the right type
3599   Assert(Op0Ty->isFPOrFPVectorTy(),
3600          "Invalid operand types for FCmp instruction", &FC);
3601   // Check that the predicate is valid.
3602   Assert(FC.isFPPredicate(),
3603          "Invalid predicate in FCmp instruction!", &FC);
3604 
3605   visitInstruction(FC);
3606 }
3607 
3608 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3609   Assert(
3610       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
3611       "Invalid extractelement operands!", &EI);
3612   visitInstruction(EI);
3613 }
3614 
3615 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3616   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
3617                                             IE.getOperand(2)),
3618          "Invalid insertelement operands!", &IE);
3619   visitInstruction(IE);
3620 }
3621 
3622 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3623   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
3624                                             SV.getShuffleMask()),
3625          "Invalid shufflevector operands!", &SV);
3626   visitInstruction(SV);
3627 }
3628 
3629 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3630   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3631 
3632   Assert(isa<PointerType>(TargetTy),
3633          "GEP base pointer is not a vector or a vector of pointers", &GEP);
3634   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3635 
3636   SmallVector<Value *, 16> Idxs(GEP.indices());
3637   Assert(all_of(
3638       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
3639       "GEP indexes must be integers", &GEP);
3640   Type *ElTy =
3641       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3642   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3643 
3644   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
3645              GEP.getResultElementType() == ElTy,
3646          "GEP is not of right type for indices!", &GEP, ElTy);
3647 
3648   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3649     // Additional checks for vector GEPs.
3650     ElementCount GEPWidth = GEPVTy->getElementCount();
3651     if (GEP.getPointerOperandType()->isVectorTy())
3652       Assert(
3653           GEPWidth ==
3654               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
3655           "Vector GEP result width doesn't match operand's", &GEP);
3656     for (Value *Idx : Idxs) {
3657       Type *IndexTy = Idx->getType();
3658       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3659         ElementCount IndexWidth = IndexVTy->getElementCount();
3660         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3661       }
3662       Assert(IndexTy->isIntOrIntVectorTy(),
3663              "All GEP indices should be of integer type");
3664     }
3665   }
3666 
3667   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3668     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
3669            "GEP address space doesn't match type", &GEP);
3670   }
3671 
3672   visitInstruction(GEP);
3673 }
3674 
3675 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3676   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3677 }
3678 
3679 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3680   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3681          "precondition violation");
3682 
3683   unsigned NumOperands = Range->getNumOperands();
3684   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
3685   unsigned NumRanges = NumOperands / 2;
3686   Assert(NumRanges >= 1, "It should have at least one range!", Range);
3687 
3688   ConstantRange LastRange(1, true); // Dummy initial value
3689   for (unsigned i = 0; i < NumRanges; ++i) {
3690     ConstantInt *Low =
3691         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3692     Assert(Low, "The lower limit must be an integer!", Low);
3693     ConstantInt *High =
3694         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3695     Assert(High, "The upper limit must be an integer!", High);
3696     Assert(High->getType() == Low->getType() && High->getType() == Ty,
3697            "Range types must match instruction type!", &I);
3698 
3699     APInt HighV = High->getValue();
3700     APInt LowV = Low->getValue();
3701     ConstantRange CurRange(LowV, HighV);
3702     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3703            "Range must not be empty!", Range);
3704     if (i != 0) {
3705       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3706              "Intervals are overlapping", Range);
3707       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3708              Range);
3709       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3710              Range);
3711     }
3712     LastRange = ConstantRange(LowV, HighV);
3713   }
3714   if (NumRanges > 2) {
3715     APInt FirstLow =
3716         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3717     APInt FirstHigh =
3718         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3719     ConstantRange FirstRange(FirstLow, FirstHigh);
3720     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3721            "Intervals are overlapping", Range);
3722     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3723            Range);
3724   }
3725 }
3726 
3727 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3728   unsigned Size = DL.getTypeSizeInBits(Ty);
3729   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3730   Assert(!(Size & (Size - 1)),
3731          "atomic memory access' operand must have a power-of-two size", Ty, I);
3732 }
3733 
3734 void Verifier::visitLoadInst(LoadInst &LI) {
3735   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
3736   Assert(PTy, "Load operand must be a pointer.", &LI);
3737   Type *ElTy = LI.getType();
3738   Assert(LI.getAlignment() <= Value::MaximumAlignment,
3739          "huge alignment values are unsupported", &LI);
3740   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
3741   if (LI.isAtomic()) {
3742     Assert(LI.getOrdering() != AtomicOrdering::Release &&
3743                LI.getOrdering() != AtomicOrdering::AcquireRelease,
3744            "Load cannot have Release ordering", &LI);
3745     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3746            "atomic load operand must have integer, pointer, or floating point "
3747            "type!",
3748            ElTy, &LI);
3749     checkAtomicMemAccessSize(ElTy, &LI);
3750   } else {
3751     Assert(LI.getSyncScopeID() == SyncScope::System,
3752            "Non-atomic load cannot have SynchronizationScope specified", &LI);
3753   }
3754 
3755   visitInstruction(LI);
3756 }
3757 
3758 void Verifier::visitStoreInst(StoreInst &SI) {
3759   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
3760   Assert(PTy, "Store operand must be a pointer.", &SI);
3761   Type *ElTy = SI.getOperand(0)->getType();
3762   Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
3763          "Stored value type does not match pointer operand type!", &SI, ElTy);
3764   Assert(SI.getAlignment() <= Value::MaximumAlignment,
3765          "huge alignment values are unsupported", &SI);
3766   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
3767   if (SI.isAtomic()) {
3768     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
3769                SI.getOrdering() != AtomicOrdering::AcquireRelease,
3770            "Store cannot have Acquire ordering", &SI);
3771     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3772            "atomic store operand must have integer, pointer, or floating point "
3773            "type!",
3774            ElTy, &SI);
3775     checkAtomicMemAccessSize(ElTy, &SI);
3776   } else {
3777     Assert(SI.getSyncScopeID() == SyncScope::System,
3778            "Non-atomic store cannot have SynchronizationScope specified", &SI);
3779   }
3780   visitInstruction(SI);
3781 }
3782 
3783 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
3784 void Verifier::verifySwiftErrorCall(CallBase &Call,
3785                                     const Value *SwiftErrorVal) {
3786   for (const auto &I : llvm::enumerate(Call.args())) {
3787     if (I.value() == SwiftErrorVal) {
3788       Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError),
3789              "swifterror value when used in a callsite should be marked "
3790              "with swifterror attribute",
3791              SwiftErrorVal, Call);
3792     }
3793   }
3794 }
3795 
3796 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3797   // Check that swifterror value is only used by loads, stores, or as
3798   // a swifterror argument.
3799   for (const User *U : SwiftErrorVal->users()) {
3800     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3801            isa<InvokeInst>(U),
3802            "swifterror value can only be loaded and stored from, or "
3803            "as a swifterror argument!",
3804            SwiftErrorVal, U);
3805     // If it is used by a store, check it is the second operand.
3806     if (auto StoreI = dyn_cast<StoreInst>(U))
3807       Assert(StoreI->getOperand(1) == SwiftErrorVal,
3808              "swifterror value should be the second operand when used "
3809              "by stores", SwiftErrorVal, U);
3810     if (auto *Call = dyn_cast<CallBase>(U))
3811       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
3812   }
3813 }
3814 
3815 void Verifier::visitAllocaInst(AllocaInst &AI) {
3816   SmallPtrSet<Type*, 4> Visited;
3817   Assert(AI.getAllocatedType()->isSized(&Visited),
3818          "Cannot allocate unsized type", &AI);
3819   Assert(AI.getArraySize()->getType()->isIntegerTy(),
3820          "Alloca array size must have integer type", &AI);
3821   Assert(AI.getAlignment() <= Value::MaximumAlignment,
3822          "huge alignment values are unsupported", &AI);
3823 
3824   if (AI.isSwiftError()) {
3825     verifySwiftErrorValue(&AI);
3826   }
3827 
3828   visitInstruction(AI);
3829 }
3830 
3831 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3832   Type *ElTy = CXI.getOperand(1)->getType();
3833   Assert(ElTy->isIntOrPtrTy(),
3834          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3835   checkAtomicMemAccessSize(ElTy, &CXI);
3836   visitInstruction(CXI);
3837 }
3838 
3839 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
3840   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
3841          "atomicrmw instructions cannot be unordered.", &RMWI);
3842   auto Op = RMWI.getOperation();
3843   Type *ElTy = RMWI.getOperand(1)->getType();
3844   if (Op == AtomicRMWInst::Xchg) {
3845     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
3846            AtomicRMWInst::getOperationName(Op) +
3847            " operand must have integer or floating point type!",
3848            &RMWI, ElTy);
3849   } else if (AtomicRMWInst::isFPOperation(Op)) {
3850     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
3851            AtomicRMWInst::getOperationName(Op) +
3852            " operand must have floating point type!",
3853            &RMWI, ElTy);
3854   } else {
3855     Assert(ElTy->isIntegerTy(), "atomicrmw " +
3856            AtomicRMWInst::getOperationName(Op) +
3857            " operand must have integer type!",
3858            &RMWI, ElTy);
3859   }
3860   checkAtomicMemAccessSize(ElTy, &RMWI);
3861   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
3862          "Invalid binary operation!", &RMWI);
3863   visitInstruction(RMWI);
3864 }
3865 
3866 void Verifier::visitFenceInst(FenceInst &FI) {
3867   const AtomicOrdering Ordering = FI.getOrdering();
3868   Assert(Ordering == AtomicOrdering::Acquire ||
3869              Ordering == AtomicOrdering::Release ||
3870              Ordering == AtomicOrdering::AcquireRelease ||
3871              Ordering == AtomicOrdering::SequentiallyConsistent,
3872          "fence instructions may only have acquire, release, acq_rel, or "
3873          "seq_cst ordering.",
3874          &FI);
3875   visitInstruction(FI);
3876 }
3877 
3878 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
3879   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
3880                                           EVI.getIndices()) == EVI.getType(),
3881          "Invalid ExtractValueInst operands!", &EVI);
3882 
3883   visitInstruction(EVI);
3884 }
3885 
3886 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
3887   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
3888                                           IVI.getIndices()) ==
3889              IVI.getOperand(1)->getType(),
3890          "Invalid InsertValueInst operands!", &IVI);
3891 
3892   visitInstruction(IVI);
3893 }
3894 
3895 static Value *getParentPad(Value *EHPad) {
3896   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3897     return FPI->getParentPad();
3898 
3899   return cast<CatchSwitchInst>(EHPad)->getParentPad();
3900 }
3901 
3902 void Verifier::visitEHPadPredecessors(Instruction &I) {
3903   assert(I.isEHPad());
3904 
3905   BasicBlock *BB = I.getParent();
3906   Function *F = BB->getParent();
3907 
3908   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3909 
3910   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3911     // The landingpad instruction defines its parent as a landing pad block. The
3912     // landing pad block may be branched to only by the unwind edge of an
3913     // invoke.
3914     for (BasicBlock *PredBB : predecessors(BB)) {
3915       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3916       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3917              "Block containing LandingPadInst must be jumped to "
3918              "only by the unwind edge of an invoke.",
3919              LPI);
3920     }
3921     return;
3922   }
3923   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3924     if (!pred_empty(BB))
3925       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3926              "Block containg CatchPadInst must be jumped to "
3927              "only by its catchswitch.",
3928              CPI);
3929     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3930            "Catchswitch cannot unwind to one of its catchpads",
3931            CPI->getCatchSwitch(), CPI);
3932     return;
3933   }
3934 
3935   // Verify that each pred has a legal terminator with a legal to/from EH
3936   // pad relationship.
3937   Instruction *ToPad = &I;
3938   Value *ToPadParent = getParentPad(ToPad);
3939   for (BasicBlock *PredBB : predecessors(BB)) {
3940     Instruction *TI = PredBB->getTerminator();
3941     Value *FromPad;
3942     if (auto *II = dyn_cast<InvokeInst>(TI)) {
3943       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
3944              "EH pad must be jumped to via an unwind edge", ToPad, II);
3945       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3946         FromPad = Bundle->Inputs[0];
3947       else
3948         FromPad = ConstantTokenNone::get(II->getContext());
3949     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3950       FromPad = CRI->getOperand(0);
3951       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3952     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3953       FromPad = CSI;
3954     } else {
3955       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3956     }
3957 
3958     // The edge may exit from zero or more nested pads.
3959     SmallSet<Value *, 8> Seen;
3960     for (;; FromPad = getParentPad(FromPad)) {
3961       Assert(FromPad != ToPad,
3962              "EH pad cannot handle exceptions raised within it", FromPad, TI);
3963       if (FromPad == ToPadParent) {
3964         // This is a legal unwind edge.
3965         break;
3966       }
3967       Assert(!isa<ConstantTokenNone>(FromPad),
3968              "A single unwind edge may only enter one EH pad", TI);
3969       Assert(Seen.insert(FromPad).second,
3970              "EH pad jumps through a cycle of pads", FromPad);
3971     }
3972   }
3973 }
3974 
3975 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3976   // The landingpad instruction is ill-formed if it doesn't have any clauses and
3977   // isn't a cleanup.
3978   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3979          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3980 
3981   visitEHPadPredecessors(LPI);
3982 
3983   if (!LandingPadResultTy)
3984     LandingPadResultTy = LPI.getType();
3985   else
3986     Assert(LandingPadResultTy == LPI.getType(),
3987            "The landingpad instruction should have a consistent result type "
3988            "inside a function.",
3989            &LPI);
3990 
3991   Function *F = LPI.getParent()->getParent();
3992   Assert(F->hasPersonalityFn(),
3993          "LandingPadInst needs to be in a function with a personality.", &LPI);
3994 
3995   // The landingpad instruction must be the first non-PHI instruction in the
3996   // block.
3997   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
3998          "LandingPadInst not the first non-PHI instruction in the block.",
3999          &LPI);
4000 
4001   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4002     Constant *Clause = LPI.getClause(i);
4003     if (LPI.isCatch(i)) {
4004       Assert(isa<PointerType>(Clause->getType()),
4005              "Catch operand does not have pointer type!", &LPI);
4006     } else {
4007       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4008       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
4009              "Filter operand is not an array of constants!", &LPI);
4010     }
4011   }
4012 
4013   visitInstruction(LPI);
4014 }
4015 
4016 void Verifier::visitResumeInst(ResumeInst &RI) {
4017   Assert(RI.getFunction()->hasPersonalityFn(),
4018          "ResumeInst needs to be in a function with a personality.", &RI);
4019 
4020   if (!LandingPadResultTy)
4021     LandingPadResultTy = RI.getValue()->getType();
4022   else
4023     Assert(LandingPadResultTy == RI.getValue()->getType(),
4024            "The resume instruction should have a consistent result type "
4025            "inside a function.",
4026            &RI);
4027 
4028   visitTerminator(RI);
4029 }
4030 
4031 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4032   BasicBlock *BB = CPI.getParent();
4033 
4034   Function *F = BB->getParent();
4035   Assert(F->hasPersonalityFn(),
4036          "CatchPadInst needs to be in a function with a personality.", &CPI);
4037 
4038   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
4039          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4040          CPI.getParentPad());
4041 
4042   // The catchpad instruction must be the first non-PHI instruction in the
4043   // block.
4044   Assert(BB->getFirstNonPHI() == &CPI,
4045          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4046 
4047   visitEHPadPredecessors(CPI);
4048   visitFuncletPadInst(CPI);
4049 }
4050 
4051 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4052   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4053          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4054          CatchReturn.getOperand(0));
4055 
4056   visitTerminator(CatchReturn);
4057 }
4058 
4059 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4060   BasicBlock *BB = CPI.getParent();
4061 
4062   Function *F = BB->getParent();
4063   Assert(F->hasPersonalityFn(),
4064          "CleanupPadInst needs to be in a function with a personality.", &CPI);
4065 
4066   // The cleanuppad instruction must be the first non-PHI instruction in the
4067   // block.
4068   Assert(BB->getFirstNonPHI() == &CPI,
4069          "CleanupPadInst not the first non-PHI instruction in the block.",
4070          &CPI);
4071 
4072   auto *ParentPad = CPI.getParentPad();
4073   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4074          "CleanupPadInst has an invalid parent.", &CPI);
4075 
4076   visitEHPadPredecessors(CPI);
4077   visitFuncletPadInst(CPI);
4078 }
4079 
4080 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4081   User *FirstUser = nullptr;
4082   Value *FirstUnwindPad = nullptr;
4083   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4084   SmallSet<FuncletPadInst *, 8> Seen;
4085 
4086   while (!Worklist.empty()) {
4087     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4088     Assert(Seen.insert(CurrentPad).second,
4089            "FuncletPadInst must not be nested within itself", CurrentPad);
4090     Value *UnresolvedAncestorPad = nullptr;
4091     for (User *U : CurrentPad->users()) {
4092       BasicBlock *UnwindDest;
4093       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4094         UnwindDest = CRI->getUnwindDest();
4095       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4096         // We allow catchswitch unwind to caller to nest
4097         // within an outer pad that unwinds somewhere else,
4098         // because catchswitch doesn't have a nounwind variant.
4099         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4100         if (CSI->unwindsToCaller())
4101           continue;
4102         UnwindDest = CSI->getUnwindDest();
4103       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4104         UnwindDest = II->getUnwindDest();
4105       } else if (isa<CallInst>(U)) {
4106         // Calls which don't unwind may be found inside funclet
4107         // pads that unwind somewhere else.  We don't *require*
4108         // such calls to be annotated nounwind.
4109         continue;
4110       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4111         // The unwind dest for a cleanup can only be found by
4112         // recursive search.  Add it to the worklist, and we'll
4113         // search for its first use that determines where it unwinds.
4114         Worklist.push_back(CPI);
4115         continue;
4116       } else {
4117         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
4118         continue;
4119       }
4120 
4121       Value *UnwindPad;
4122       bool ExitsFPI;
4123       if (UnwindDest) {
4124         UnwindPad = UnwindDest->getFirstNonPHI();
4125         if (!cast<Instruction>(UnwindPad)->isEHPad())
4126           continue;
4127         Value *UnwindParent = getParentPad(UnwindPad);
4128         // Ignore unwind edges that don't exit CurrentPad.
4129         if (UnwindParent == CurrentPad)
4130           continue;
4131         // Determine whether the original funclet pad is exited,
4132         // and if we are scanning nested pads determine how many
4133         // of them are exited so we can stop searching their
4134         // children.
4135         Value *ExitedPad = CurrentPad;
4136         ExitsFPI = false;
4137         do {
4138           if (ExitedPad == &FPI) {
4139             ExitsFPI = true;
4140             // Now we can resolve any ancestors of CurrentPad up to
4141             // FPI, but not including FPI since we need to make sure
4142             // to check all direct users of FPI for consistency.
4143             UnresolvedAncestorPad = &FPI;
4144             break;
4145           }
4146           Value *ExitedParent = getParentPad(ExitedPad);
4147           if (ExitedParent == UnwindParent) {
4148             // ExitedPad is the ancestor-most pad which this unwind
4149             // edge exits, so we can resolve up to it, meaning that
4150             // ExitedParent is the first ancestor still unresolved.
4151             UnresolvedAncestorPad = ExitedParent;
4152             break;
4153           }
4154           ExitedPad = ExitedParent;
4155         } while (!isa<ConstantTokenNone>(ExitedPad));
4156       } else {
4157         // Unwinding to caller exits all pads.
4158         UnwindPad = ConstantTokenNone::get(FPI.getContext());
4159         ExitsFPI = true;
4160         UnresolvedAncestorPad = &FPI;
4161       }
4162 
4163       if (ExitsFPI) {
4164         // This unwind edge exits FPI.  Make sure it agrees with other
4165         // such edges.
4166         if (FirstUser) {
4167           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
4168                                               "pad must have the same unwind "
4169                                               "dest",
4170                  &FPI, U, FirstUser);
4171         } else {
4172           FirstUser = U;
4173           FirstUnwindPad = UnwindPad;
4174           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4175           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4176               getParentPad(UnwindPad) == getParentPad(&FPI))
4177             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4178         }
4179       }
4180       // Make sure we visit all uses of FPI, but for nested pads stop as
4181       // soon as we know where they unwind to.
4182       if (CurrentPad != &FPI)
4183         break;
4184     }
4185     if (UnresolvedAncestorPad) {
4186       if (CurrentPad == UnresolvedAncestorPad) {
4187         // When CurrentPad is FPI itself, we don't mark it as resolved even if
4188         // we've found an unwind edge that exits it, because we need to verify
4189         // all direct uses of FPI.
4190         assert(CurrentPad == &FPI);
4191         continue;
4192       }
4193       // Pop off the worklist any nested pads that we've found an unwind
4194       // destination for.  The pads on the worklist are the uncles,
4195       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
4196       // for all ancestors of CurrentPad up to but not including
4197       // UnresolvedAncestorPad.
4198       Value *ResolvedPad = CurrentPad;
4199       while (!Worklist.empty()) {
4200         Value *UnclePad = Worklist.back();
4201         Value *AncestorPad = getParentPad(UnclePad);
4202         // Walk ResolvedPad up the ancestor list until we either find the
4203         // uncle's parent or the last resolved ancestor.
4204         while (ResolvedPad != AncestorPad) {
4205           Value *ResolvedParent = getParentPad(ResolvedPad);
4206           if (ResolvedParent == UnresolvedAncestorPad) {
4207             break;
4208           }
4209           ResolvedPad = ResolvedParent;
4210         }
4211         // If the resolved ancestor search didn't find the uncle's parent,
4212         // then the uncle is not yet resolved.
4213         if (ResolvedPad != AncestorPad)
4214           break;
4215         // This uncle is resolved, so pop it from the worklist.
4216         Worklist.pop_back();
4217       }
4218     }
4219   }
4220 
4221   if (FirstUnwindPad) {
4222     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4223       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4224       Value *SwitchUnwindPad;
4225       if (SwitchUnwindDest)
4226         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4227       else
4228         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4229       Assert(SwitchUnwindPad == FirstUnwindPad,
4230              "Unwind edges out of a catch must have the same unwind dest as "
4231              "the parent catchswitch",
4232              &FPI, FirstUser, CatchSwitch);
4233     }
4234   }
4235 
4236   visitInstruction(FPI);
4237 }
4238 
4239 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4240   BasicBlock *BB = CatchSwitch.getParent();
4241 
4242   Function *F = BB->getParent();
4243   Assert(F->hasPersonalityFn(),
4244          "CatchSwitchInst needs to be in a function with a personality.",
4245          &CatchSwitch);
4246 
4247   // The catchswitch instruction must be the first non-PHI instruction in the
4248   // block.
4249   Assert(BB->getFirstNonPHI() == &CatchSwitch,
4250          "CatchSwitchInst not the first non-PHI instruction in the block.",
4251          &CatchSwitch);
4252 
4253   auto *ParentPad = CatchSwitch.getParentPad();
4254   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4255          "CatchSwitchInst has an invalid parent.", ParentPad);
4256 
4257   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4258     Instruction *I = UnwindDest->getFirstNonPHI();
4259     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4260            "CatchSwitchInst must unwind to an EH block which is not a "
4261            "landingpad.",
4262            &CatchSwitch);
4263 
4264     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4265     if (getParentPad(I) == ParentPad)
4266       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4267   }
4268 
4269   Assert(CatchSwitch.getNumHandlers() != 0,
4270          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4271 
4272   for (BasicBlock *Handler : CatchSwitch.handlers()) {
4273     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4274            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4275   }
4276 
4277   visitEHPadPredecessors(CatchSwitch);
4278   visitTerminator(CatchSwitch);
4279 }
4280 
4281 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4282   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
4283          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4284          CRI.getOperand(0));
4285 
4286   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4287     Instruction *I = UnwindDest->getFirstNonPHI();
4288     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4289            "CleanupReturnInst must unwind to an EH block which is not a "
4290            "landingpad.",
4291            &CRI);
4292   }
4293 
4294   visitTerminator(CRI);
4295 }
4296 
4297 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4298   Instruction *Op = cast<Instruction>(I.getOperand(i));
4299   // If the we have an invalid invoke, don't try to compute the dominance.
4300   // We already reject it in the invoke specific checks and the dominance
4301   // computation doesn't handle multiple edges.
4302   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4303     if (II->getNormalDest() == II->getUnwindDest())
4304       return;
4305   }
4306 
4307   // Quick check whether the def has already been encountered in the same block.
4308   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4309   // uses are defined to happen on the incoming edge, not at the instruction.
4310   //
4311   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4312   // wrapping an SSA value, assert that we've already encountered it.  See
4313   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4314   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4315     return;
4316 
4317   const Use &U = I.getOperandUse(i);
4318   Assert(DT.dominates(Op, U),
4319          "Instruction does not dominate all uses!", Op, &I);
4320 }
4321 
4322 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4323   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
4324          "apply only to pointer types", &I);
4325   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4326          "dereferenceable, dereferenceable_or_null apply only to load"
4327          " and inttoptr instructions, use attributes for calls or invokes", &I);
4328   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
4329          "take one operand!", &I);
4330   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4331   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
4332          "dereferenceable_or_null metadata value must be an i64!", &I);
4333 }
4334 
4335 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4336   Assert(MD->getNumOperands() >= 2,
4337          "!prof annotations should have no less than 2 operands", MD);
4338 
4339   // Check first operand.
4340   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4341   Assert(isa<MDString>(MD->getOperand(0)),
4342          "expected string with name of the !prof annotation", MD);
4343   MDString *MDS = cast<MDString>(MD->getOperand(0));
4344   StringRef ProfName = MDS->getString();
4345 
4346   // Check consistency of !prof branch_weights metadata.
4347   if (ProfName.equals("branch_weights")) {
4348     if (isa<InvokeInst>(&I)) {
4349       Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4350              "Wrong number of InvokeInst branch_weights operands", MD);
4351     } else {
4352       unsigned ExpectedNumOperands = 0;
4353       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4354         ExpectedNumOperands = BI->getNumSuccessors();
4355       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4356         ExpectedNumOperands = SI->getNumSuccessors();
4357       else if (isa<CallInst>(&I))
4358         ExpectedNumOperands = 1;
4359       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4360         ExpectedNumOperands = IBI->getNumDestinations();
4361       else if (isa<SelectInst>(&I))
4362         ExpectedNumOperands = 2;
4363       else
4364         CheckFailed("!prof branch_weights are not allowed for this instruction",
4365                     MD);
4366 
4367       Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
4368              "Wrong number of operands", MD);
4369     }
4370     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4371       auto &MDO = MD->getOperand(i);
4372       Assert(MDO, "second operand should not be null", MD);
4373       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
4374              "!prof brunch_weights operand is not a const int");
4375     }
4376   }
4377 }
4378 
4379 void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4380   Assert(isa<MDTuple>(Annotation), "annotation must be a tuple");
4381   Assert(Annotation->getNumOperands() >= 1,
4382          "annotation must have at least one operand");
4383   for (const MDOperand &Op : Annotation->operands())
4384     Assert(isa<MDString>(Op.get()), "operands must be strings");
4385 }
4386 
4387 void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4388   unsigned NumOps = MD->getNumOperands();
4389   Assert(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4390          MD);
4391   Assert(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4392          "first scope operand must be self-referential or string", MD);
4393   if (NumOps == 3)
4394     Assert(isa<MDString>(MD->getOperand(2)),
4395            "third scope operand must be string (if used)", MD);
4396 
4397   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
4398   Assert(Domain != nullptr, "second scope operand must be MDNode", MD);
4399 
4400   unsigned NumDomainOps = Domain->getNumOperands();
4401   Assert(NumDomainOps >= 1 && NumDomainOps <= 2,
4402          "domain must have one or two operands", Domain);
4403   Assert(Domain->getOperand(0).get() == Domain ||
4404              isa<MDString>(Domain->getOperand(0)),
4405          "first domain operand must be self-referential or string", Domain);
4406   if (NumDomainOps == 2)
4407     Assert(isa<MDString>(Domain->getOperand(1)),
4408            "second domain operand must be string (if used)", Domain);
4409 }
4410 
4411 void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4412   for (const MDOperand &Op : MD->operands()) {
4413     const MDNode *OpMD = dyn_cast<MDNode>(Op);
4414     Assert(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4415     visitAliasScopeMetadata(OpMD);
4416   }
4417 }
4418 
4419 /// verifyInstruction - Verify that an instruction is well formed.
4420 ///
4421 void Verifier::visitInstruction(Instruction &I) {
4422   BasicBlock *BB = I.getParent();
4423   Assert(BB, "Instruction not embedded in basic block!", &I);
4424 
4425   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
4426     for (User *U : I.users()) {
4427       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
4428              "Only PHI nodes may reference their own value!", &I);
4429     }
4430   }
4431 
4432   // Check that void typed values don't have names
4433   Assert(!I.getType()->isVoidTy() || !I.hasName(),
4434          "Instruction has a name, but provides a void value!", &I);
4435 
4436   // Check that the return value of the instruction is either void or a legal
4437   // value type.
4438   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
4439          "Instruction returns a non-scalar type!", &I);
4440 
4441   // Check that the instruction doesn't produce metadata. Calls are already
4442   // checked against the callee type.
4443   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
4444          "Invalid use of metadata!", &I);
4445 
4446   // Check that all uses of the instruction, if they are instructions
4447   // themselves, actually have parent basic blocks.  If the use is not an
4448   // instruction, it is an error!
4449   for (Use &U : I.uses()) {
4450     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
4451       Assert(Used->getParent() != nullptr,
4452              "Instruction referencing"
4453              " instruction not embedded in a basic block!",
4454              &I, Used);
4455     else {
4456       CheckFailed("Use of instruction is not an instruction!", U);
4457       return;
4458     }
4459   }
4460 
4461   // Get a pointer to the call base of the instruction if it is some form of
4462   // call.
4463   const CallBase *CBI = dyn_cast<CallBase>(&I);
4464 
4465   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
4466     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
4467 
4468     // Check to make sure that only first-class-values are operands to
4469     // instructions.
4470     if (!I.getOperand(i)->getType()->isFirstClassType()) {
4471       Assert(false, "Instruction operands must be first-class values!", &I);
4472     }
4473 
4474     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4475       // This code checks whether the function is used as the operand of a
4476       // clang_arc_attachedcall operand bundle.
4477       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4478                                       int Idx) {
4479         return CBI && CBI->isOperandBundleOfType(
4480                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4481       };
4482 
4483       // Check to make sure that the "address of" an intrinsic function is never
4484       // taken. Ignore cases where the address of the intrinsic function is used
4485       // as the argument of operand bundle "clang.arc.attachedcall" as those
4486       // cases are handled in verifyAttachedCallBundle.
4487       Assert((!F->isIntrinsic() ||
4488               (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4489               IsAttachedCallOperand(F, CBI, i)),
4490              "Cannot take the address of an intrinsic!", &I);
4491       Assert(
4492           !F->isIntrinsic() || isa<CallInst>(I) ||
4493               F->getIntrinsicID() == Intrinsic::donothing ||
4494               F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4495               F->getIntrinsicID() == Intrinsic::seh_try_end ||
4496               F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4497               F->getIntrinsicID() == Intrinsic::seh_scope_end ||
4498               F->getIntrinsicID() == Intrinsic::coro_resume ||
4499               F->getIntrinsicID() == Intrinsic::coro_destroy ||
4500               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
4501               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
4502               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4503               F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4504               IsAttachedCallOperand(F, CBI, i),
4505           "Cannot invoke an intrinsic other than donothing, patchpoint, "
4506           "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4507           &I);
4508       Assert(F->getParent() == &M, "Referencing function in another module!",
4509              &I, &M, F, F->getParent());
4510     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
4511       Assert(OpBB->getParent() == BB->getParent(),
4512              "Referring to a basic block in another function!", &I);
4513     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
4514       Assert(OpArg->getParent() == BB->getParent(),
4515              "Referring to an argument in another function!", &I);
4516     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
4517       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
4518              &M, GV, GV->getParent());
4519     } else if (isa<Instruction>(I.getOperand(i))) {
4520       verifyDominatesUse(I, i);
4521     } else if (isa<InlineAsm>(I.getOperand(i))) {
4522       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
4523              "Cannot take the address of an inline asm!", &I);
4524     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4525       if (CE->getType()->isPtrOrPtrVectorTy()) {
4526         // If we have a ConstantExpr pointer, we need to see if it came from an
4527         // illegal bitcast.
4528         visitConstantExprsRecursively(CE);
4529       }
4530     }
4531   }
4532 
4533   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
4534     Assert(I.getType()->isFPOrFPVectorTy(),
4535            "fpmath requires a floating point result!", &I);
4536     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
4537     if (ConstantFP *CFP0 =
4538             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
4539       const APFloat &Accuracy = CFP0->getValueAPF();
4540       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
4541              "fpmath accuracy must have float type", &I);
4542       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
4543              "fpmath accuracy not a positive number!", &I);
4544     } else {
4545       Assert(false, "invalid fpmath accuracy!", &I);
4546     }
4547   }
4548 
4549   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
4550     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
4551            "Ranges are only for loads, calls and invokes!", &I);
4552     visitRangeMetadata(I, Range, I.getType());
4553   }
4554 
4555   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
4556     Assert(isa<LoadInst>(I) || isa<StoreInst>(I),
4557            "invariant.group metadata is only for loads and stores", &I);
4558   }
4559 
4560   if (I.getMetadata(LLVMContext::MD_nonnull)) {
4561     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
4562            &I);
4563     Assert(isa<LoadInst>(I),
4564            "nonnull applies only to load instructions, use attributes"
4565            " for calls or invokes",
4566            &I);
4567   }
4568 
4569   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
4570     visitDereferenceableMetadata(I, MD);
4571 
4572   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4573     visitDereferenceableMetadata(I, MD);
4574 
4575   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
4576     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4577 
4578   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
4579     visitAliasScopeListMetadata(MD);
4580   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
4581     visitAliasScopeListMetadata(MD);
4582 
4583   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4584     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
4585            &I);
4586     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
4587            "use attributes for calls or invokes", &I);
4588     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
4589     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4590     Assert(CI && CI->getType()->isIntegerTy(64),
4591            "align metadata value must be an i64!", &I);
4592     uint64_t Align = CI->getZExtValue();
4593     Assert(isPowerOf2_64(Align),
4594            "align metadata value must be a power of 2!", &I);
4595     Assert(Align <= Value::MaximumAlignment,
4596            "alignment is larger that implementation defined limit", &I);
4597   }
4598 
4599   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
4600     visitProfMetadata(I, MD);
4601 
4602   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4603     visitAnnotationMetadata(Annotation);
4604 
4605   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
4606     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
4607     visitMDNode(*N, AreDebugLocsAllowed::Yes);
4608   }
4609 
4610   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
4611     verifyFragmentExpression(*DII);
4612     verifyNotEntryValue(*DII);
4613   }
4614 
4615   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4616   I.getAllMetadata(MDs);
4617   for (auto Attachment : MDs) {
4618     unsigned Kind = Attachment.first;
4619     auto AllowLocs =
4620         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
4621             ? AreDebugLocsAllowed::Yes
4622             : AreDebugLocsAllowed::No;
4623     visitMDNode(*Attachment.second, AllowLocs);
4624   }
4625 
4626   InstsInThisBlock.insert(&I);
4627 }
4628 
4629 /// Allow intrinsics to be verified in different ways.
4630 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
4631   Function *IF = Call.getCalledFunction();
4632   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
4633          IF);
4634 
4635   // Verify that the intrinsic prototype lines up with what the .td files
4636   // describe.
4637   FunctionType *IFTy = IF->getFunctionType();
4638   bool IsVarArg = IFTy->isVarArg();
4639 
4640   SmallVector<Intrinsic::IITDescriptor, 8> Table;
4641   getIntrinsicInfoTableEntries(ID, Table);
4642   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
4643 
4644   // Walk the descriptors to extract overloaded types.
4645   SmallVector<Type *, 4> ArgTys;
4646   Intrinsic::MatchIntrinsicTypesResult Res =
4647       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
4648   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
4649          "Intrinsic has incorrect return type!", IF);
4650   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
4651          "Intrinsic has incorrect argument type!", IF);
4652 
4653   // Verify if the intrinsic call matches the vararg property.
4654   if (IsVarArg)
4655     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4656            "Intrinsic was not defined with variable arguments!", IF);
4657   else
4658     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4659            "Callsite was not defined with variable arguments!", IF);
4660 
4661   // All descriptors should be absorbed by now.
4662   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
4663 
4664   // Now that we have the intrinsic ID and the actual argument types (and we
4665   // know they are legal for the intrinsic!) get the intrinsic name through the
4666   // usual means.  This allows us to verify the mangling of argument types into
4667   // the name.
4668   const std::string ExpectedName =
4669       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
4670   Assert(ExpectedName == IF->getName(),
4671          "Intrinsic name not mangled correctly for type arguments! "
4672          "Should be: " +
4673              ExpectedName,
4674          IF);
4675 
4676   // If the intrinsic takes MDNode arguments, verify that they are either global
4677   // or are local to *this* function.
4678   for (Value *V : Call.args()) {
4679     if (auto *MD = dyn_cast<MetadataAsValue>(V))
4680       visitMetadataAsValue(*MD, Call.getCaller());
4681     if (auto *Const = dyn_cast<Constant>(V))
4682       Assert(!Const->getType()->isX86_AMXTy(),
4683              "const x86_amx is not allowed in argument!");
4684   }
4685 
4686   switch (ID) {
4687   default:
4688     break;
4689   case Intrinsic::assume: {
4690     for (auto &Elem : Call.bundle_op_infos()) {
4691       Assert(Elem.Tag->getKey() == "ignore" ||
4692                  Attribute::isExistingAttribute(Elem.Tag->getKey()),
4693              "tags must be valid attribute names", Call);
4694       Attribute::AttrKind Kind =
4695           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4696       unsigned ArgCount = Elem.End - Elem.Begin;
4697       if (Kind == Attribute::Alignment) {
4698         Assert(ArgCount <= 3 && ArgCount >= 2,
4699                "alignment assumptions should have 2 or 3 arguments", Call);
4700         Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4701                "first argument should be a pointer", Call);
4702         Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4703                "second argument should be an integer", Call);
4704         if (ArgCount == 3)
4705           Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4706                  "third argument should be an integer if present", Call);
4707         return;
4708       }
4709       Assert(ArgCount <= 2, "too many arguments", Call);
4710       if (Kind == Attribute::None)
4711         break;
4712       if (Attribute::isIntAttrKind(Kind)) {
4713         Assert(ArgCount == 2, "this attribute should have 2 arguments", Call);
4714         Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
4715                "the second argument should be a constant integral value", Call);
4716       } else if (Attribute::canUseAsParamAttr(Kind)) {
4717         Assert((ArgCount) == 1, "this attribute should have one argument",
4718                Call);
4719       } else if (Attribute::canUseAsFnAttr(Kind)) {
4720         Assert((ArgCount) == 0, "this attribute has no argument", Call);
4721       }
4722     }
4723     break;
4724   }
4725   case Intrinsic::coro_id: {
4726     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
4727     if (isa<ConstantPointerNull>(InfoArg))
4728       break;
4729     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4730     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4731            "info argument of llvm.coro.id must refer to an initialized "
4732            "constant");
4733     Constant *Init = GV->getInitializer();
4734     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4735            "info argument of llvm.coro.id must refer to either a struct or "
4736            "an array");
4737     break;
4738   }
4739 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
4740   case Intrinsic::INTRINSIC:
4741 #include "llvm/IR/ConstrainedOps.def"
4742     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
4743     break;
4744   case Intrinsic::dbg_declare: // llvm.dbg.declare
4745     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
4746            "invalid llvm.dbg.declare intrinsic call 1", Call);
4747     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
4748     break;
4749   case Intrinsic::dbg_addr: // llvm.dbg.addr
4750     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
4751     break;
4752   case Intrinsic::dbg_value: // llvm.dbg.value
4753     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
4754     break;
4755   case Intrinsic::dbg_label: // llvm.dbg.label
4756     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
4757     break;
4758   case Intrinsic::memcpy:
4759   case Intrinsic::memcpy_inline:
4760   case Intrinsic::memmove:
4761   case Intrinsic::memset: {
4762     const auto *MI = cast<MemIntrinsic>(&Call);
4763     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
4764       return Alignment == 0 || isPowerOf2_32(Alignment);
4765     };
4766     Assert(IsValidAlignment(MI->getDestAlignment()),
4767            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4768            Call);
4769     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
4770       Assert(IsValidAlignment(MTI->getSourceAlignment()),
4771              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4772              Call);
4773     }
4774 
4775     break;
4776   }
4777   case Intrinsic::memcpy_element_unordered_atomic:
4778   case Intrinsic::memmove_element_unordered_atomic:
4779   case Intrinsic::memset_element_unordered_atomic: {
4780     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
4781 
4782     ConstantInt *ElementSizeCI =
4783         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4784     const APInt &ElementSizeVal = ElementSizeCI->getValue();
4785     Assert(ElementSizeVal.isPowerOf2(),
4786            "element size of the element-wise atomic memory intrinsic "
4787            "must be a power of 2",
4788            Call);
4789 
4790     auto IsValidAlignment = [&](uint64_t Alignment) {
4791       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4792     };
4793     uint64_t DstAlignment = AMI->getDestAlignment();
4794     Assert(IsValidAlignment(DstAlignment),
4795            "incorrect alignment of the destination argument", Call);
4796     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4797       uint64_t SrcAlignment = AMT->getSourceAlignment();
4798       Assert(IsValidAlignment(SrcAlignment),
4799              "incorrect alignment of the source argument", Call);
4800     }
4801     break;
4802   }
4803   case Intrinsic::call_preallocated_setup: {
4804     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
4805     Assert(NumArgs != nullptr,
4806            "llvm.call.preallocated.setup argument must be a constant");
4807     bool FoundCall = false;
4808     for (User *U : Call.users()) {
4809       auto *UseCall = dyn_cast<CallBase>(U);
4810       Assert(UseCall != nullptr,
4811              "Uses of llvm.call.preallocated.setup must be calls");
4812       const Function *Fn = UseCall->getCalledFunction();
4813       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
4814         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
4815         Assert(AllocArgIndex != nullptr,
4816                "llvm.call.preallocated.alloc arg index must be a constant");
4817         auto AllocArgIndexInt = AllocArgIndex->getValue();
4818         Assert(AllocArgIndexInt.sge(0) &&
4819                    AllocArgIndexInt.slt(NumArgs->getValue()),
4820                "llvm.call.preallocated.alloc arg index must be between 0 and "
4821                "corresponding "
4822                "llvm.call.preallocated.setup's argument count");
4823       } else if (Fn && Fn->getIntrinsicID() ==
4824                            Intrinsic::call_preallocated_teardown) {
4825         // nothing to do
4826       } else {
4827         Assert(!FoundCall, "Can have at most one call corresponding to a "
4828                            "llvm.call.preallocated.setup");
4829         FoundCall = true;
4830         size_t NumPreallocatedArgs = 0;
4831         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
4832           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
4833             ++NumPreallocatedArgs;
4834           }
4835         }
4836         Assert(NumPreallocatedArgs != 0,
4837                "cannot use preallocated intrinsics on a call without "
4838                "preallocated arguments");
4839         Assert(NumArgs->equalsInt(NumPreallocatedArgs),
4840                "llvm.call.preallocated.setup arg size must be equal to number "
4841                "of preallocated arguments "
4842                "at call site",
4843                Call, *UseCall);
4844         // getOperandBundle() cannot be called if more than one of the operand
4845         // bundle exists. There is already a check elsewhere for this, so skip
4846         // here if we see more than one.
4847         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
4848             1) {
4849           return;
4850         }
4851         auto PreallocatedBundle =
4852             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
4853         Assert(PreallocatedBundle,
4854                "Use of llvm.call.preallocated.setup outside intrinsics "
4855                "must be in \"preallocated\" operand bundle");
4856         Assert(PreallocatedBundle->Inputs.front().get() == &Call,
4857                "preallocated bundle must have token from corresponding "
4858                "llvm.call.preallocated.setup");
4859       }
4860     }
4861     break;
4862   }
4863   case Intrinsic::call_preallocated_arg: {
4864     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4865     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4866                         Intrinsic::call_preallocated_setup,
4867            "llvm.call.preallocated.arg token argument must be a "
4868            "llvm.call.preallocated.setup");
4869     Assert(Call.hasFnAttr(Attribute::Preallocated),
4870            "llvm.call.preallocated.arg must be called with a \"preallocated\" "
4871            "call site attribute");
4872     break;
4873   }
4874   case Intrinsic::call_preallocated_teardown: {
4875     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4876     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4877                         Intrinsic::call_preallocated_setup,
4878            "llvm.call.preallocated.teardown token argument must be a "
4879            "llvm.call.preallocated.setup");
4880     break;
4881   }
4882   case Intrinsic::gcroot:
4883   case Intrinsic::gcwrite:
4884   case Intrinsic::gcread:
4885     if (ID == Intrinsic::gcroot) {
4886       AllocaInst *AI =
4887           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
4888       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
4889       Assert(isa<Constant>(Call.getArgOperand(1)),
4890              "llvm.gcroot parameter #2 must be a constant.", Call);
4891       if (!AI->getAllocatedType()->isPointerTy()) {
4892         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
4893                "llvm.gcroot parameter #1 must either be a pointer alloca, "
4894                "or argument #2 must be a non-null constant.",
4895                Call);
4896       }
4897     }
4898 
4899     Assert(Call.getParent()->getParent()->hasGC(),
4900            "Enclosing function does not use GC.", Call);
4901     break;
4902   case Intrinsic::init_trampoline:
4903     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
4904            "llvm.init_trampoline parameter #2 must resolve to a function.",
4905            Call);
4906     break;
4907   case Intrinsic::prefetch:
4908     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
4909            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
4910            "invalid arguments to llvm.prefetch", Call);
4911     break;
4912   case Intrinsic::stackprotector:
4913     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
4914            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
4915     break;
4916   case Intrinsic::localescape: {
4917     BasicBlock *BB = Call.getParent();
4918     Assert(BB == &BB->getParent()->front(),
4919            "llvm.localescape used outside of entry block", Call);
4920     Assert(!SawFrameEscape,
4921            "multiple calls to llvm.localescape in one function", Call);
4922     for (Value *Arg : Call.args()) {
4923       if (isa<ConstantPointerNull>(Arg))
4924         continue; // Null values are allowed as placeholders.
4925       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
4926       Assert(AI && AI->isStaticAlloca(),
4927              "llvm.localescape only accepts static allocas", Call);
4928     }
4929     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
4930     SawFrameEscape = true;
4931     break;
4932   }
4933   case Intrinsic::localrecover: {
4934     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
4935     Function *Fn = dyn_cast<Function>(FnArg);
4936     Assert(Fn && !Fn->isDeclaration(),
4937            "llvm.localrecover first "
4938            "argument must be function defined in this module",
4939            Call);
4940     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
4941     auto &Entry = FrameEscapeInfo[Fn];
4942     Entry.second = unsigned(
4943         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4944     break;
4945   }
4946 
4947   case Intrinsic::experimental_gc_statepoint:
4948     if (auto *CI = dyn_cast<CallInst>(&Call))
4949       Assert(!CI->isInlineAsm(),
4950              "gc.statepoint support for inline assembly unimplemented", CI);
4951     Assert(Call.getParent()->getParent()->hasGC(),
4952            "Enclosing function does not use GC.", Call);
4953 
4954     verifyStatepoint(Call);
4955     break;
4956   case Intrinsic::experimental_gc_result: {
4957     Assert(Call.getParent()->getParent()->hasGC(),
4958            "Enclosing function does not use GC.", Call);
4959     // Are we tied to a statepoint properly?
4960     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
4961     const Function *StatepointFn =
4962         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
4963     Assert(StatepointFn && StatepointFn->isDeclaration() &&
4964                StatepointFn->getIntrinsicID() ==
4965                    Intrinsic::experimental_gc_statepoint,
4966            "gc.result operand #1 must be from a statepoint", Call,
4967            Call.getArgOperand(0));
4968 
4969     // Assert that result type matches wrapped callee.
4970     const Value *Target = StatepointCall->getArgOperand(2);
4971     auto *PT = cast<PointerType>(Target->getType());
4972     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4973     Assert(Call.getType() == TargetFuncType->getReturnType(),
4974            "gc.result result type does not match wrapped callee", Call);
4975     break;
4976   }
4977   case Intrinsic::experimental_gc_relocate: {
4978     Assert(Call.arg_size() == 3, "wrong number of arguments", Call);
4979 
4980     Assert(isa<PointerType>(Call.getType()->getScalarType()),
4981            "gc.relocate must return a pointer or a vector of pointers", Call);
4982 
4983     // Check that this relocate is correctly tied to the statepoint
4984 
4985     // This is case for relocate on the unwinding path of an invoke statepoint
4986     if (LandingPadInst *LandingPad =
4987             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
4988 
4989       const BasicBlock *InvokeBB =
4990           LandingPad->getParent()->getUniquePredecessor();
4991 
4992       // Landingpad relocates should have only one predecessor with invoke
4993       // statepoint terminator
4994       Assert(InvokeBB, "safepoints should have unique landingpads",
4995              LandingPad->getParent());
4996       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
4997              InvokeBB);
4998       Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),
4999              "gc relocate should be linked to a statepoint", InvokeBB);
5000     } else {
5001       // In all other cases relocate should be tied to the statepoint directly.
5002       // This covers relocates on a normal return path of invoke statepoint and
5003       // relocates of a call statepoint.
5004       auto Token = Call.getArgOperand(0);
5005       Assert(isa<GCStatepointInst>(Token),
5006              "gc relocate is incorrectly tied to the statepoint", Call, Token);
5007     }
5008 
5009     // Verify rest of the relocate arguments.
5010     const CallBase &StatepointCall =
5011       *cast<GCRelocateInst>(Call).getStatepoint();
5012 
5013     // Both the base and derived must be piped through the safepoint.
5014     Value *Base = Call.getArgOperand(1);
5015     Assert(isa<ConstantInt>(Base),
5016            "gc.relocate operand #2 must be integer offset", Call);
5017 
5018     Value *Derived = Call.getArgOperand(2);
5019     Assert(isa<ConstantInt>(Derived),
5020            "gc.relocate operand #3 must be integer offset", Call);
5021 
5022     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
5023     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
5024 
5025     // Check the bounds
5026     if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
5027       Assert(BaseIndex < Opt->Inputs.size(),
5028              "gc.relocate: statepoint base index out of bounds", Call);
5029       Assert(DerivedIndex < Opt->Inputs.size(),
5030              "gc.relocate: statepoint derived index out of bounds", Call);
5031     }
5032 
5033     // Relocated value must be either a pointer type or vector-of-pointer type,
5034     // but gc_relocate does not need to return the same pointer type as the
5035     // relocated pointer. It can be casted to the correct type later if it's
5036     // desired. However, they must have the same address space and 'vectorness'
5037     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5038     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
5039            "gc.relocate: relocated value must be a gc pointer", Call);
5040 
5041     auto ResultType = Call.getType();
5042     auto DerivedType = Relocate.getDerivedPtr()->getType();
5043     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
5044            "gc.relocate: vector relocates to vector and pointer to pointer",
5045            Call);
5046     Assert(
5047         ResultType->getPointerAddressSpace() ==
5048             DerivedType->getPointerAddressSpace(),
5049         "gc.relocate: relocating a pointer shouldn't change its address space",
5050         Call);
5051     break;
5052   }
5053   case Intrinsic::eh_exceptioncode:
5054   case Intrinsic::eh_exceptionpointer: {
5055     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
5056            "eh.exceptionpointer argument must be a catchpad", Call);
5057     break;
5058   }
5059   case Intrinsic::get_active_lane_mask: {
5060     Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "
5061            "vector", Call);
5062     auto *ElemTy = Call.getType()->getScalarType();
5063     Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "
5064            "i1", Call);
5065     break;
5066   }
5067   case Intrinsic::masked_load: {
5068     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
5069            Call);
5070 
5071     Value *Ptr = Call.getArgOperand(0);
5072     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
5073     Value *Mask = Call.getArgOperand(2);
5074     Value *PassThru = Call.getArgOperand(3);
5075     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
5076            Call);
5077     Assert(Alignment->getValue().isPowerOf2(),
5078            "masked_load: alignment must be a power of 2", Call);
5079 
5080     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5081     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
5082            "masked_load: return must match pointer type", Call);
5083     Assert(PassThru->getType() == Call.getType(),
5084            "masked_load: pass through and return type must match", Call);
5085     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5086                cast<VectorType>(Call.getType())->getElementCount(),
5087            "masked_load: vector mask must be same length as return", Call);
5088     break;
5089   }
5090   case Intrinsic::masked_store: {
5091     Value *Val = Call.getArgOperand(0);
5092     Value *Ptr = Call.getArgOperand(1);
5093     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
5094     Value *Mask = Call.getArgOperand(3);
5095     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
5096            Call);
5097     Assert(Alignment->getValue().isPowerOf2(),
5098            "masked_store: alignment must be a power of 2", Call);
5099 
5100     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5101     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
5102            "masked_store: storee must match pointer type", Call);
5103     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5104                cast<VectorType>(Val->getType())->getElementCount(),
5105            "masked_store: vector mask must be same length as value", Call);
5106     break;
5107   }
5108 
5109   case Intrinsic::masked_gather: {
5110     const APInt &Alignment =
5111         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
5112     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5113            "masked_gather: alignment must be 0 or a power of 2", Call);
5114     break;
5115   }
5116   case Intrinsic::masked_scatter: {
5117     const APInt &Alignment =
5118         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
5119     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5120            "masked_scatter: alignment must be 0 or a power of 2", Call);
5121     break;
5122   }
5123 
5124   case Intrinsic::experimental_guard: {
5125     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
5126     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5127            "experimental_guard must have exactly one "
5128            "\"deopt\" operand bundle");
5129     break;
5130   }
5131 
5132   case Intrinsic::experimental_deoptimize: {
5133     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
5134            Call);
5135     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5136            "experimental_deoptimize must have exactly one "
5137            "\"deopt\" operand bundle");
5138     Assert(Call.getType() == Call.getFunction()->getReturnType(),
5139            "experimental_deoptimize return type must match caller return type");
5140 
5141     if (isa<CallInst>(Call)) {
5142       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
5143       Assert(RI,
5144              "calls to experimental_deoptimize must be followed by a return");
5145 
5146       if (!Call.getType()->isVoidTy() && RI)
5147         Assert(RI->getReturnValue() == &Call,
5148                "calls to experimental_deoptimize must be followed by a return "
5149                "of the value computed by experimental_deoptimize");
5150     }
5151 
5152     break;
5153   }
5154   case Intrinsic::vector_reduce_and:
5155   case Intrinsic::vector_reduce_or:
5156   case Intrinsic::vector_reduce_xor:
5157   case Intrinsic::vector_reduce_add:
5158   case Intrinsic::vector_reduce_mul:
5159   case Intrinsic::vector_reduce_smax:
5160   case Intrinsic::vector_reduce_smin:
5161   case Intrinsic::vector_reduce_umax:
5162   case Intrinsic::vector_reduce_umin: {
5163     Type *ArgTy = Call.getArgOperand(0)->getType();
5164     Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5165            "Intrinsic has incorrect argument type!");
5166     break;
5167   }
5168   case Intrinsic::vector_reduce_fmax:
5169   case Intrinsic::vector_reduce_fmin: {
5170     Type *ArgTy = Call.getArgOperand(0)->getType();
5171     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5172            "Intrinsic has incorrect argument type!");
5173     break;
5174   }
5175   case Intrinsic::vector_reduce_fadd:
5176   case Intrinsic::vector_reduce_fmul: {
5177     // Unlike the other reductions, the first argument is a start value. The
5178     // second argument is the vector to be reduced.
5179     Type *ArgTy = Call.getArgOperand(1)->getType();
5180     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5181            "Intrinsic has incorrect argument type!");
5182     break;
5183   }
5184   case Intrinsic::smul_fix:
5185   case Intrinsic::smul_fix_sat:
5186   case Intrinsic::umul_fix:
5187   case Intrinsic::umul_fix_sat:
5188   case Intrinsic::sdiv_fix:
5189   case Intrinsic::sdiv_fix_sat:
5190   case Intrinsic::udiv_fix:
5191   case Intrinsic::udiv_fix_sat: {
5192     Value *Op1 = Call.getArgOperand(0);
5193     Value *Op2 = Call.getArgOperand(1);
5194     Assert(Op1->getType()->isIntOrIntVectorTy(),
5195            "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5196            "vector of ints");
5197     Assert(Op2->getType()->isIntOrIntVectorTy(),
5198            "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5199            "vector of ints");
5200 
5201     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5202     Assert(Op3->getType()->getBitWidth() <= 32,
5203            "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
5204 
5205     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
5206         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
5207       Assert(
5208           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5209           "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5210           "the operands");
5211     } else {
5212       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5213              "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5214              "to the width of the operands");
5215     }
5216     break;
5217   }
5218   case Intrinsic::lround:
5219   case Intrinsic::llround:
5220   case Intrinsic::lrint:
5221   case Intrinsic::llrint: {
5222     Type *ValTy = Call.getArgOperand(0)->getType();
5223     Type *ResultTy = Call.getType();
5224     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5225            "Intrinsic does not support vectors", &Call);
5226     break;
5227   }
5228   case Intrinsic::bswap: {
5229     Type *Ty = Call.getType();
5230     unsigned Size = Ty->getScalarSizeInBits();
5231     Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
5232     break;
5233   }
5234   case Intrinsic::invariant_start: {
5235     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
5236     Assert(InvariantSize &&
5237                (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5238            "invariant_start parameter must be -1, 0 or a positive number",
5239            &Call);
5240     break;
5241   }
5242   case Intrinsic::matrix_multiply:
5243   case Intrinsic::matrix_transpose:
5244   case Intrinsic::matrix_column_major_load:
5245   case Intrinsic::matrix_column_major_store: {
5246     Function *IF = Call.getCalledFunction();
5247     ConstantInt *Stride = nullptr;
5248     ConstantInt *NumRows;
5249     ConstantInt *NumColumns;
5250     VectorType *ResultTy;
5251     Type *Op0ElemTy = nullptr;
5252     Type *Op1ElemTy = nullptr;
5253     switch (ID) {
5254     case Intrinsic::matrix_multiply:
5255       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
5256       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5257       ResultTy = cast<VectorType>(Call.getType());
5258       Op0ElemTy =
5259           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5260       Op1ElemTy =
5261           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
5262       break;
5263     case Intrinsic::matrix_transpose:
5264       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
5265       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
5266       ResultTy = cast<VectorType>(Call.getType());
5267       Op0ElemTy =
5268           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5269       break;
5270     case Intrinsic::matrix_column_major_load: {
5271       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
5272       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
5273       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5274       ResultTy = cast<VectorType>(Call.getType());
5275 
5276       PointerType *Op0PtrTy =
5277           cast<PointerType>(Call.getArgOperand(0)->getType());
5278       if (!Op0PtrTy->isOpaque())
5279         Op0ElemTy = Op0PtrTy->getElementType();
5280       break;
5281     }
5282     case Intrinsic::matrix_column_major_store: {
5283       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
5284       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
5285       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
5286       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
5287       Op0ElemTy =
5288           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5289 
5290       PointerType *Op1PtrTy =
5291           cast<PointerType>(Call.getArgOperand(1)->getType());
5292       if (!Op1PtrTy->isOpaque())
5293         Op1ElemTy = Op1PtrTy->getElementType();
5294       break;
5295     }
5296     default:
5297       llvm_unreachable("unexpected intrinsic");
5298     }
5299 
5300     Assert(ResultTy->getElementType()->isIntegerTy() ||
5301            ResultTy->getElementType()->isFloatingPointTy(),
5302            "Result type must be an integer or floating-point type!", IF);
5303 
5304     if (Op0ElemTy)
5305       Assert(ResultTy->getElementType() == Op0ElemTy,
5306              "Vector element type mismatch of the result and first operand "
5307              "vector!", IF);
5308 
5309     if (Op1ElemTy)
5310       Assert(ResultTy->getElementType() == Op1ElemTy,
5311              "Vector element type mismatch of the result and second operand "
5312              "vector!", IF);
5313 
5314     Assert(cast<FixedVectorType>(ResultTy)->getNumElements() ==
5315                NumRows->getZExtValue() * NumColumns->getZExtValue(),
5316            "Result of a matrix operation does not fit in the returned vector!");
5317 
5318     if (Stride)
5319       Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),
5320              "Stride must be greater or equal than the number of rows!", IF);
5321 
5322     break;
5323   }
5324   case Intrinsic::experimental_stepvector: {
5325     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
5326     Assert(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5327                VecTy->getScalarSizeInBits() >= 8,
5328            "experimental_stepvector only supported for vectors of integers "
5329            "with a bitwidth of at least 8.",
5330            &Call);
5331     break;
5332   }
5333   case Intrinsic::experimental_vector_insert: {
5334     Value *Vec = Call.getArgOperand(0);
5335     Value *SubVec = Call.getArgOperand(1);
5336     Value *Idx = Call.getArgOperand(2);
5337     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5338 
5339     VectorType *VecTy = cast<VectorType>(Vec->getType());
5340     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5341 
5342     ElementCount VecEC = VecTy->getElementCount();
5343     ElementCount SubVecEC = SubVecTy->getElementCount();
5344     Assert(VecTy->getElementType() == SubVecTy->getElementType(),
5345            "experimental_vector_insert parameters must have the same element "
5346            "type.",
5347            &Call);
5348     Assert(IdxN % SubVecEC.getKnownMinValue() == 0,
5349            "experimental_vector_insert index must be a constant multiple of "
5350            "the subvector's known minimum vector length.");
5351 
5352     // If this insertion is not the 'mixed' case where a fixed vector is
5353     // inserted into a scalable vector, ensure that the insertion of the
5354     // subvector does not overrun the parent vector.
5355     if (VecEC.isScalable() == SubVecEC.isScalable()) {
5356       Assert(
5357           IdxN < VecEC.getKnownMinValue() &&
5358               IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5359           "subvector operand of experimental_vector_insert would overrun the "
5360           "vector being inserted into.");
5361     }
5362     break;
5363   }
5364   case Intrinsic::experimental_vector_extract: {
5365     Value *Vec = Call.getArgOperand(0);
5366     Value *Idx = Call.getArgOperand(1);
5367     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5368 
5369     VectorType *ResultTy = cast<VectorType>(Call.getType());
5370     VectorType *VecTy = cast<VectorType>(Vec->getType());
5371 
5372     ElementCount VecEC = VecTy->getElementCount();
5373     ElementCount ResultEC = ResultTy->getElementCount();
5374 
5375     Assert(ResultTy->getElementType() == VecTy->getElementType(),
5376            "experimental_vector_extract result must have the same element "
5377            "type as the input vector.",
5378            &Call);
5379     Assert(IdxN % ResultEC.getKnownMinValue() == 0,
5380            "experimental_vector_extract index must be a constant multiple of "
5381            "the result type's known minimum vector length.");
5382 
5383     // If this extraction is not the 'mixed' case where a fixed vector is is
5384     // extracted from a scalable vector, ensure that the extraction does not
5385     // overrun the parent vector.
5386     if (VecEC.isScalable() == ResultEC.isScalable()) {
5387       Assert(IdxN < VecEC.getKnownMinValue() &&
5388                  IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5389              "experimental_vector_extract would overrun.");
5390     }
5391     break;
5392   }
5393   case Intrinsic::experimental_noalias_scope_decl: {
5394     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5395     break;
5396   }
5397   case Intrinsic::preserve_array_access_index:
5398   case Intrinsic::preserve_struct_access_index: {
5399     Type *ElemTy = Call.getAttributes().getParamElementType(0);
5400     Assert(ElemTy,
5401            "Intrinsic requires elementtype attribute on first argument.",
5402            &Call);
5403     break;
5404   }
5405   };
5406 }
5407 
5408 /// Carefully grab the subprogram from a local scope.
5409 ///
5410 /// This carefully grabs the subprogram from a local scope, avoiding the
5411 /// built-in assertions that would typically fire.
5412 static DISubprogram *getSubprogram(Metadata *LocalScope) {
5413   if (!LocalScope)
5414     return nullptr;
5415 
5416   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
5417     return SP;
5418 
5419   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
5420     return getSubprogram(LB->getRawScope());
5421 
5422   // Just return null; broken scope chains are checked elsewhere.
5423   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
5424   return nullptr;
5425 }
5426 
5427 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5428   unsigned NumOperands;
5429   bool HasRoundingMD;
5430   switch (FPI.getIntrinsicID()) {
5431 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5432   case Intrinsic::INTRINSIC:                                                   \
5433     NumOperands = NARG;                                                        \
5434     HasRoundingMD = ROUND_MODE;                                                \
5435     break;
5436 #include "llvm/IR/ConstrainedOps.def"
5437   default:
5438     llvm_unreachable("Invalid constrained FP intrinsic!");
5439   }
5440   NumOperands += (1 + HasRoundingMD);
5441   // Compare intrinsics carry an extra predicate metadata operand.
5442   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5443     NumOperands += 1;
5444   Assert((FPI.arg_size() == NumOperands),
5445          "invalid arguments for constrained FP intrinsic", &FPI);
5446 
5447   switch (FPI.getIntrinsicID()) {
5448   case Intrinsic::experimental_constrained_lrint:
5449   case Intrinsic::experimental_constrained_llrint: {
5450     Type *ValTy = FPI.getArgOperand(0)->getType();
5451     Type *ResultTy = FPI.getType();
5452     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5453            "Intrinsic does not support vectors", &FPI);
5454   }
5455     break;
5456 
5457   case Intrinsic::experimental_constrained_lround:
5458   case Intrinsic::experimental_constrained_llround: {
5459     Type *ValTy = FPI.getArgOperand(0)->getType();
5460     Type *ResultTy = FPI.getType();
5461     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5462            "Intrinsic does not support vectors", &FPI);
5463     break;
5464   }
5465 
5466   case Intrinsic::experimental_constrained_fcmp:
5467   case Intrinsic::experimental_constrained_fcmps: {
5468     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5469     Assert(CmpInst::isFPPredicate(Pred),
5470            "invalid predicate for constrained FP comparison intrinsic", &FPI);
5471     break;
5472   }
5473 
5474   case Intrinsic::experimental_constrained_fptosi:
5475   case Intrinsic::experimental_constrained_fptoui: {
5476     Value *Operand = FPI.getArgOperand(0);
5477     uint64_t NumSrcElem = 0;
5478     Assert(Operand->getType()->isFPOrFPVectorTy(),
5479            "Intrinsic first argument must be floating point", &FPI);
5480     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5481       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5482     }
5483 
5484     Operand = &FPI;
5485     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5486            "Intrinsic first argument and result disagree on vector use", &FPI);
5487     Assert(Operand->getType()->isIntOrIntVectorTy(),
5488            "Intrinsic result must be an integer", &FPI);
5489     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5490       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5491              "Intrinsic first argument and result vector lengths must be equal",
5492              &FPI);
5493     }
5494   }
5495     break;
5496 
5497   case Intrinsic::experimental_constrained_sitofp:
5498   case Intrinsic::experimental_constrained_uitofp: {
5499     Value *Operand = FPI.getArgOperand(0);
5500     uint64_t NumSrcElem = 0;
5501     Assert(Operand->getType()->isIntOrIntVectorTy(),
5502            "Intrinsic first argument must be integer", &FPI);
5503     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5504       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5505     }
5506 
5507     Operand = &FPI;
5508     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5509            "Intrinsic first argument and result disagree on vector use", &FPI);
5510     Assert(Operand->getType()->isFPOrFPVectorTy(),
5511            "Intrinsic result must be a floating point", &FPI);
5512     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5513       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5514              "Intrinsic first argument and result vector lengths must be equal",
5515              &FPI);
5516     }
5517   } break;
5518 
5519   case Intrinsic::experimental_constrained_fptrunc:
5520   case Intrinsic::experimental_constrained_fpext: {
5521     Value *Operand = FPI.getArgOperand(0);
5522     Type *OperandTy = Operand->getType();
5523     Value *Result = &FPI;
5524     Type *ResultTy = Result->getType();
5525     Assert(OperandTy->isFPOrFPVectorTy(),
5526            "Intrinsic first argument must be FP or FP vector", &FPI);
5527     Assert(ResultTy->isFPOrFPVectorTy(),
5528            "Intrinsic result must be FP or FP vector", &FPI);
5529     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
5530            "Intrinsic first argument and result disagree on vector use", &FPI);
5531     if (OperandTy->isVectorTy()) {
5532       Assert(cast<FixedVectorType>(OperandTy)->getNumElements() ==
5533                  cast<FixedVectorType>(ResultTy)->getNumElements(),
5534              "Intrinsic first argument and result vector lengths must be equal",
5535              &FPI);
5536     }
5537     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
5538       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
5539              "Intrinsic first argument's type must be larger than result type",
5540              &FPI);
5541     } else {
5542       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
5543              "Intrinsic first argument's type must be smaller than result type",
5544              &FPI);
5545     }
5546   }
5547     break;
5548 
5549   default:
5550     break;
5551   }
5552 
5553   // If a non-metadata argument is passed in a metadata slot then the
5554   // error will be caught earlier when the incorrect argument doesn't
5555   // match the specification in the intrinsic call table. Thus, no
5556   // argument type check is needed here.
5557 
5558   Assert(FPI.getExceptionBehavior().hasValue(),
5559          "invalid exception behavior argument", &FPI);
5560   if (HasRoundingMD) {
5561     Assert(FPI.getRoundingMode().hasValue(),
5562            "invalid rounding mode argument", &FPI);
5563   }
5564 }
5565 
5566 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
5567   auto *MD = DII.getRawLocation();
5568   AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
5569                (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
5570            "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
5571   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
5572          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
5573          DII.getRawVariable());
5574   AssertDI(isa<DIExpression>(DII.getRawExpression()),
5575          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
5576          DII.getRawExpression());
5577 
5578   // Ignore broken !dbg attachments; they're checked elsewhere.
5579   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
5580     if (!isa<DILocation>(N))
5581       return;
5582 
5583   BasicBlock *BB = DII.getParent();
5584   Function *F = BB ? BB->getParent() : nullptr;
5585 
5586   // The scopes for variables and !dbg attachments must agree.
5587   DILocalVariable *Var = DII.getVariable();
5588   DILocation *Loc = DII.getDebugLoc();
5589   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5590            &DII, BB, F);
5591 
5592   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
5593   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5594   if (!VarSP || !LocSP)
5595     return; // Broken scope chains are checked elsewhere.
5596 
5597   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5598                                " variable and !dbg attachment",
5599            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
5600            Loc->getScope()->getSubprogram());
5601 
5602   // This check is redundant with one in visitLocalVariable().
5603   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
5604            Var->getRawType());
5605   verifyFnArgs(DII);
5606 }
5607 
5608 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
5609   AssertDI(isa<DILabel>(DLI.getRawLabel()),
5610          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
5611          DLI.getRawLabel());
5612 
5613   // Ignore broken !dbg attachments; they're checked elsewhere.
5614   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
5615     if (!isa<DILocation>(N))
5616       return;
5617 
5618   BasicBlock *BB = DLI.getParent();
5619   Function *F = BB ? BB->getParent() : nullptr;
5620 
5621   // The scopes for variables and !dbg attachments must agree.
5622   DILabel *Label = DLI.getLabel();
5623   DILocation *Loc = DLI.getDebugLoc();
5624   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5625          &DLI, BB, F);
5626 
5627   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
5628   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5629   if (!LabelSP || !LocSP)
5630     return;
5631 
5632   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5633                              " label and !dbg attachment",
5634            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
5635            Loc->getScope()->getSubprogram());
5636 }
5637 
5638 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
5639   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
5640   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5641 
5642   // We don't know whether this intrinsic verified correctly.
5643   if (!V || !E || !E->isValid())
5644     return;
5645 
5646   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
5647   auto Fragment = E->getFragmentInfo();
5648   if (!Fragment)
5649     return;
5650 
5651   // The frontend helps out GDB by emitting the members of local anonymous
5652   // unions as artificial local variables with shared storage. When SROA splits
5653   // the storage for artificial local variables that are smaller than the entire
5654   // union, the overhang piece will be outside of the allotted space for the
5655   // variable and this check fails.
5656   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
5657   if (V->isArtificial())
5658     return;
5659 
5660   verifyFragmentExpression(*V, *Fragment, &I);
5661 }
5662 
5663 template <typename ValueOrMetadata>
5664 void Verifier::verifyFragmentExpression(const DIVariable &V,
5665                                         DIExpression::FragmentInfo Fragment,
5666                                         ValueOrMetadata *Desc) {
5667   // If there's no size, the type is broken, but that should be checked
5668   // elsewhere.
5669   auto VarSize = V.getSizeInBits();
5670   if (!VarSize)
5671     return;
5672 
5673   unsigned FragSize = Fragment.SizeInBits;
5674   unsigned FragOffset = Fragment.OffsetInBits;
5675   AssertDI(FragSize + FragOffset <= *VarSize,
5676          "fragment is larger than or outside of variable", Desc, &V);
5677   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
5678 }
5679 
5680 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
5681   // This function does not take the scope of noninlined function arguments into
5682   // account. Don't run it if current function is nodebug, because it may
5683   // contain inlined debug intrinsics.
5684   if (!HasDebugInfo)
5685     return;
5686 
5687   // For performance reasons only check non-inlined ones.
5688   if (I.getDebugLoc()->getInlinedAt())
5689     return;
5690 
5691   DILocalVariable *Var = I.getVariable();
5692   AssertDI(Var, "dbg intrinsic without variable");
5693 
5694   unsigned ArgNo = Var->getArg();
5695   if (!ArgNo)
5696     return;
5697 
5698   // Verify there are no duplicate function argument debug info entries.
5699   // These will cause hard-to-debug assertions in the DWARF backend.
5700   if (DebugFnArgs.size() < ArgNo)
5701     DebugFnArgs.resize(ArgNo, nullptr);
5702 
5703   auto *Prev = DebugFnArgs[ArgNo - 1];
5704   DebugFnArgs[ArgNo - 1] = Var;
5705   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
5706            Prev, Var);
5707 }
5708 
5709 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
5710   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5711 
5712   // We don't know whether this intrinsic verified correctly.
5713   if (!E || !E->isValid())
5714     return;
5715 
5716   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
5717 }
5718 
5719 void Verifier::verifyCompileUnits() {
5720   // When more than one Module is imported into the same context, such as during
5721   // an LTO build before linking the modules, ODR type uniquing may cause types
5722   // to point to a different CU. This check does not make sense in this case.
5723   if (M.getContext().isODRUniquingDebugTypes())
5724     return;
5725   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
5726   SmallPtrSet<const Metadata *, 2> Listed;
5727   if (CUs)
5728     Listed.insert(CUs->op_begin(), CUs->op_end());
5729   for (auto *CU : CUVisited)
5730     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
5731   CUVisited.clear();
5732 }
5733 
5734 void Verifier::verifyDeoptimizeCallingConvs() {
5735   if (DeoptimizeDeclarations.empty())
5736     return;
5737 
5738   const Function *First = DeoptimizeDeclarations[0];
5739   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
5740     Assert(First->getCallingConv() == F->getCallingConv(),
5741            "All llvm.experimental.deoptimize declarations must have the same "
5742            "calling convention",
5743            First, F);
5744   }
5745 }
5746 
5747 void Verifier::verifyAttachedCallBundle(const CallBase &Call,
5748                                         const OperandBundleUse &BU) {
5749   FunctionType *FTy = Call.getFunctionType();
5750 
5751   Assert((FTy->getReturnType()->isPointerTy() ||
5752           (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
5753          "a call with operand bundle \"clang.arc.attachedcall\" must call a "
5754          "function returning a pointer or a non-returning function that has a "
5755          "void return type",
5756          Call);
5757 
5758   Assert((BU.Inputs.empty() ||
5759           (BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()))),
5760          "operand bundle \"clang.arc.attachedcall\" can take either no "
5761          "arguments or one function as an argument",
5762          Call);
5763 
5764   if (BU.Inputs.empty())
5765     return;
5766 
5767   auto *Fn = cast<Function>(BU.Inputs.front());
5768   Intrinsic::ID IID = Fn->getIntrinsicID();
5769 
5770   if (IID) {
5771     Assert((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
5772             IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
5773            "invalid function argument", Call);
5774   } else {
5775     StringRef FnName = Fn->getName();
5776     Assert((FnName == "objc_retainAutoreleasedReturnValue" ||
5777             FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
5778            "invalid function argument", Call);
5779   }
5780 }
5781 
5782 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
5783   bool HasSource = F.getSource().hasValue();
5784   if (!HasSourceDebugInfo.count(&U))
5785     HasSourceDebugInfo[&U] = HasSource;
5786   AssertDI(HasSource == HasSourceDebugInfo[&U],
5787            "inconsistent use of embedded source");
5788 }
5789 
5790 void Verifier::verifyNoAliasScopeDecl() {
5791   if (NoAliasScopeDecls.empty())
5792     return;
5793 
5794   // only a single scope must be declared at a time.
5795   for (auto *II : NoAliasScopeDecls) {
5796     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
5797            "Not a llvm.experimental.noalias.scope.decl ?");
5798     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
5799         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5800     Assert(ScopeListMV != nullptr,
5801            "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
5802            "argument",
5803            II);
5804 
5805     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
5806     Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode",
5807            II);
5808     Assert(ScopeListMD->getNumOperands() == 1,
5809            "!id.scope.list must point to a list with a single scope", II);
5810     visitAliasScopeListMetadata(ScopeListMD);
5811   }
5812 
5813   // Only check the domination rule when requested. Once all passes have been
5814   // adapted this option can go away.
5815   if (!VerifyNoAliasScopeDomination)
5816     return;
5817 
5818   // Now sort the intrinsics based on the scope MDNode so that declarations of
5819   // the same scopes are next to each other.
5820   auto GetScope = [](IntrinsicInst *II) {
5821     const auto *ScopeListMV = cast<MetadataAsValue>(
5822         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5823     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
5824   };
5825 
5826   // We are sorting on MDNode pointers here. For valid input IR this is ok.
5827   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
5828   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
5829     return GetScope(Lhs) < GetScope(Rhs);
5830   };
5831 
5832   llvm::sort(NoAliasScopeDecls, Compare);
5833 
5834   // Go over the intrinsics and check that for the same scope, they are not
5835   // dominating each other.
5836   auto ItCurrent = NoAliasScopeDecls.begin();
5837   while (ItCurrent != NoAliasScopeDecls.end()) {
5838     auto CurScope = GetScope(*ItCurrent);
5839     auto ItNext = ItCurrent;
5840     do {
5841       ++ItNext;
5842     } while (ItNext != NoAliasScopeDecls.end() &&
5843              GetScope(*ItNext) == CurScope);
5844 
5845     // [ItCurrent, ItNext) represents the declarations for the same scope.
5846     // Ensure they are not dominating each other.. but only if it is not too
5847     // expensive.
5848     if (ItNext - ItCurrent < 32)
5849       for (auto *I : llvm::make_range(ItCurrent, ItNext))
5850         for (auto *J : llvm::make_range(ItCurrent, ItNext))
5851           if (I != J)
5852             Assert(!DT.dominates(I, J),
5853                    "llvm.experimental.noalias.scope.decl dominates another one "
5854                    "with the same scope",
5855                    I);
5856     ItCurrent = ItNext;
5857   }
5858 }
5859 
5860 //===----------------------------------------------------------------------===//
5861 //  Implement the public interfaces to this file...
5862 //===----------------------------------------------------------------------===//
5863 
5864 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
5865   Function &F = const_cast<Function &>(f);
5866 
5867   // Don't use a raw_null_ostream.  Printing IR is expensive.
5868   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
5869 
5870   // Note that this function's return value is inverted from what you would
5871   // expect of a function called "verify".
5872   return !V.verify(F);
5873 }
5874 
5875 bool llvm::verifyModule(const Module &M, raw_ostream *OS,
5876                         bool *BrokenDebugInfo) {
5877   // Don't use a raw_null_ostream.  Printing IR is expensive.
5878   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
5879 
5880   bool Broken = false;
5881   for (const Function &F : M)
5882     Broken |= !V.verify(F);
5883 
5884   Broken |= !V.verify();
5885   if (BrokenDebugInfo)
5886     *BrokenDebugInfo = V.hasBrokenDebugInfo();
5887   // Note that this function's return value is inverted from what you would
5888   // expect of a function called "verify".
5889   return Broken;
5890 }
5891 
5892 namespace {
5893 
5894 struct VerifierLegacyPass : public FunctionPass {
5895   static char ID;
5896 
5897   std::unique_ptr<Verifier> V;
5898   bool FatalErrors = true;
5899 
5900   VerifierLegacyPass() : FunctionPass(ID) {
5901     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5902   }
5903   explicit VerifierLegacyPass(bool FatalErrors)
5904       : FunctionPass(ID),
5905         FatalErrors(FatalErrors) {
5906     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5907   }
5908 
5909   bool doInitialization(Module &M) override {
5910     V = std::make_unique<Verifier>(
5911         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
5912     return false;
5913   }
5914 
5915   bool runOnFunction(Function &F) override {
5916     if (!V->verify(F) && FatalErrors) {
5917       errs() << "in function " << F.getName() << '\n';
5918       report_fatal_error("Broken function found, compilation aborted!");
5919     }
5920     return false;
5921   }
5922 
5923   bool doFinalization(Module &M) override {
5924     bool HasErrors = false;
5925     for (Function &F : M)
5926       if (F.isDeclaration())
5927         HasErrors |= !V->verify(F);
5928 
5929     HasErrors |= !V->verify();
5930     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
5931       report_fatal_error("Broken module found, compilation aborted!");
5932     return false;
5933   }
5934 
5935   void getAnalysisUsage(AnalysisUsage &AU) const override {
5936     AU.setPreservesAll();
5937   }
5938 };
5939 
5940 } // end anonymous namespace
5941 
5942 /// Helper to issue failure from the TBAA verification
5943 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
5944   if (Diagnostic)
5945     return Diagnostic->CheckFailed(Args...);
5946 }
5947 
5948 #define AssertTBAA(C, ...)                                                     \
5949   do {                                                                         \
5950     if (!(C)) {                                                                \
5951       CheckFailed(__VA_ARGS__);                                                \
5952       return false;                                                            \
5953     }                                                                          \
5954   } while (false)
5955 
5956 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
5957 /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
5958 /// struct-type node describing an aggregate data structure (like a struct).
5959 TBAAVerifier::TBAABaseNodeSummary
5960 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
5961                                  bool IsNewFormat) {
5962   if (BaseNode->getNumOperands() < 2) {
5963     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
5964     return {true, ~0u};
5965   }
5966 
5967   auto Itr = TBAABaseNodes.find(BaseNode);
5968   if (Itr != TBAABaseNodes.end())
5969     return Itr->second;
5970 
5971   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
5972   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
5973   (void)InsertResult;
5974   assert(InsertResult.second && "We just checked!");
5975   return Result;
5976 }
5977 
5978 TBAAVerifier::TBAABaseNodeSummary
5979 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
5980                                      bool IsNewFormat) {
5981   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
5982 
5983   if (BaseNode->getNumOperands() == 2) {
5984     // Scalar nodes can only be accessed at offset 0.
5985     return isValidScalarTBAANode(BaseNode)
5986                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
5987                : InvalidNode;
5988   }
5989 
5990   if (IsNewFormat) {
5991     if (BaseNode->getNumOperands() % 3 != 0) {
5992       CheckFailed("Access tag nodes must have the number of operands that is a "
5993                   "multiple of 3!", BaseNode);
5994       return InvalidNode;
5995     }
5996   } else {
5997     if (BaseNode->getNumOperands() % 2 != 1) {
5998       CheckFailed("Struct tag nodes must have an odd number of operands!",
5999                   BaseNode);
6000       return InvalidNode;
6001     }
6002   }
6003 
6004   // Check the type size field.
6005   if (IsNewFormat) {
6006     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6007         BaseNode->getOperand(1));
6008     if (!TypeSizeNode) {
6009       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
6010       return InvalidNode;
6011     }
6012   }
6013 
6014   // Check the type name field. In the new format it can be anything.
6015   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
6016     CheckFailed("Struct tag nodes have a string as their first operand",
6017                 BaseNode);
6018     return InvalidNode;
6019   }
6020 
6021   bool Failed = false;
6022 
6023   Optional<APInt> PrevOffset;
6024   unsigned BitWidth = ~0u;
6025 
6026   // We've already checked that BaseNode is not a degenerate root node with one
6027   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
6028   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6029   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6030   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6031            Idx += NumOpsPerField) {
6032     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
6033     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
6034     if (!isa<MDNode>(FieldTy)) {
6035       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
6036       Failed = true;
6037       continue;
6038     }
6039 
6040     auto *OffsetEntryCI =
6041         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
6042     if (!OffsetEntryCI) {
6043       CheckFailed("Offset entries must be constants!", &I, BaseNode);
6044       Failed = true;
6045       continue;
6046     }
6047 
6048     if (BitWidth == ~0u)
6049       BitWidth = OffsetEntryCI->getBitWidth();
6050 
6051     if (OffsetEntryCI->getBitWidth() != BitWidth) {
6052       CheckFailed(
6053           "Bitwidth between the offsets and struct type entries must match", &I,
6054           BaseNode);
6055       Failed = true;
6056       continue;
6057     }
6058 
6059     // NB! As far as I can tell, we generate a non-strictly increasing offset
6060     // sequence only from structs that have zero size bit fields.  When
6061     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
6062     // pick the field lexically the latest in struct type metadata node.  This
6063     // mirrors the actual behavior of the alias analysis implementation.
6064     bool IsAscending =
6065         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
6066 
6067     if (!IsAscending) {
6068       CheckFailed("Offsets must be increasing!", &I, BaseNode);
6069       Failed = true;
6070     }
6071 
6072     PrevOffset = OffsetEntryCI->getValue();
6073 
6074     if (IsNewFormat) {
6075       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6076           BaseNode->getOperand(Idx + 2));
6077       if (!MemberSizeNode) {
6078         CheckFailed("Member size entries must be constants!", &I, BaseNode);
6079         Failed = true;
6080         continue;
6081       }
6082     }
6083   }
6084 
6085   return Failed ? InvalidNode
6086                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
6087 }
6088 
6089 static bool IsRootTBAANode(const MDNode *MD) {
6090   return MD->getNumOperands() < 2;
6091 }
6092 
6093 static bool IsScalarTBAANodeImpl(const MDNode *MD,
6094                                  SmallPtrSetImpl<const MDNode *> &Visited) {
6095   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
6096     return false;
6097 
6098   if (!isa<MDString>(MD->getOperand(0)))
6099     return false;
6100 
6101   if (MD->getNumOperands() == 3) {
6102     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
6103     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
6104       return false;
6105   }
6106 
6107   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6108   return Parent && Visited.insert(Parent).second &&
6109          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
6110 }
6111 
6112 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
6113   auto ResultIt = TBAAScalarNodes.find(MD);
6114   if (ResultIt != TBAAScalarNodes.end())
6115     return ResultIt->second;
6116 
6117   SmallPtrSet<const MDNode *, 4> Visited;
6118   bool Result = IsScalarTBAANodeImpl(MD, Visited);
6119   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
6120   (void)InsertResult;
6121   assert(InsertResult.second && "Just checked!");
6122 
6123   return Result;
6124 }
6125 
6126 /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
6127 /// Offset in place to be the offset within the field node returned.
6128 ///
6129 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
6130 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
6131                                                    const MDNode *BaseNode,
6132                                                    APInt &Offset,
6133                                                    bool IsNewFormat) {
6134   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
6135 
6136   // Scalar nodes have only one possible "field" -- their parent in the access
6137   // hierarchy.  Offset must be zero at this point, but our caller is supposed
6138   // to Assert that.
6139   if (BaseNode->getNumOperands() == 2)
6140     return cast<MDNode>(BaseNode->getOperand(1));
6141 
6142   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6143   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6144   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6145            Idx += NumOpsPerField) {
6146     auto *OffsetEntryCI =
6147         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
6148     if (OffsetEntryCI->getValue().ugt(Offset)) {
6149       if (Idx == FirstFieldOpNo) {
6150         CheckFailed("Could not find TBAA parent in struct type node", &I,
6151                     BaseNode, &Offset);
6152         return nullptr;
6153       }
6154 
6155       unsigned PrevIdx = Idx - NumOpsPerField;
6156       auto *PrevOffsetEntryCI =
6157           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
6158       Offset -= PrevOffsetEntryCI->getValue();
6159       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
6160     }
6161   }
6162 
6163   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
6164   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
6165       BaseNode->getOperand(LastIdx + 1));
6166   Offset -= LastOffsetEntryCI->getValue();
6167   return cast<MDNode>(BaseNode->getOperand(LastIdx));
6168 }
6169 
6170 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
6171   if (!Type || Type->getNumOperands() < 3)
6172     return false;
6173 
6174   // In the new format type nodes shall have a reference to the parent type as
6175   // its first operand.
6176   return isa_and_nonnull<MDNode>(Type->getOperand(0));
6177 }
6178 
6179 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
6180   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
6181                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
6182                  isa<AtomicCmpXchgInst>(I),
6183              "This instruction shall not have a TBAA access tag!", &I);
6184 
6185   bool IsStructPathTBAA =
6186       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
6187 
6188   AssertTBAA(
6189       IsStructPathTBAA,
6190       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
6191 
6192   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
6193   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6194 
6195   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
6196 
6197   if (IsNewFormat) {
6198     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
6199                "Access tag metadata must have either 4 or 5 operands", &I, MD);
6200   } else {
6201     AssertTBAA(MD->getNumOperands() < 5,
6202                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
6203   }
6204 
6205   // Check the access size field.
6206   if (IsNewFormat) {
6207     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6208         MD->getOperand(3));
6209     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
6210   }
6211 
6212   // Check the immutability flag.
6213   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
6214   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
6215     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
6216         MD->getOperand(ImmutabilityFlagOpNo));
6217     AssertTBAA(IsImmutableCI,
6218                "Immutability tag on struct tag metadata must be a constant",
6219                &I, MD);
6220     AssertTBAA(
6221         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
6222         "Immutability part of the struct tag metadata must be either 0 or 1",
6223         &I, MD);
6224   }
6225 
6226   AssertTBAA(BaseNode && AccessType,
6227              "Malformed struct tag metadata: base and access-type "
6228              "should be non-null and point to Metadata nodes",
6229              &I, MD, BaseNode, AccessType);
6230 
6231   if (!IsNewFormat) {
6232     AssertTBAA(isValidScalarTBAANode(AccessType),
6233                "Access type node must be a valid scalar type", &I, MD,
6234                AccessType);
6235   }
6236 
6237   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
6238   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
6239 
6240   APInt Offset = OffsetCI->getValue();
6241   bool SeenAccessTypeInPath = false;
6242 
6243   SmallPtrSet<MDNode *, 4> StructPath;
6244 
6245   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
6246        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
6247                                                IsNewFormat)) {
6248     if (!StructPath.insert(BaseNode).second) {
6249       CheckFailed("Cycle detected in struct path", &I, MD);
6250       return false;
6251     }
6252 
6253     bool Invalid;
6254     unsigned BaseNodeBitWidth;
6255     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
6256                                                              IsNewFormat);
6257 
6258     // If the base node is invalid in itself, then we've already printed all the
6259     // errors we wanted to print.
6260     if (Invalid)
6261       return false;
6262 
6263     SeenAccessTypeInPath |= BaseNode == AccessType;
6264 
6265     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
6266       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
6267                  &I, MD, &Offset);
6268 
6269     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
6270                    (BaseNodeBitWidth == 0 && Offset == 0) ||
6271                    (IsNewFormat && BaseNodeBitWidth == ~0u),
6272                "Access bit-width not the same as description bit-width", &I, MD,
6273                BaseNodeBitWidth, Offset.getBitWidth());
6274 
6275     if (IsNewFormat && SeenAccessTypeInPath)
6276       break;
6277   }
6278 
6279   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
6280              &I, MD);
6281   return true;
6282 }
6283 
6284 char VerifierLegacyPass::ID = 0;
6285 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
6286 
6287 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
6288   return new VerifierLegacyPass(FatalErrors);
6289 }
6290 
6291 AnalysisKey VerifierAnalysis::Key;
6292 VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
6293                                                ModuleAnalysisManager &) {
6294   Result Res;
6295   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
6296   return Res;
6297 }
6298 
6299 VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
6300                                                FunctionAnalysisManager &) {
6301   return { llvm::verifyFunction(F, &dbgs()), false };
6302 }
6303 
6304 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
6305   auto Res = AM.getResult<VerifierAnalysis>(M);
6306   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
6307     report_fatal_error("Broken module found, compilation aborted!");
6308 
6309   return PreservedAnalyses::all();
6310 }
6311 
6312 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
6313   auto res = AM.getResult<VerifierAnalysis>(F);
6314   if (res.IRBroken && FatalErrors)
6315     report_fatal_error("Broken function found, compilation aborted!");
6316 
6317   return PreservedAnalyses::all();
6318 }
6319