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