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