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