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