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