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