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