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