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