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