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