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