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