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