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