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