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