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