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