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