Macro debug info support in LLVM IR
[oota-llvm.git] / lib / IR / Verifier.cpp
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/STLExtras.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/CallSite.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/ConstantRange.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DebugInfo.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/Dominators.h"
62 #include "llvm/IR/InlineAsm.h"
63 #include "llvm/IR/InstIterator.h"
64 #include "llvm/IR/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/IR/Statepoint.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
81
82 namespace {
83 struct VerifierSupport {
84   raw_ostream &OS;
85   const Module *M;
86
87   /// \brief Track the brokenness of the module while recursively visiting.
88   bool Broken;
89
90   explicit VerifierSupport(raw_ostream &OS)
91       : OS(OS), M(nullptr), Broken(false) {}
92
93 private:
94   template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
95     Write(&*I);
96   }
97
98   void Write(const Module *M) {
99     if (!M)
100       return;
101     OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
102   }
103
104   void Write(const Value *V) {
105     if (!V)
106       return;
107     if (isa<Instruction>(V)) {
108       OS << *V << '\n';
109     } else {
110       V->printAsOperand(OS, true, M);
111       OS << '\n';
112     }
113   }
114   void Write(ImmutableCallSite CS) {
115     Write(CS.getInstruction());
116   }
117
118   void Write(const Metadata *MD) {
119     if (!MD)
120       return;
121     MD->print(OS, M);
122     OS << '\n';
123   }
124
125   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
126     Write(MD.get());
127   }
128
129   void Write(const NamedMDNode *NMD) {
130     if (!NMD)
131       return;
132     NMD->print(OS);
133     OS << '\n';
134   }
135
136   void Write(Type *T) {
137     if (!T)
138       return;
139     OS << ' ' << *T;
140   }
141
142   void Write(const Comdat *C) {
143     if (!C)
144       return;
145     OS << *C;
146   }
147
148   template <typename T1, typename... Ts>
149   void WriteTs(const T1 &V1, const Ts &... Vs) {
150     Write(V1);
151     WriteTs(Vs...);
152   }
153
154   template <typename... Ts> void WriteTs() {}
155
156 public:
157   /// \brief A check failed, so printout out the condition and the message.
158   ///
159   /// This provides a nice place to put a breakpoint if you want to see why
160   /// something is not correct.
161   void CheckFailed(const Twine &Message) {
162     OS << Message << '\n';
163     Broken = true;
164   }
165
166   /// \brief A check failed (with values to print).
167   ///
168   /// This calls the Message-only version so that the above is easier to set a
169   /// breakpoint on.
170   template <typename T1, typename... Ts>
171   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
172     CheckFailed(Message);
173     WriteTs(V1, Vs...);
174   }
175 };
176
177 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
178   friend class InstVisitor<Verifier>;
179
180   LLVMContext *Context;
181   DominatorTree DT;
182
183   /// \brief When verifying a basic block, keep track of all of the
184   /// instructions we have seen so far.
185   ///
186   /// This allows us to do efficient dominance checks for the case when an
187   /// instruction has an operand that is an instruction in the same block.
188   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
189
190   /// \brief Keep track of the metadata nodes that have been checked already.
191   SmallPtrSet<const Metadata *, 32> MDNodes;
192
193   /// \brief Track unresolved string-based type references.
194   SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
195
196   /// \brief The result type for a landingpad.
197   Type *LandingPadResultTy;
198
199   /// \brief Whether we've seen a call to @llvm.localescape in this function
200   /// already.
201   bool SawFrameEscape;
202
203   /// Stores the count of how many objects were passed to llvm.localescape for a
204   /// given function and the largest index passed to llvm.localrecover.
205   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
206
207 public:
208   explicit Verifier(raw_ostream &OS)
209       : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
210         SawFrameEscape(false) {}
211
212   bool verify(const Function &F) {
213     M = F.getParent();
214     Context = &M->getContext();
215
216     // First ensure the function is well-enough formed to compute dominance
217     // information.
218     if (F.empty()) {
219       OS << "Function '" << F.getName()
220          << "' does not contain an entry block!\n";
221       return false;
222     }
223     for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
224       if (I->empty() || !I->back().isTerminator()) {
225         OS << "Basic Block in function '" << F.getName()
226            << "' does not have terminator!\n";
227         I->printAsOperand(OS, true);
228         OS << "\n";
229         return false;
230       }
231     }
232
233     // Now directly compute a dominance tree. We don't rely on the pass
234     // manager to provide this as it isolates us from a potentially
235     // out-of-date dominator tree and makes it significantly more complex to
236     // run this code outside of a pass manager.
237     // FIXME: It's really gross that we have to cast away constness here.
238     DT.recalculate(const_cast<Function &>(F));
239
240     Broken = false;
241     // FIXME: We strip const here because the inst visitor strips const.
242     visit(const_cast<Function &>(F));
243     InstsInThisBlock.clear();
244     LandingPadResultTy = nullptr;
245     SawFrameEscape = false;
246
247     return !Broken;
248   }
249
250   bool verify(const Module &M) {
251     this->M = &M;
252     Context = &M.getContext();
253     Broken = false;
254
255     // Scan through, checking all of the external function's linkage now...
256     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
257       visitGlobalValue(*I);
258
259       // Check to make sure function prototypes are okay.
260       if (I->isDeclaration())
261         visitFunction(*I);
262     }
263
264     // Now that we've visited every function, verify that we never asked to
265     // recover a frame index that wasn't escaped.
266     verifyFrameRecoverIndices();
267
268     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
269          I != E; ++I)
270       visitGlobalVariable(*I);
271
272     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
273          I != E; ++I)
274       visitGlobalAlias(*I);
275
276     for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
277                                                E = M.named_metadata_end();
278          I != E; ++I)
279       visitNamedMDNode(*I);
280
281     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
282       visitComdat(SMEC.getValue());
283
284     visitModuleFlags(M);
285     visitModuleIdents(M);
286
287     // Verify type referneces last.
288     verifyTypeRefs();
289
290     return !Broken;
291   }
292
293 private:
294   // Verification methods...
295   void visitGlobalValue(const GlobalValue &GV);
296   void visitGlobalVariable(const GlobalVariable &GV);
297   void visitGlobalAlias(const GlobalAlias &GA);
298   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
299   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
300                            const GlobalAlias &A, const Constant &C);
301   void visitNamedMDNode(const NamedMDNode &NMD);
302   void visitMDNode(const MDNode &MD);
303   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
304   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
305   void visitComdat(const Comdat &C);
306   void visitModuleIdents(const Module &M);
307   void visitModuleFlags(const Module &M);
308   void visitModuleFlag(const MDNode *Op,
309                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
310                        SmallVectorImpl<const MDNode *> &Requirements);
311   void visitFunction(const Function &F);
312   void visitBasicBlock(BasicBlock &BB);
313   void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
314   void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
315
316   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
317 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
318 #include "llvm/IR/Metadata.def"
319   void visitDIScope(const DIScope &N);
320   void visitDIVariable(const DIVariable &N);
321   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
322   void visitDITemplateParameter(const DITemplateParameter &N);
323
324   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
325
326   /// \brief Check for a valid string-based type reference.
327   ///
328   /// Checks if \c MD is a string-based type reference.  If it is, keeps track
329   /// of it (and its user, \c N) for error messages later.
330   bool isValidUUID(const MDNode &N, const Metadata *MD);
331
332   /// \brief Check for a valid type reference.
333   ///
334   /// Checks for subclasses of \a DIType, or \a isValidUUID().
335   bool isTypeRef(const MDNode &N, const Metadata *MD);
336
337   /// \brief Check for a valid scope reference.
338   ///
339   /// Checks for subclasses of \a DIScope, or \a isValidUUID().
340   bool isScopeRef(const MDNode &N, const Metadata *MD);
341
342   /// \brief Check for a valid debug info reference.
343   ///
344   /// Checks for subclasses of \a DINode, or \a isValidUUID().
345   bool isDIRef(const MDNode &N, const Metadata *MD);
346
347   // InstVisitor overrides...
348   using InstVisitor<Verifier>::visit;
349   void visit(Instruction &I);
350
351   void visitTruncInst(TruncInst &I);
352   void visitZExtInst(ZExtInst &I);
353   void visitSExtInst(SExtInst &I);
354   void visitFPTruncInst(FPTruncInst &I);
355   void visitFPExtInst(FPExtInst &I);
356   void visitFPToUIInst(FPToUIInst &I);
357   void visitFPToSIInst(FPToSIInst &I);
358   void visitUIToFPInst(UIToFPInst &I);
359   void visitSIToFPInst(SIToFPInst &I);
360   void visitIntToPtrInst(IntToPtrInst &I);
361   void visitPtrToIntInst(PtrToIntInst &I);
362   void visitBitCastInst(BitCastInst &I);
363   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
364   void visitPHINode(PHINode &PN);
365   void visitBinaryOperator(BinaryOperator &B);
366   void visitICmpInst(ICmpInst &IC);
367   void visitFCmpInst(FCmpInst &FC);
368   void visitExtractElementInst(ExtractElementInst &EI);
369   void visitInsertElementInst(InsertElementInst &EI);
370   void visitShuffleVectorInst(ShuffleVectorInst &EI);
371   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
372   void visitCallInst(CallInst &CI);
373   void visitInvokeInst(InvokeInst &II);
374   void visitGetElementPtrInst(GetElementPtrInst &GEP);
375   void visitLoadInst(LoadInst &LI);
376   void visitStoreInst(StoreInst &SI);
377   void verifyDominatesUse(Instruction &I, unsigned i);
378   void visitInstruction(Instruction &I);
379   void visitTerminatorInst(TerminatorInst &I);
380   void visitBranchInst(BranchInst &BI);
381   void visitReturnInst(ReturnInst &RI);
382   void visitSwitchInst(SwitchInst &SI);
383   void visitIndirectBrInst(IndirectBrInst &BI);
384   void visitSelectInst(SelectInst &SI);
385   void visitUserOp1(Instruction &I);
386   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
387   void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
388   template <class DbgIntrinsicTy>
389   void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
390   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
391   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
392   void visitFenceInst(FenceInst &FI);
393   void visitAllocaInst(AllocaInst &AI);
394   void visitExtractValueInst(ExtractValueInst &EVI);
395   void visitInsertValueInst(InsertValueInst &IVI);
396   void visitEHPadPredecessors(Instruction &I);
397   void visitLandingPadInst(LandingPadInst &LPI);
398   void visitCatchPadInst(CatchPadInst &CPI);
399   void visitCatchEndPadInst(CatchEndPadInst &CEPI);
400   void visitCleanupPadInst(CleanupPadInst &CPI);
401   void visitCleanupEndPadInst(CleanupEndPadInst &CEPI);
402   void visitCleanupReturnInst(CleanupReturnInst &CRI);
403   void visitTerminatePadInst(TerminatePadInst &TPI);
404
405   void VerifyCallSite(CallSite CS);
406   void verifyMustTailCall(CallInst &CI);
407   bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
408                         unsigned ArgNo, std::string &Suffix);
409   bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
410                            SmallVectorImpl<Type *> &ArgTys);
411   bool VerifyIntrinsicIsVarArg(bool isVarArg,
412                                ArrayRef<Intrinsic::IITDescriptor> &Infos);
413   bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
414   void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
415                             const Value *V);
416   void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
417                             bool isReturnValue, const Value *V);
418   void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
419                            const Value *V);
420   void VerifyFunctionMetadata(
421       const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
422
423   void VerifyConstantExprBitcastType(const ConstantExpr *CE);
424   void VerifyStatepoint(ImmutableCallSite CS);
425   void verifyFrameRecoverIndices();
426
427   // Module-level debug info verification...
428   void verifyTypeRefs();
429   template <class MapTy>
430   void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
431                                 const MapTy &TypeRefs);
432   void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
433 };
434 } // End anonymous namespace
435
436 // Assert - We know that cond should be true, if not print an error message.
437 #define Assert(C, ...) \
438   do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
439
440 void Verifier::visit(Instruction &I) {
441   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
442     Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
443   InstVisitor<Verifier>::visit(I);
444 }
445
446
447 void Verifier::visitGlobalValue(const GlobalValue &GV) {
448   Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
449              GV.hasExternalWeakLinkage(),
450          "Global is external, but doesn't have external or weak linkage!", &GV);
451
452   Assert(GV.getAlignment() <= Value::MaximumAlignment,
453          "huge alignment values are unsupported", &GV);
454   Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
455          "Only global variables can have appending linkage!", &GV);
456
457   if (GV.hasAppendingLinkage()) {
458     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
459     Assert(GVar && GVar->getValueType()->isArrayTy(),
460            "Only global arrays can have appending linkage!", GVar);
461   }
462
463   if (GV.isDeclarationForLinker())
464     Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
465 }
466
467 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
468   if (GV.hasInitializer()) {
469     Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
470            "Global variable initializer type does not match global "
471            "variable type!",
472            &GV);
473
474     // If the global has common linkage, it must have a zero initializer and
475     // cannot be constant.
476     if (GV.hasCommonLinkage()) {
477       Assert(GV.getInitializer()->isNullValue(),
478              "'common' global must have a zero initializer!", &GV);
479       Assert(!GV.isConstant(), "'common' global may not be marked constant!",
480              &GV);
481       Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
482     }
483   } else {
484     Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
485            "invalid linkage type for global declaration", &GV);
486   }
487
488   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
489                        GV.getName() == "llvm.global_dtors")) {
490     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
491            "invalid linkage for intrinsic global variable", &GV);
492     // Don't worry about emitting an error for it not being an array,
493     // visitGlobalValue will complain on appending non-array.
494     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
495       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
496       PointerType *FuncPtrTy =
497           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
498       // FIXME: Reject the 2-field form in LLVM 4.0.
499       Assert(STy &&
500                  (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
501                  STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
502                  STy->getTypeAtIndex(1) == FuncPtrTy,
503              "wrong type for intrinsic global variable", &GV);
504       if (STy->getNumElements() == 3) {
505         Type *ETy = STy->getTypeAtIndex(2);
506         Assert(ETy->isPointerTy() &&
507                    cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
508                "wrong type for intrinsic global variable", &GV);
509       }
510     }
511   }
512
513   if (GV.hasName() && (GV.getName() == "llvm.used" ||
514                        GV.getName() == "llvm.compiler.used")) {
515     Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
516            "invalid linkage for intrinsic global variable", &GV);
517     Type *GVType = GV.getValueType();
518     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
519       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
520       Assert(PTy, "wrong type for intrinsic global variable", &GV);
521       if (GV.hasInitializer()) {
522         const Constant *Init = GV.getInitializer();
523         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
524         Assert(InitArray, "wrong initalizer for intrinsic global variable",
525                Init);
526         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
527           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
528           Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
529                      isa<GlobalAlias>(V),
530                  "invalid llvm.used member", V);
531           Assert(V->hasName(), "members of llvm.used must be named", V);
532         }
533       }
534     }
535   }
536
537   Assert(!GV.hasDLLImportStorageClass() ||
538              (GV.isDeclaration() && GV.hasExternalLinkage()) ||
539              GV.hasAvailableExternallyLinkage(),
540          "Global is marked as dllimport, but not external", &GV);
541
542   if (!GV.hasInitializer()) {
543     visitGlobalValue(GV);
544     return;
545   }
546
547   // Walk any aggregate initializers looking for bitcasts between address spaces
548   SmallPtrSet<const Value *, 4> Visited;
549   SmallVector<const Value *, 4> WorkStack;
550   WorkStack.push_back(cast<Value>(GV.getInitializer()));
551
552   while (!WorkStack.empty()) {
553     const Value *V = WorkStack.pop_back_val();
554     if (!Visited.insert(V).second)
555       continue;
556
557     if (const User *U = dyn_cast<User>(V)) {
558       WorkStack.append(U->op_begin(), U->op_end());
559     }
560
561     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
562       VerifyConstantExprBitcastType(CE);
563       if (Broken)
564         return;
565     }
566   }
567
568   visitGlobalValue(GV);
569 }
570
571 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
572   SmallPtrSet<const GlobalAlias*, 4> Visited;
573   Visited.insert(&GA);
574   visitAliaseeSubExpr(Visited, GA, C);
575 }
576
577 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
578                                    const GlobalAlias &GA, const Constant &C) {
579   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
580     Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
581            &GA);
582
583     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
584       Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
585
586       Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
587              &GA);
588     } else {
589       // Only continue verifying subexpressions of GlobalAliases.
590       // Do not recurse into global initializers.
591       return;
592     }
593   }
594
595   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
596     VerifyConstantExprBitcastType(CE);
597
598   for (const Use &U : C.operands()) {
599     Value *V = &*U;
600     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
601       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
602     else if (const auto *C2 = dyn_cast<Constant>(V))
603       visitAliaseeSubExpr(Visited, GA, *C2);
604   }
605 }
606
607 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
608   Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
609          "Alias should have private, internal, linkonce, weak, linkonce_odr, "
610          "weak_odr, or external linkage!",
611          &GA);
612   const Constant *Aliasee = GA.getAliasee();
613   Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
614   Assert(GA.getType() == Aliasee->getType(),
615          "Alias and aliasee types should match!", &GA);
616
617   Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
618          "Aliasee should be either GlobalValue or ConstantExpr", &GA);
619
620   visitAliaseeSubExpr(GA, *Aliasee);
621
622   visitGlobalValue(GA);
623 }
624
625 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
626   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
627     MDNode *MD = NMD.getOperand(i);
628
629     if (NMD.getName() == "llvm.dbg.cu") {
630       Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
631     }
632
633     if (!MD)
634       continue;
635
636     visitMDNode(*MD);
637   }
638 }
639
640 void Verifier::visitMDNode(const MDNode &MD) {
641   // Only visit each node once.  Metadata can be mutually recursive, so this
642   // avoids infinite recursion here, as well as being an optimization.
643   if (!MDNodes.insert(&MD).second)
644     return;
645
646   switch (MD.getMetadataID()) {
647   default:
648     llvm_unreachable("Invalid MDNode subclass");
649   case Metadata::MDTupleKind:
650     break;
651 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
652   case Metadata::CLASS##Kind:                                                  \
653     visit##CLASS(cast<CLASS>(MD));                                             \
654     break;
655 #include "llvm/IR/Metadata.def"
656   }
657
658   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
659     Metadata *Op = MD.getOperand(i);
660     if (!Op)
661       continue;
662     Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
663            &MD, Op);
664     if (auto *N = dyn_cast<MDNode>(Op)) {
665       visitMDNode(*N);
666       continue;
667     }
668     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
669       visitValueAsMetadata(*V, nullptr);
670       continue;
671     }
672   }
673
674   // Check these last, so we diagnose problems in operands first.
675   Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
676   Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
677 }
678
679 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
680   Assert(MD.getValue(), "Expected valid value", &MD);
681   Assert(!MD.getValue()->getType()->isMetadataTy(),
682          "Unexpected metadata round-trip through values", &MD, MD.getValue());
683
684   auto *L = dyn_cast<LocalAsMetadata>(&MD);
685   if (!L)
686     return;
687
688   Assert(F, "function-local metadata used outside a function", L);
689
690   // If this was an instruction, bb, or argument, verify that it is in the
691   // function that we expect.
692   Function *ActualF = nullptr;
693   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
694     Assert(I->getParent(), "function-local metadata not in basic block", L, I);
695     ActualF = I->getParent()->getParent();
696   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
697     ActualF = BB->getParent();
698   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
699     ActualF = A->getParent();
700   assert(ActualF && "Unimplemented function local metadata case!");
701
702   Assert(ActualF == F, "function-local metadata used in wrong function", L);
703 }
704
705 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
706   Metadata *MD = MDV.getMetadata();
707   if (auto *N = dyn_cast<MDNode>(MD)) {
708     visitMDNode(*N);
709     return;
710   }
711
712   // Only visit each node once.  Metadata can be mutually recursive, so this
713   // avoids infinite recursion here, as well as being an optimization.
714   if (!MDNodes.insert(MD).second)
715     return;
716
717   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
718     visitValueAsMetadata(*V, F);
719 }
720
721 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
722   auto *S = dyn_cast<MDString>(MD);
723   if (!S)
724     return false;
725   if (S->getString().empty())
726     return false;
727
728   // Keep track of names of types referenced via UUID so we can check that they
729   // actually exist.
730   UnresolvedTypeRefs.insert(std::make_pair(S, &N));
731   return true;
732 }
733
734 /// \brief Check if a value can be a reference to a type.
735 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
736   return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
737 }
738
739 /// \brief Check if a value can be a ScopeRef.
740 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
741   return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
742 }
743
744 /// \brief Check if a value can be a debug info ref.
745 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
746   return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
747 }
748
749 template <class Ty>
750 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
751   for (Metadata *MD : N.operands()) {
752     if (MD) {
753       if (!isa<Ty>(MD))
754         return false;
755     } else {
756       if (!AllowNull)
757         return false;
758     }
759   }
760   return true;
761 }
762
763 template <class Ty>
764 bool isValidMetadataArray(const MDTuple &N) {
765   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
766 }
767
768 template <class Ty>
769 bool isValidMetadataNullArray(const MDTuple &N) {
770   return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
771 }
772
773 void Verifier::visitDILocation(const DILocation &N) {
774   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
775          "location requires a valid scope", &N, N.getRawScope());
776   if (auto *IA = N.getRawInlinedAt())
777     Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
778 }
779
780 void Verifier::visitGenericDINode(const GenericDINode &N) {
781   Assert(N.getTag(), "invalid tag", &N);
782 }
783
784 void Verifier::visitDIScope(const DIScope &N) {
785   if (auto *F = N.getRawFile())
786     Assert(isa<DIFile>(F), "invalid file", &N, F);
787 }
788
789 void Verifier::visitDISubrange(const DISubrange &N) {
790   Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
791   Assert(N.getCount() >= -1, "invalid subrange count", &N);
792 }
793
794 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
795   Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
796 }
797
798 void Verifier::visitDIBasicType(const DIBasicType &N) {
799   Assert(N.getTag() == dwarf::DW_TAG_base_type ||
800              N.getTag() == dwarf::DW_TAG_unspecified_type,
801          "invalid tag", &N);
802 }
803
804 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
805   // Common scope checks.
806   visitDIScope(N);
807
808   Assert(N.getTag() == dwarf::DW_TAG_typedef ||
809              N.getTag() == dwarf::DW_TAG_pointer_type ||
810              N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
811              N.getTag() == dwarf::DW_TAG_reference_type ||
812              N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
813              N.getTag() == dwarf::DW_TAG_const_type ||
814              N.getTag() == dwarf::DW_TAG_volatile_type ||
815              N.getTag() == dwarf::DW_TAG_restrict_type ||
816              N.getTag() == dwarf::DW_TAG_member ||
817              N.getTag() == dwarf::DW_TAG_inheritance ||
818              N.getTag() == dwarf::DW_TAG_friend,
819          "invalid tag", &N);
820   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
821     Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
822            N.getExtraData());
823   }
824
825   Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
826   Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
827          N.getBaseType());
828 }
829
830 static bool hasConflictingReferenceFlags(unsigned Flags) {
831   return (Flags & DINode::FlagLValueReference) &&
832          (Flags & DINode::FlagRValueReference);
833 }
834
835 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
836   auto *Params = dyn_cast<MDTuple>(&RawParams);
837   Assert(Params, "invalid template params", &N, &RawParams);
838   for (Metadata *Op : Params->operands()) {
839     Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
840            Params, Op);
841   }
842 }
843
844 void Verifier::visitDICompositeType(const DICompositeType &N) {
845   // Common scope checks.
846   visitDIScope(N);
847
848   Assert(N.getTag() == dwarf::DW_TAG_array_type ||
849              N.getTag() == dwarf::DW_TAG_structure_type ||
850              N.getTag() == dwarf::DW_TAG_union_type ||
851              N.getTag() == dwarf::DW_TAG_enumeration_type ||
852              N.getTag() == dwarf::DW_TAG_class_type,
853          "invalid tag", &N);
854
855   Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
856   Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
857          N.getBaseType());
858
859   Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
860          "invalid composite elements", &N, N.getRawElements());
861   Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
862          N.getRawVTableHolder());
863   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
864          &N);
865   if (auto *Params = N.getRawTemplateParams())
866     visitTemplateParams(N, *Params);
867
868   if (N.getTag() == dwarf::DW_TAG_class_type ||
869       N.getTag() == dwarf::DW_TAG_union_type) {
870     Assert(N.getFile() && !N.getFile()->getFilename().empty(),
871            "class/union requires a filename", &N, N.getFile());
872   }
873 }
874
875 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
876   Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
877   if (auto *Types = N.getRawTypeArray()) {
878     Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
879     for (Metadata *Ty : N.getTypeArray()->operands()) {
880       Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
881     }
882   }
883   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
884          &N);
885 }
886
887 void Verifier::visitDIFile(const DIFile &N) {
888   Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
889 }
890
891 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
892   Assert(N.isDistinct(), "compile units must be distinct", &N);
893   Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
894
895   // Don't bother verifying the compilation directory or producer string
896   // as those could be empty.
897   Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
898          N.getRawFile());
899   Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
900          N.getFile());
901
902   if (auto *Array = N.getRawEnumTypes()) {
903     Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
904     for (Metadata *Op : N.getEnumTypes()->operands()) {
905       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
906       Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
907              "invalid enum type", &N, N.getEnumTypes(), Op);
908     }
909   }
910   if (auto *Array = N.getRawRetainedTypes()) {
911     Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
912     for (Metadata *Op : N.getRetainedTypes()->operands()) {
913       Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
914     }
915   }
916   if (auto *Array = N.getRawSubprograms()) {
917     Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
918     for (Metadata *Op : N.getSubprograms()->operands()) {
919       Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
920     }
921   }
922   if (auto *Array = N.getRawGlobalVariables()) {
923     Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
924     for (Metadata *Op : N.getGlobalVariables()->operands()) {
925       Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
926              Op);
927     }
928   }
929   if (auto *Array = N.getRawImportedEntities()) {
930     Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
931     for (Metadata *Op : N.getImportedEntities()->operands()) {
932       Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
933              Op);
934     }
935   }
936   if (auto *Array = N.getRawMacros()) {
937     Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
938     for (Metadata *Op : N.getMacros()->operands()) {
939       Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
940     }
941   }
942 }
943
944 void Verifier::visitDISubprogram(const DISubprogram &N) {
945   Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
946   Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
947   if (auto *T = N.getRawType())
948     Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
949   Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
950          N.getRawContainingType());
951   if (auto *Params = N.getRawTemplateParams())
952     visitTemplateParams(N, *Params);
953   if (auto *S = N.getRawDeclaration()) {
954     Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
955            "invalid subprogram declaration", &N, S);
956   }
957   if (auto *RawVars = N.getRawVariables()) {
958     auto *Vars = dyn_cast<MDTuple>(RawVars);
959     Assert(Vars, "invalid variable list", &N, RawVars);
960     for (Metadata *Op : Vars->operands()) {
961       Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
962              Op);
963     }
964   }
965   Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
966          &N);
967
968   if (N.isDefinition())
969     Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
970 }
971
972 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
973   Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
974   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
975          "invalid local scope", &N, N.getRawScope());
976 }
977
978 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
979   visitDILexicalBlockBase(N);
980
981   Assert(N.getLine() || !N.getColumn(),
982          "cannot have column info without line info", &N);
983 }
984
985 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
986   visitDILexicalBlockBase(N);
987 }
988
989 void Verifier::visitDINamespace(const DINamespace &N) {
990   Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
991   if (auto *S = N.getRawScope())
992     Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
993 }
994
995 void Verifier::visitDIMacro(const DIMacro &N) {
996   Assert(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
997          N.getMacinfoType() == dwarf::DW_MACINFO_undef,
998          "invalid macinfo type", &N);
999   Assert(!N.getName().empty(), "anonymous macro", &N);
1000 }
1001
1002 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1003   Assert(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1004          "invalid macinfo type", &N);
1005   if (auto *F = N.getRawFile())
1006     Assert(isa<DIFile>(F), "invalid file", &N, F);
1007
1008   if (auto *Array = N.getRawElements()) {
1009     Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1010     for (Metadata *Op : N.getElements()->operands()) {
1011       Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1012     }
1013   }
1014 }
1015
1016 void Verifier::visitDIModule(const DIModule &N) {
1017   Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1018   Assert(!N.getName().empty(), "anonymous module", &N);
1019 }
1020
1021 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1022   Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1023 }
1024
1025 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1026   visitDITemplateParameter(N);
1027
1028   Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1029          &N);
1030 }
1031
1032 void Verifier::visitDITemplateValueParameter(
1033     const DITemplateValueParameter &N) {
1034   visitDITemplateParameter(N);
1035
1036   Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1037              N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1038              N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1039          "invalid tag", &N);
1040 }
1041
1042 void Verifier::visitDIVariable(const DIVariable &N) {
1043   if (auto *S = N.getRawScope())
1044     Assert(isa<DIScope>(S), "invalid scope", &N, S);
1045   Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1046   if (auto *F = N.getRawFile())
1047     Assert(isa<DIFile>(F), "invalid file", &N, F);
1048 }
1049
1050 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1051   // Checks common to all variables.
1052   visitDIVariable(N);
1053
1054   Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1055   Assert(!N.getName().empty(), "missing global variable name", &N);
1056   if (auto *V = N.getRawVariable()) {
1057     Assert(isa<ConstantAsMetadata>(V) &&
1058                !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1059            "invalid global varaible ref", &N, V);
1060   }
1061   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1062     Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1063            &N, Member);
1064   }
1065 }
1066
1067 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1068   // Checks common to all variables.
1069   visitDIVariable(N);
1070
1071   Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1072   Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1073          "local variable requires a valid scope", &N, N.getRawScope());
1074 }
1075
1076 void Verifier::visitDIExpression(const DIExpression &N) {
1077   Assert(N.isValid(), "invalid expression", &N);
1078 }
1079
1080 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1081   Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1082   if (auto *T = N.getRawType())
1083     Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1084   if (auto *F = N.getRawFile())
1085     Assert(isa<DIFile>(F), "invalid file", &N, F);
1086 }
1087
1088 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1089   Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1090              N.getTag() == dwarf::DW_TAG_imported_declaration,
1091          "invalid tag", &N);
1092   if (auto *S = N.getRawScope())
1093     Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1094   Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1095          N.getEntity());
1096 }
1097
1098 void Verifier::visitComdat(const Comdat &C) {
1099   // The Module is invalid if the GlobalValue has private linkage.  Entities
1100   // with private linkage don't have entries in the symbol table.
1101   if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1102     Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1103            GV);
1104 }
1105
1106 void Verifier::visitModuleIdents(const Module &M) {
1107   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1108   if (!Idents) 
1109     return;
1110   
1111   // llvm.ident takes a list of metadata entry. Each entry has only one string.
1112   // Scan each llvm.ident entry and make sure that this requirement is met.
1113   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1114     const MDNode *N = Idents->getOperand(i);
1115     Assert(N->getNumOperands() == 1,
1116            "incorrect number of operands in llvm.ident metadata", N);
1117     Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1118            ("invalid value for llvm.ident metadata entry operand"
1119             "(the operand should be a string)"),
1120            N->getOperand(0));
1121   } 
1122 }
1123
1124 void Verifier::visitModuleFlags(const Module &M) {
1125   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1126   if (!Flags) return;
1127
1128   // Scan each flag, and track the flags and requirements.
1129   DenseMap<const MDString*, const MDNode*> SeenIDs;
1130   SmallVector<const MDNode*, 16> Requirements;
1131   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1132     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1133   }
1134
1135   // Validate that the requirements in the module are valid.
1136   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1137     const MDNode *Requirement = Requirements[I];
1138     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1139     const Metadata *ReqValue = Requirement->getOperand(1);
1140
1141     const MDNode *Op = SeenIDs.lookup(Flag);
1142     if (!Op) {
1143       CheckFailed("invalid requirement on flag, flag is not present in module",
1144                   Flag);
1145       continue;
1146     }
1147
1148     if (Op->getOperand(2) != ReqValue) {
1149       CheckFailed(("invalid requirement on flag, "
1150                    "flag does not have the required value"),
1151                   Flag);
1152       continue;
1153     }
1154   }
1155 }
1156
1157 void
1158 Verifier::visitModuleFlag(const MDNode *Op,
1159                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
1160                           SmallVectorImpl<const MDNode *> &Requirements) {
1161   // Each module flag should have three arguments, the merge behavior (a
1162   // constant int), the flag ID (an MDString), and the value.
1163   Assert(Op->getNumOperands() == 3,
1164          "incorrect number of operands in module flag", Op);
1165   Module::ModFlagBehavior MFB;
1166   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1167     Assert(
1168         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1169         "invalid behavior operand in module flag (expected constant integer)",
1170         Op->getOperand(0));
1171     Assert(false,
1172            "invalid behavior operand in module flag (unexpected constant)",
1173            Op->getOperand(0));
1174   }
1175   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1176   Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1177          Op->getOperand(1));
1178
1179   // Sanity check the values for behaviors with additional requirements.
1180   switch (MFB) {
1181   case Module::Error:
1182   case Module::Warning:
1183   case Module::Override:
1184     // These behavior types accept any value.
1185     break;
1186
1187   case Module::Require: {
1188     // The value should itself be an MDNode with two operands, a flag ID (an
1189     // MDString), and a value.
1190     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1191     Assert(Value && Value->getNumOperands() == 2,
1192            "invalid value for 'require' module flag (expected metadata pair)",
1193            Op->getOperand(2));
1194     Assert(isa<MDString>(Value->getOperand(0)),
1195            ("invalid value for 'require' module flag "
1196             "(first value operand should be a string)"),
1197            Value->getOperand(0));
1198
1199     // Append it to the list of requirements, to check once all module flags are
1200     // scanned.
1201     Requirements.push_back(Value);
1202     break;
1203   }
1204
1205   case Module::Append:
1206   case Module::AppendUnique: {
1207     // These behavior types require the operand be an MDNode.
1208     Assert(isa<MDNode>(Op->getOperand(2)),
1209            "invalid value for 'append'-type module flag "
1210            "(expected a metadata node)",
1211            Op->getOperand(2));
1212     break;
1213   }
1214   }
1215
1216   // Unless this is a "requires" flag, check the ID is unique.
1217   if (MFB != Module::Require) {
1218     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1219     Assert(Inserted,
1220            "module flag identifiers must be unique (or of 'require' type)", ID);
1221   }
1222 }
1223
1224 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1225                                     bool isFunction, const Value *V) {
1226   unsigned Slot = ~0U;
1227   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1228     if (Attrs.getSlotIndex(I) == Idx) {
1229       Slot = I;
1230       break;
1231     }
1232
1233   assert(Slot != ~0U && "Attribute set inconsistency!");
1234
1235   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1236          I != E; ++I) {
1237     if (I->isStringAttribute())
1238       continue;
1239
1240     if (I->getKindAsEnum() == Attribute::NoReturn ||
1241         I->getKindAsEnum() == Attribute::NoUnwind ||
1242         I->getKindAsEnum() == Attribute::NoInline ||
1243         I->getKindAsEnum() == Attribute::AlwaysInline ||
1244         I->getKindAsEnum() == Attribute::OptimizeForSize ||
1245         I->getKindAsEnum() == Attribute::StackProtect ||
1246         I->getKindAsEnum() == Attribute::StackProtectReq ||
1247         I->getKindAsEnum() == Attribute::StackProtectStrong ||
1248         I->getKindAsEnum() == Attribute::SafeStack ||
1249         I->getKindAsEnum() == Attribute::NoRedZone ||
1250         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1251         I->getKindAsEnum() == Attribute::Naked ||
1252         I->getKindAsEnum() == Attribute::InlineHint ||
1253         I->getKindAsEnum() == Attribute::StackAlignment ||
1254         I->getKindAsEnum() == Attribute::UWTable ||
1255         I->getKindAsEnum() == Attribute::NonLazyBind ||
1256         I->getKindAsEnum() == Attribute::ReturnsTwice ||
1257         I->getKindAsEnum() == Attribute::SanitizeAddress ||
1258         I->getKindAsEnum() == Attribute::SanitizeThread ||
1259         I->getKindAsEnum() == Attribute::SanitizeMemory ||
1260         I->getKindAsEnum() == Attribute::MinSize ||
1261         I->getKindAsEnum() == Attribute::NoDuplicate ||
1262         I->getKindAsEnum() == Attribute::Builtin ||
1263         I->getKindAsEnum() == Attribute::NoBuiltin ||
1264         I->getKindAsEnum() == Attribute::Cold ||
1265         I->getKindAsEnum() == Attribute::OptimizeNone ||
1266         I->getKindAsEnum() == Attribute::JumpTable ||
1267         I->getKindAsEnum() == Attribute::Convergent ||
1268         I->getKindAsEnum() == Attribute::ArgMemOnly ||
1269         I->getKindAsEnum() == Attribute::NoRecurse) {
1270       if (!isFunction) {
1271         CheckFailed("Attribute '" + I->getAsString() +
1272                     "' only applies to functions!", V);
1273         return;
1274       }
1275     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1276                I->getKindAsEnum() == Attribute::ReadNone) {
1277       if (Idx == 0) {
1278         CheckFailed("Attribute '" + I->getAsString() +
1279                     "' does not apply to function returns");
1280         return;
1281       }
1282     } else if (isFunction) {
1283       CheckFailed("Attribute '" + I->getAsString() +
1284                   "' does not apply to functions!", V);
1285       return;
1286     }
1287   }
1288 }
1289
1290 // VerifyParameterAttrs - Check the given attributes for an argument or return
1291 // value of the specified type.  The value V is printed in error messages.
1292 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1293                                     bool isReturnValue, const Value *V) {
1294   if (!Attrs.hasAttributes(Idx))
1295     return;
1296
1297   VerifyAttributeTypes(Attrs, Idx, false, V);
1298
1299   if (isReturnValue)
1300     Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1301                !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1302                !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1303                !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1304                !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1305                !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1306            "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1307            "'returned' do not apply to return values!",
1308            V);
1309
1310   // Check for mutually incompatible attributes.  Only inreg is compatible with
1311   // sret.
1312   unsigned AttrCount = 0;
1313   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1314   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1315   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1316                Attrs.hasAttribute(Idx, Attribute::InReg);
1317   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1318   Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1319                          "and 'sret' are incompatible!",
1320          V);
1321
1322   Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1323            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1324          "Attributes "
1325          "'inalloca and readonly' are incompatible!",
1326          V);
1327
1328   Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1329            Attrs.hasAttribute(Idx, Attribute::Returned)),
1330          "Attributes "
1331          "'sret and returned' are incompatible!",
1332          V);
1333
1334   Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1335            Attrs.hasAttribute(Idx, Attribute::SExt)),
1336          "Attributes "
1337          "'zeroext and signext' are incompatible!",
1338          V);
1339
1340   Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1341            Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1342          "Attributes "
1343          "'readnone and readonly' are incompatible!",
1344          V);
1345
1346   Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1347            Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1348          "Attributes "
1349          "'noinline and alwaysinline' are incompatible!",
1350          V);
1351
1352   Assert(!AttrBuilder(Attrs, Idx)
1353               .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1354          "Wrong types for attribute: " +
1355          AttributeSet::get(*Context, Idx,
1356                         AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1357          V);
1358
1359   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1360     SmallPtrSet<Type*, 4> Visited;
1361     if (!PTy->getElementType()->isSized(&Visited)) {
1362       Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1363                  !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1364              "Attributes 'byval' and 'inalloca' do not support unsized types!",
1365              V);
1366     }
1367   } else {
1368     Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1369            "Attribute 'byval' only applies to parameters with pointer type!",
1370            V);
1371   }
1372 }
1373
1374 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1375 // The value V is printed in error messages.
1376 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1377                                    const Value *V) {
1378   if (Attrs.isEmpty())
1379     return;
1380
1381   bool SawNest = false;
1382   bool SawReturned = false;
1383   bool SawSRet = false;
1384
1385   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1386     unsigned Idx = Attrs.getSlotIndex(i);
1387
1388     Type *Ty;
1389     if (Idx == 0)
1390       Ty = FT->getReturnType();
1391     else if (Idx-1 < FT->getNumParams())
1392       Ty = FT->getParamType(Idx-1);
1393     else
1394       break;  // VarArgs attributes, verified elsewhere.
1395
1396     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1397
1398     if (Idx == 0)
1399       continue;
1400
1401     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1402       Assert(!SawNest, "More than one parameter has attribute nest!", V);
1403       SawNest = true;
1404     }
1405
1406     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1407       Assert(!SawReturned, "More than one parameter has attribute returned!",
1408              V);
1409       Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1410              "Incompatible "
1411              "argument and return types for 'returned' attribute",
1412              V);
1413       SawReturned = true;
1414     }
1415
1416     if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1417       Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1418       Assert(Idx == 1 || Idx == 2,
1419              "Attribute 'sret' is not on first or second parameter!", V);
1420       SawSRet = true;
1421     }
1422
1423     if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1424       Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1425              V);
1426     }
1427   }
1428
1429   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1430     return;
1431
1432   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1433
1434   Assert(
1435       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1436         Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1437       "Attributes 'readnone and readonly' are incompatible!", V);
1438
1439   Assert(
1440       !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1441         Attrs.hasAttribute(AttributeSet::FunctionIndex,
1442                            Attribute::AlwaysInline)),
1443       "Attributes 'noinline and alwaysinline' are incompatible!", V);
1444
1445   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
1446                          Attribute::OptimizeNone)) {
1447     Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1448            "Attribute 'optnone' requires 'noinline'!", V);
1449
1450     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1451                                Attribute::OptimizeForSize),
1452            "Attributes 'optsize and optnone' are incompatible!", V);
1453
1454     Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1455            "Attributes 'minsize and optnone' are incompatible!", V);
1456   }
1457
1458   if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1459                          Attribute::JumpTable)) {
1460     const GlobalValue *GV = cast<GlobalValue>(V);
1461     Assert(GV->hasUnnamedAddr(),
1462            "Attribute 'jumptable' requires 'unnamed_addr'", V);
1463   }
1464 }
1465
1466 void Verifier::VerifyFunctionMetadata(
1467     const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1468   if (MDs.empty())
1469     return;
1470
1471   for (unsigned i = 0; i < MDs.size(); i++) {
1472     if (MDs[i].first == LLVMContext::MD_prof) {
1473       MDNode *MD = MDs[i].second;
1474       Assert(MD->getNumOperands() == 2,
1475              "!prof annotations should have exactly 2 operands", MD);
1476
1477       // Check first operand.
1478       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1479              MD);
1480       Assert(isa<MDString>(MD->getOperand(0)),
1481              "expected string with name of the !prof annotation", MD);
1482       MDString *MDS = cast<MDString>(MD->getOperand(0));
1483       StringRef ProfName = MDS->getString();
1484       Assert(ProfName.equals("function_entry_count"),
1485              "first operand should be 'function_entry_count'", MD);
1486
1487       // Check second operand.
1488       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1489              MD);
1490       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1491              "expected integer argument to function_entry_count", MD);
1492     }
1493   }
1494 }
1495
1496 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1497   if (CE->getOpcode() != Instruction::BitCast)
1498     return;
1499
1500   Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1501                                CE->getType()),
1502          "Invalid bitcast", CE);
1503 }
1504
1505 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1506   if (Attrs.getNumSlots() == 0)
1507     return true;
1508
1509   unsigned LastSlot = Attrs.getNumSlots() - 1;
1510   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1511   if (LastIndex <= Params
1512       || (LastIndex == AttributeSet::FunctionIndex
1513           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1514     return true;
1515
1516   return false;
1517 }
1518
1519 /// \brief Verify that statepoint intrinsic is well formed.
1520 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1521   assert(CS.getCalledFunction() &&
1522          CS.getCalledFunction()->getIntrinsicID() ==
1523            Intrinsic::experimental_gc_statepoint);
1524
1525   const Instruction &CI = *CS.getInstruction();
1526
1527   Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1528          !CS.onlyAccessesArgMemory(),
1529          "gc.statepoint must read and write all memory to preserve "
1530          "reordering restrictions required by safepoint semantics",
1531          &CI);
1532
1533   const Value *IDV = CS.getArgument(0);
1534   Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1535          &CI);
1536
1537   const Value *NumPatchBytesV = CS.getArgument(1);
1538   Assert(isa<ConstantInt>(NumPatchBytesV),
1539          "gc.statepoint number of patchable bytes must be a constant integer",
1540          &CI);
1541   const int64_t NumPatchBytes =
1542       cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1543   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1544   Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1545                              "positive",
1546          &CI);
1547
1548   const Value *Target = CS.getArgument(2);
1549   auto *PT = dyn_cast<PointerType>(Target->getType());
1550   Assert(PT && PT->getElementType()->isFunctionTy(),
1551          "gc.statepoint callee must be of function pointer type", &CI, Target);
1552   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1553
1554   const Value *NumCallArgsV = CS.getArgument(3);
1555   Assert(isa<ConstantInt>(NumCallArgsV),
1556          "gc.statepoint number of arguments to underlying call "
1557          "must be constant integer",
1558          &CI);
1559   const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1560   Assert(NumCallArgs >= 0,
1561          "gc.statepoint number of arguments to underlying call "
1562          "must be positive",
1563          &CI);
1564   const int NumParams = (int)TargetFuncType->getNumParams();
1565   if (TargetFuncType->isVarArg()) {
1566     Assert(NumCallArgs >= NumParams,
1567            "gc.statepoint mismatch in number of vararg call args", &CI);
1568
1569     // TODO: Remove this limitation
1570     Assert(TargetFuncType->getReturnType()->isVoidTy(),
1571            "gc.statepoint doesn't support wrapping non-void "
1572            "vararg functions yet",
1573            &CI);
1574   } else
1575     Assert(NumCallArgs == NumParams,
1576            "gc.statepoint mismatch in number of call args", &CI);
1577
1578   const Value *FlagsV = CS.getArgument(4);
1579   Assert(isa<ConstantInt>(FlagsV),
1580          "gc.statepoint flags must be constant integer", &CI);
1581   const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1582   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1583          "unknown flag used in gc.statepoint flags argument", &CI);
1584
1585   // Verify that the types of the call parameter arguments match
1586   // the type of the wrapped callee.
1587   for (int i = 0; i < NumParams; i++) {
1588     Type *ParamType = TargetFuncType->getParamType(i);
1589     Type *ArgType = CS.getArgument(5 + i)->getType();
1590     Assert(ArgType == ParamType,
1591            "gc.statepoint call argument does not match wrapped "
1592            "function type",
1593            &CI);
1594   }
1595
1596   const int EndCallArgsInx = 4 + NumCallArgs;
1597
1598   const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1599   Assert(isa<ConstantInt>(NumTransitionArgsV),
1600          "gc.statepoint number of transition arguments "
1601          "must be constant integer",
1602          &CI);
1603   const int NumTransitionArgs =
1604       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1605   Assert(NumTransitionArgs >= 0,
1606          "gc.statepoint number of transition arguments must be positive", &CI);
1607   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1608
1609   const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1610   Assert(isa<ConstantInt>(NumDeoptArgsV),
1611          "gc.statepoint number of deoptimization arguments "
1612          "must be constant integer",
1613          &CI);
1614   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1615   Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1616                             "must be positive",
1617          &CI);
1618
1619   const int ExpectedNumArgs =
1620       7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1621   Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1622          "gc.statepoint too few arguments according to length fields", &CI);
1623
1624   // Check that the only uses of this gc.statepoint are gc.result or 
1625   // gc.relocate calls which are tied to this statepoint and thus part
1626   // of the same statepoint sequence
1627   for (const User *U : CI.users()) {
1628     const CallInst *Call = dyn_cast<const CallInst>(U);
1629     Assert(Call, "illegal use of statepoint token", &CI, U);
1630     if (!Call) continue;
1631     Assert(isGCRelocate(Call) || isGCResult(Call),
1632            "gc.result or gc.relocate are the only value uses"
1633            "of a gc.statepoint",
1634            &CI, U);
1635     if (isGCResult(Call)) {
1636       Assert(Call->getArgOperand(0) == &CI,
1637              "gc.result connected to wrong gc.statepoint", &CI, Call);
1638     } else if (isGCRelocate(Call)) {
1639       Assert(Call->getArgOperand(0) == &CI,
1640              "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1641     }
1642   }
1643
1644   // Note: It is legal for a single derived pointer to be listed multiple
1645   // times.  It's non-optimal, but it is legal.  It can also happen after
1646   // insertion if we strip a bitcast away.
1647   // Note: It is really tempting to check that each base is relocated and
1648   // that a derived pointer is never reused as a base pointer.  This turns
1649   // out to be problematic since optimizations run after safepoint insertion
1650   // can recognize equality properties that the insertion logic doesn't know
1651   // about.  See example statepoint.ll in the verifier subdirectory
1652 }
1653
1654 void Verifier::verifyFrameRecoverIndices() {
1655   for (auto &Counts : FrameEscapeInfo) {
1656     Function *F = Counts.first;
1657     unsigned EscapedObjectCount = Counts.second.first;
1658     unsigned MaxRecoveredIndex = Counts.second.second;
1659     Assert(MaxRecoveredIndex <= EscapedObjectCount,
1660            "all indices passed to llvm.localrecover must be less than the "
1661            "number of arguments passed ot llvm.localescape in the parent "
1662            "function",
1663            F);
1664   }
1665 }
1666
1667 // visitFunction - Verify that a function is ok.
1668 //
1669 void Verifier::visitFunction(const Function &F) {
1670   // Check function arguments.
1671   FunctionType *FT = F.getFunctionType();
1672   unsigned NumArgs = F.arg_size();
1673
1674   Assert(Context == &F.getContext(),
1675          "Function context does not match Module context!", &F);
1676
1677   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1678   Assert(FT->getNumParams() == NumArgs,
1679          "# formal arguments must match # of arguments for function type!", &F,
1680          FT);
1681   Assert(F.getReturnType()->isFirstClassType() ||
1682              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1683          "Functions cannot return aggregate values!", &F);
1684
1685   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1686          "Invalid struct return type!", &F);
1687
1688   AttributeSet Attrs = F.getAttributes();
1689
1690   Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1691          "Attribute after last parameter!", &F);
1692
1693   // Check function attributes.
1694   VerifyFunctionAttrs(FT, Attrs, &F);
1695
1696   // On function declarations/definitions, we do not support the builtin
1697   // attribute. We do not check this in VerifyFunctionAttrs since that is
1698   // checking for Attributes that can/can not ever be on functions.
1699   Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1700          "Attribute 'builtin' can only be applied to a callsite.", &F);
1701
1702   // Check that this function meets the restrictions on this calling convention.
1703   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1704   // restrictions can be lifted.
1705   switch (F.getCallingConv()) {
1706   default:
1707   case CallingConv::C:
1708     break;
1709   case CallingConv::Fast:
1710   case CallingConv::Cold:
1711   case CallingConv::Intel_OCL_BI:
1712   case CallingConv::PTX_Kernel:
1713   case CallingConv::PTX_Device:
1714     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1715                           "perfect forwarding!",
1716            &F);
1717     break;
1718   }
1719
1720   bool isLLVMdotName = F.getName().size() >= 5 &&
1721                        F.getName().substr(0, 5) == "llvm.";
1722
1723   // Check that the argument values match the function type for this function...
1724   unsigned i = 0;
1725   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1726        ++I, ++i) {
1727     Assert(I->getType() == FT->getParamType(i),
1728            "Argument value does not match function argument type!", I,
1729            FT->getParamType(i));
1730     Assert(I->getType()->isFirstClassType(),
1731            "Function arguments must have first-class types!", I);
1732     if (!isLLVMdotName) {
1733       Assert(!I->getType()->isMetadataTy(),
1734              "Function takes metadata but isn't an intrinsic", I, &F);
1735       Assert(!I->getType()->isTokenTy(),
1736              "Function takes token but isn't an intrinsic", I, &F);
1737     }
1738   }
1739
1740   if (!isLLVMdotName)
1741     Assert(!F.getReturnType()->isTokenTy(),
1742            "Functions returns a token but isn't an intrinsic", &F);
1743
1744   // Get the function metadata attachments.
1745   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1746   F.getAllMetadata(MDs);
1747   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1748   VerifyFunctionMetadata(MDs);
1749
1750   // Check validity of the personality function
1751   if (F.hasPersonalityFn()) {
1752     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1753     if (Per)
1754       Assert(Per->getParent() == F.getParent(),
1755              "Referencing personality function in another module!",
1756              &F, F.getParent(), Per, Per->getParent());
1757   }
1758
1759   if (F.isMaterializable()) {
1760     // Function has a body somewhere we can't see.
1761     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1762            MDs.empty() ? nullptr : MDs.front().second);
1763   } else if (F.isDeclaration()) {
1764     Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1765            "invalid linkage type for function declaration", &F);
1766     Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1767            MDs.empty() ? nullptr : MDs.front().second);
1768     Assert(!F.hasPersonalityFn(),
1769            "Function declaration shouldn't have a personality routine", &F);
1770   } else {
1771     // Verify that this function (which has a body) is not named "llvm.*".  It
1772     // is not legal to define intrinsics.
1773     Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1774
1775     // Check the entry node
1776     const BasicBlock *Entry = &F.getEntryBlock();
1777     Assert(pred_empty(Entry),
1778            "Entry block to function must not have predecessors!", Entry);
1779
1780     // The address of the entry block cannot be taken, unless it is dead.
1781     if (Entry->hasAddressTaken()) {
1782       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1783              "blockaddress may not be used with the entry block!", Entry);
1784     }
1785
1786     // Visit metadata attachments.
1787     for (const auto &I : MDs) {
1788       // Verify that the attachment is legal.
1789       switch (I.first) {
1790       default:
1791         break;
1792       case LLVMContext::MD_dbg:
1793         Assert(isa<DISubprogram>(I.second),
1794                "function !dbg attachment must be a subprogram", &F, I.second);
1795         break;
1796       }
1797
1798       // Verify the metadata itself.
1799       visitMDNode(*I.second);
1800     }
1801   }
1802
1803   // If this function is actually an intrinsic, verify that it is only used in
1804   // direct call/invokes, never having its "address taken".
1805   if (F.getIntrinsicID()) {
1806     const User *U;
1807     if (F.hasAddressTaken(&U))
1808       Assert(0, "Invalid user of intrinsic instruction!", U);
1809   }
1810
1811   Assert(!F.hasDLLImportStorageClass() ||
1812              (F.isDeclaration() && F.hasExternalLinkage()) ||
1813              F.hasAvailableExternallyLinkage(),
1814          "Function is marked as dllimport, but not external.", &F);
1815
1816   auto *N = F.getSubprogram();
1817   if (!N)
1818     return;
1819
1820   // Check that all !dbg attachments lead to back to N (or, at least, another
1821   // subprogram that describes the same function).
1822   //
1823   // FIXME: Check this incrementally while visiting !dbg attachments.
1824   // FIXME: Only check when N is the canonical subprogram for F.
1825   SmallPtrSet<const MDNode *, 32> Seen;
1826   for (auto &BB : F)
1827     for (auto &I : BB) {
1828       // Be careful about using DILocation here since we might be dealing with
1829       // broken code (this is the Verifier after all).
1830       DILocation *DL =
1831           dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1832       if (!DL)
1833         continue;
1834       if (!Seen.insert(DL).second)
1835         continue;
1836
1837       DILocalScope *Scope = DL->getInlinedAtScope();
1838       if (Scope && !Seen.insert(Scope).second)
1839         continue;
1840
1841       DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1842
1843       // Scope and SP could be the same MDNode and we don't want to skip
1844       // validation in that case
1845       if (SP && ((Scope != SP) && !Seen.insert(SP).second))
1846         continue;
1847
1848       // FIXME: Once N is canonical, check "SP == &N".
1849       Assert(SP->describes(&F),
1850              "!dbg attachment points at wrong subprogram for function", N, &F,
1851              &I, DL, Scope, SP);
1852     }
1853 }
1854
1855 // verifyBasicBlock - Verify that a basic block is well formed...
1856 //
1857 void Verifier::visitBasicBlock(BasicBlock &BB) {
1858   InstsInThisBlock.clear();
1859
1860   // Ensure that basic blocks have terminators!
1861   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1862
1863   // Check constraints that this basic block imposes on all of the PHI nodes in
1864   // it.
1865   if (isa<PHINode>(BB.front())) {
1866     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1867     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1868     std::sort(Preds.begin(), Preds.end());
1869     PHINode *PN;
1870     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1871       // Ensure that PHI nodes have at least one entry!
1872       Assert(PN->getNumIncomingValues() != 0,
1873              "PHI nodes must have at least one entry.  If the block is dead, "
1874              "the PHI should be removed!",
1875              PN);
1876       Assert(PN->getNumIncomingValues() == Preds.size(),
1877              "PHINode should have one entry for each predecessor of its "
1878              "parent basic block!",
1879              PN);
1880
1881       // Get and sort all incoming values in the PHI node...
1882       Values.clear();
1883       Values.reserve(PN->getNumIncomingValues());
1884       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1885         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1886                                         PN->getIncomingValue(i)));
1887       std::sort(Values.begin(), Values.end());
1888
1889       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1890         // Check to make sure that if there is more than one entry for a
1891         // particular basic block in this PHI node, that the incoming values are
1892         // all identical.
1893         //
1894         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1895                    Values[i].second == Values[i - 1].second,
1896                "PHI node has multiple entries for the same basic block with "
1897                "different incoming values!",
1898                PN, Values[i].first, Values[i].second, Values[i - 1].second);
1899
1900         // Check to make sure that the predecessors and PHI node entries are
1901         // matched up.
1902         Assert(Values[i].first == Preds[i],
1903                "PHI node entries do not match predecessors!", PN,
1904                Values[i].first, Preds[i]);
1905       }
1906     }
1907   }
1908
1909   // Check that all instructions have their parent pointers set up correctly.
1910   for (auto &I : BB)
1911   {
1912     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1913   }
1914 }
1915
1916 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1917   // Ensure that terminators only exist at the end of the basic block.
1918   Assert(&I == I.getParent()->getTerminator(),
1919          "Terminator found in the middle of a basic block!", I.getParent());
1920   visitInstruction(I);
1921 }
1922
1923 void Verifier::visitBranchInst(BranchInst &BI) {
1924   if (BI.isConditional()) {
1925     Assert(BI.getCondition()->getType()->isIntegerTy(1),
1926            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1927   }
1928   visitTerminatorInst(BI);
1929 }
1930
1931 void Verifier::visitReturnInst(ReturnInst &RI) {
1932   Function *F = RI.getParent()->getParent();
1933   unsigned N = RI.getNumOperands();
1934   if (F->getReturnType()->isVoidTy())
1935     Assert(N == 0,
1936            "Found return instr that returns non-void in Function of void "
1937            "return type!",
1938            &RI, F->getReturnType());
1939   else
1940     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1941            "Function return type does not match operand "
1942            "type of return inst!",
1943            &RI, F->getReturnType());
1944
1945   // Check to make sure that the return value has necessary properties for
1946   // terminators...
1947   visitTerminatorInst(RI);
1948 }
1949
1950 void Verifier::visitSwitchInst(SwitchInst &SI) {
1951   // Check to make sure that all of the constants in the switch instruction
1952   // have the same type as the switched-on value.
1953   Type *SwitchTy = SI.getCondition()->getType();
1954   SmallPtrSet<ConstantInt*, 32> Constants;
1955   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1956     Assert(i.getCaseValue()->getType() == SwitchTy,
1957            "Switch constants must all be same type as switch value!", &SI);
1958     Assert(Constants.insert(i.getCaseValue()).second,
1959            "Duplicate integer as switch case", &SI, i.getCaseValue());
1960   }
1961
1962   visitTerminatorInst(SI);
1963 }
1964
1965 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1966   Assert(BI.getAddress()->getType()->isPointerTy(),
1967          "Indirectbr operand must have pointer type!", &BI);
1968   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1969     Assert(BI.getDestination(i)->getType()->isLabelTy(),
1970            "Indirectbr destinations must all have pointer type!", &BI);
1971
1972   visitTerminatorInst(BI);
1973 }
1974
1975 void Verifier::visitSelectInst(SelectInst &SI) {
1976   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1977                                          SI.getOperand(2)),
1978          "Invalid operands for select instruction!", &SI);
1979
1980   Assert(SI.getTrueValue()->getType() == SI.getType(),
1981          "Select values must have same type as select instruction!", &SI);
1982   visitInstruction(SI);
1983 }
1984
1985 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1986 /// a pass, if any exist, it's an error.
1987 ///
1988 void Verifier::visitUserOp1(Instruction &I) {
1989   Assert(0, "User-defined operators should not live outside of a pass!", &I);
1990 }
1991
1992 void Verifier::visitTruncInst(TruncInst &I) {
1993   // Get the source and destination types
1994   Type *SrcTy = I.getOperand(0)->getType();
1995   Type *DestTy = I.getType();
1996
1997   // Get the size of the types in bits, we'll need this later
1998   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1999   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2000
2001   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2002   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2003   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2004          "trunc source and destination must both be a vector or neither", &I);
2005   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2006
2007   visitInstruction(I);
2008 }
2009
2010 void Verifier::visitZExtInst(ZExtInst &I) {
2011   // Get the source and destination types
2012   Type *SrcTy = I.getOperand(0)->getType();
2013   Type *DestTy = I.getType();
2014
2015   // Get the size of the types in bits, we'll need this later
2016   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2017   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2018   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2019          "zext source and destination must both be a vector or neither", &I);
2020   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2021   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2022
2023   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2024
2025   visitInstruction(I);
2026 }
2027
2028 void Verifier::visitSExtInst(SExtInst &I) {
2029   // Get the source and destination types
2030   Type *SrcTy = I.getOperand(0)->getType();
2031   Type *DestTy = I.getType();
2032
2033   // Get the size of the types in bits, we'll need this later
2034   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2035   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2036
2037   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2038   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2039   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2040          "sext source and destination must both be a vector or neither", &I);
2041   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2042
2043   visitInstruction(I);
2044 }
2045
2046 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2047   // Get the source and destination types
2048   Type *SrcTy = I.getOperand(0)->getType();
2049   Type *DestTy = I.getType();
2050   // Get the size of the types in bits, we'll need this later
2051   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2052   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2053
2054   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2055   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2056   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2057          "fptrunc source and destination must both be a vector or neither", &I);
2058   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2059
2060   visitInstruction(I);
2061 }
2062
2063 void Verifier::visitFPExtInst(FPExtInst &I) {
2064   // Get the source and destination types
2065   Type *SrcTy = I.getOperand(0)->getType();
2066   Type *DestTy = I.getType();
2067
2068   // Get the size of the types in bits, we'll need this later
2069   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2070   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2071
2072   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2073   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2074   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2075          "fpext source and destination must both be a vector or neither", &I);
2076   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2077
2078   visitInstruction(I);
2079 }
2080
2081 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2082   // Get the source and destination types
2083   Type *SrcTy = I.getOperand(0)->getType();
2084   Type *DestTy = I.getType();
2085
2086   bool SrcVec = SrcTy->isVectorTy();
2087   bool DstVec = DestTy->isVectorTy();
2088
2089   Assert(SrcVec == DstVec,
2090          "UIToFP source and dest must both be vector or scalar", &I);
2091   Assert(SrcTy->isIntOrIntVectorTy(),
2092          "UIToFP source must be integer or integer vector", &I);
2093   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2094          &I);
2095
2096   if (SrcVec && DstVec)
2097     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2098                cast<VectorType>(DestTy)->getNumElements(),
2099            "UIToFP source and dest vector length mismatch", &I);
2100
2101   visitInstruction(I);
2102 }
2103
2104 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2105   // Get the source and destination types
2106   Type *SrcTy = I.getOperand(0)->getType();
2107   Type *DestTy = I.getType();
2108
2109   bool SrcVec = SrcTy->isVectorTy();
2110   bool DstVec = DestTy->isVectorTy();
2111
2112   Assert(SrcVec == DstVec,
2113          "SIToFP source and dest must both be vector or scalar", &I);
2114   Assert(SrcTy->isIntOrIntVectorTy(),
2115          "SIToFP source must be integer or integer vector", &I);
2116   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2117          &I);
2118
2119   if (SrcVec && DstVec)
2120     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2121                cast<VectorType>(DestTy)->getNumElements(),
2122            "SIToFP source and dest vector length mismatch", &I);
2123
2124   visitInstruction(I);
2125 }
2126
2127 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2128   // Get the source and destination types
2129   Type *SrcTy = I.getOperand(0)->getType();
2130   Type *DestTy = I.getType();
2131
2132   bool SrcVec = SrcTy->isVectorTy();
2133   bool DstVec = DestTy->isVectorTy();
2134
2135   Assert(SrcVec == DstVec,
2136          "FPToUI source and dest must both be vector or scalar", &I);
2137   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2138          &I);
2139   Assert(DestTy->isIntOrIntVectorTy(),
2140          "FPToUI result must be integer or integer vector", &I);
2141
2142   if (SrcVec && DstVec)
2143     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2144                cast<VectorType>(DestTy)->getNumElements(),
2145            "FPToUI source and dest vector length mismatch", &I);
2146
2147   visitInstruction(I);
2148 }
2149
2150 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2151   // Get the source and destination types
2152   Type *SrcTy = I.getOperand(0)->getType();
2153   Type *DestTy = I.getType();
2154
2155   bool SrcVec = SrcTy->isVectorTy();
2156   bool DstVec = DestTy->isVectorTy();
2157
2158   Assert(SrcVec == DstVec,
2159          "FPToSI source and dest must both be vector or scalar", &I);
2160   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2161          &I);
2162   Assert(DestTy->isIntOrIntVectorTy(),
2163          "FPToSI result must be integer or integer vector", &I);
2164
2165   if (SrcVec && DstVec)
2166     Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2167                cast<VectorType>(DestTy)->getNumElements(),
2168            "FPToSI source and dest vector length mismatch", &I);
2169
2170   visitInstruction(I);
2171 }
2172
2173 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2174   // Get the source and destination types
2175   Type *SrcTy = I.getOperand(0)->getType();
2176   Type *DestTy = I.getType();
2177
2178   Assert(SrcTy->getScalarType()->isPointerTy(),
2179          "PtrToInt source must be pointer", &I);
2180   Assert(DestTy->getScalarType()->isIntegerTy(),
2181          "PtrToInt result must be integral", &I);
2182   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2183          &I);
2184
2185   if (SrcTy->isVectorTy()) {
2186     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2187     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2188     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2189            "PtrToInt Vector width mismatch", &I);
2190   }
2191
2192   visitInstruction(I);
2193 }
2194
2195 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2196   // Get the source and destination types
2197   Type *SrcTy = I.getOperand(0)->getType();
2198   Type *DestTy = I.getType();
2199
2200   Assert(SrcTy->getScalarType()->isIntegerTy(),
2201          "IntToPtr source must be an integral", &I);
2202   Assert(DestTy->getScalarType()->isPointerTy(),
2203          "IntToPtr result must be a pointer", &I);
2204   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2205          &I);
2206   if (SrcTy->isVectorTy()) {
2207     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2208     VectorType *VDest = dyn_cast<VectorType>(DestTy);
2209     Assert(VSrc->getNumElements() == VDest->getNumElements(),
2210            "IntToPtr Vector width mismatch", &I);
2211   }
2212   visitInstruction(I);
2213 }
2214
2215 void Verifier::visitBitCastInst(BitCastInst &I) {
2216   Assert(
2217       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2218       "Invalid bitcast", &I);
2219   visitInstruction(I);
2220 }
2221
2222 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2223   Type *SrcTy = I.getOperand(0)->getType();
2224   Type *DestTy = I.getType();
2225
2226   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2227          &I);
2228   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2229          &I);
2230   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2231          "AddrSpaceCast must be between different address spaces", &I);
2232   if (SrcTy->isVectorTy())
2233     Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2234            "AddrSpaceCast vector pointer number of elements mismatch", &I);
2235   visitInstruction(I);
2236 }
2237
2238 /// visitPHINode - Ensure that a PHI node is well formed.
2239 ///
2240 void Verifier::visitPHINode(PHINode &PN) {
2241   // Ensure that the PHI nodes are all grouped together at the top of the block.
2242   // This can be tested by checking whether the instruction before this is
2243   // either nonexistent (because this is begin()) or is a PHI node.  If not,
2244   // then there is some other instruction before a PHI.
2245   Assert(&PN == &PN.getParent()->front() ||
2246              isa<PHINode>(--BasicBlock::iterator(&PN)),
2247          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2248
2249   // Check that a PHI doesn't yield a Token.
2250   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2251
2252   // Check that all of the values of the PHI node have the same type as the
2253   // result, and that the incoming blocks are really basic blocks.
2254   for (Value *IncValue : PN.incoming_values()) {
2255     Assert(PN.getType() == IncValue->getType(),
2256            "PHI node operands are not the same type as the result!", &PN);
2257   }
2258
2259   // All other PHI node constraints are checked in the visitBasicBlock method.
2260
2261   visitInstruction(PN);
2262 }
2263
2264 void Verifier::VerifyCallSite(CallSite CS) {
2265   Instruction *I = CS.getInstruction();
2266
2267   Assert(CS.getCalledValue()->getType()->isPointerTy(),
2268          "Called function must be a pointer!", I);
2269   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2270
2271   Assert(FPTy->getElementType()->isFunctionTy(),
2272          "Called function is not pointer to function type!", I);
2273
2274   Assert(FPTy->getElementType() == CS.getFunctionType(),
2275          "Called function is not the same type as the call!", I);
2276
2277   FunctionType *FTy = CS.getFunctionType();
2278
2279   // Verify that the correct number of arguments are being passed
2280   if (FTy->isVarArg())
2281     Assert(CS.arg_size() >= FTy->getNumParams(),
2282            "Called function requires more parameters than were provided!", I);
2283   else
2284     Assert(CS.arg_size() == FTy->getNumParams(),
2285            "Incorrect number of arguments passed to called function!", I);
2286
2287   // Verify that all arguments to the call match the function type.
2288   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2289     Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2290            "Call parameter type does not match function signature!",
2291            CS.getArgument(i), FTy->getParamType(i), I);
2292
2293   AttributeSet Attrs = CS.getAttributes();
2294
2295   Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2296          "Attribute after last parameter!", I);
2297
2298   // Verify call attributes.
2299   VerifyFunctionAttrs(FTy, Attrs, I);
2300
2301   // Conservatively check the inalloca argument.
2302   // We have a bug if we can find that there is an underlying alloca without
2303   // inalloca.
2304   if (CS.hasInAllocaArgument()) {
2305     Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2306     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2307       Assert(AI->isUsedWithInAlloca(),
2308              "inalloca argument for call has mismatched alloca", AI, I);
2309   }
2310
2311   if (FTy->isVarArg()) {
2312     // FIXME? is 'nest' even legal here?
2313     bool SawNest = false;
2314     bool SawReturned = false;
2315
2316     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2317       if (Attrs.hasAttribute(Idx, Attribute::Nest))
2318         SawNest = true;
2319       if (Attrs.hasAttribute(Idx, Attribute::Returned))
2320         SawReturned = true;
2321     }
2322
2323     // Check attributes on the varargs part.
2324     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2325       Type *Ty = CS.getArgument(Idx-1)->getType();
2326       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2327
2328       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2329         Assert(!SawNest, "More than one parameter has attribute nest!", I);
2330         SawNest = true;
2331       }
2332
2333       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2334         Assert(!SawReturned, "More than one parameter has attribute returned!",
2335                I);
2336         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2337                "Incompatible argument and return types for 'returned' "
2338                "attribute",
2339                I);
2340         SawReturned = true;
2341       }
2342
2343       Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2344              "Attribute 'sret' cannot be used for vararg call arguments!", I);
2345
2346       if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2347         Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2348     }
2349   }
2350
2351   // Verify that there's no metadata unless it's a direct call to an intrinsic.
2352   if (CS.getCalledFunction() == nullptr ||
2353       !CS.getCalledFunction()->getName().startswith("llvm.")) {
2354     for (Type *ParamTy : FTy->params()) {
2355       Assert(!ParamTy->isMetadataTy(),
2356              "Function has metadata parameter but isn't an intrinsic", I);
2357       Assert(!ParamTy->isTokenTy(),
2358              "Function has token parameter but isn't an intrinsic", I);
2359     }
2360   }
2361
2362   // Verify that indirect calls don't return tokens.
2363   if (CS.getCalledFunction() == nullptr)
2364     Assert(!FTy->getReturnType()->isTokenTy(),
2365            "Return type cannot be token for indirect call!");
2366
2367   if (Function *F = CS.getCalledFunction())
2368     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2369       visitIntrinsicCallSite(ID, CS);
2370
2371   // Verify that a callsite has at most one "deopt" operand bundle.
2372   bool FoundDeoptBundle = false;
2373   for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2374     if (CS.getOperandBundleAt(i).getTagID() == LLVMContext::OB_deopt) {
2375       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2376       FoundDeoptBundle = true;
2377     }
2378   }
2379
2380   visitInstruction(*I);
2381 }
2382
2383 /// Two types are "congruent" if they are identical, or if they are both pointer
2384 /// types with different pointee types and the same address space.
2385 static bool isTypeCongruent(Type *L, Type *R) {
2386   if (L == R)
2387     return true;
2388   PointerType *PL = dyn_cast<PointerType>(L);
2389   PointerType *PR = dyn_cast<PointerType>(R);
2390   if (!PL || !PR)
2391     return false;
2392   return PL->getAddressSpace() == PR->getAddressSpace();
2393 }
2394
2395 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2396   static const Attribute::AttrKind ABIAttrs[] = {
2397       Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2398       Attribute::InReg, Attribute::Returned};
2399   AttrBuilder Copy;
2400   for (auto AK : ABIAttrs) {
2401     if (Attrs.hasAttribute(I + 1, AK))
2402       Copy.addAttribute(AK);
2403   }
2404   if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2405     Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2406   return Copy;
2407 }
2408
2409 void Verifier::verifyMustTailCall(CallInst &CI) {
2410   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2411
2412   // - The caller and callee prototypes must match.  Pointer types of
2413   //   parameters or return types may differ in pointee type, but not
2414   //   address space.
2415   Function *F = CI.getParent()->getParent();
2416   FunctionType *CallerTy = F->getFunctionType();
2417   FunctionType *CalleeTy = CI.getFunctionType();
2418   Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2419          "cannot guarantee tail call due to mismatched parameter counts", &CI);
2420   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2421          "cannot guarantee tail call due to mismatched varargs", &CI);
2422   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2423          "cannot guarantee tail call due to mismatched return types", &CI);
2424   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2425     Assert(
2426         isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2427         "cannot guarantee tail call due to mismatched parameter types", &CI);
2428   }
2429
2430   // - The calling conventions of the caller and callee must match.
2431   Assert(F->getCallingConv() == CI.getCallingConv(),
2432          "cannot guarantee tail call due to mismatched calling conv", &CI);
2433
2434   // - All ABI-impacting function attributes, such as sret, byval, inreg,
2435   //   returned, and inalloca, must match.
2436   AttributeSet CallerAttrs = F->getAttributes();
2437   AttributeSet CalleeAttrs = CI.getAttributes();
2438   for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2439     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2440     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2441     Assert(CallerABIAttrs == CalleeABIAttrs,
2442            "cannot guarantee tail call due to mismatched ABI impacting "
2443            "function attributes",
2444            &CI, CI.getOperand(I));
2445   }
2446
2447   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2448   //   or a pointer bitcast followed by a ret instruction.
2449   // - The ret instruction must return the (possibly bitcasted) value
2450   //   produced by the call or void.
2451   Value *RetVal = &CI;
2452   Instruction *Next = CI.getNextNode();
2453
2454   // Handle the optional bitcast.
2455   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2456     Assert(BI->getOperand(0) == RetVal,
2457            "bitcast following musttail call must use the call", BI);
2458     RetVal = BI;
2459     Next = BI->getNextNode();
2460   }
2461
2462   // Check the return.
2463   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2464   Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2465          &CI);
2466   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2467          "musttail call result must be returned", Ret);
2468 }
2469
2470 void Verifier::visitCallInst(CallInst &CI) {
2471   VerifyCallSite(&CI);
2472
2473   if (CI.isMustTailCall())
2474     verifyMustTailCall(CI);
2475 }
2476
2477 void Verifier::visitInvokeInst(InvokeInst &II) {
2478   VerifyCallSite(&II);
2479
2480   // Verify that the first non-PHI instruction of the unwind destination is an
2481   // exception handling instruction.
2482   Assert(
2483       II.getUnwindDest()->isEHPad(),
2484       "The unwind destination does not have an exception handling instruction!",
2485       &II);
2486
2487   visitTerminatorInst(II);
2488 }
2489
2490 /// visitBinaryOperator - Check that both arguments to the binary operator are
2491 /// of the same type!
2492 ///
2493 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2494   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2495          "Both operands to a binary operator are not of the same type!", &B);
2496
2497   switch (B.getOpcode()) {
2498   // Check that integer arithmetic operators are only used with
2499   // integral operands.
2500   case Instruction::Add:
2501   case Instruction::Sub:
2502   case Instruction::Mul:
2503   case Instruction::SDiv:
2504   case Instruction::UDiv:
2505   case Instruction::SRem:
2506   case Instruction::URem:
2507     Assert(B.getType()->isIntOrIntVectorTy(),
2508            "Integer arithmetic operators only work with integral types!", &B);
2509     Assert(B.getType() == B.getOperand(0)->getType(),
2510            "Integer arithmetic operators must have same type "
2511            "for operands and result!",
2512            &B);
2513     break;
2514   // Check that floating-point arithmetic operators are only used with
2515   // floating-point operands.
2516   case Instruction::FAdd:
2517   case Instruction::FSub:
2518   case Instruction::FMul:
2519   case Instruction::FDiv:
2520   case Instruction::FRem:
2521     Assert(B.getType()->isFPOrFPVectorTy(),
2522            "Floating-point arithmetic operators only work with "
2523            "floating-point types!",
2524            &B);
2525     Assert(B.getType() == B.getOperand(0)->getType(),
2526            "Floating-point arithmetic operators must have same type "
2527            "for operands and result!",
2528            &B);
2529     break;
2530   // Check that logical operators are only used with integral operands.
2531   case Instruction::And:
2532   case Instruction::Or:
2533   case Instruction::Xor:
2534     Assert(B.getType()->isIntOrIntVectorTy(),
2535            "Logical operators only work with integral types!", &B);
2536     Assert(B.getType() == B.getOperand(0)->getType(),
2537            "Logical operators must have same type for operands and result!",
2538            &B);
2539     break;
2540   case Instruction::Shl:
2541   case Instruction::LShr:
2542   case Instruction::AShr:
2543     Assert(B.getType()->isIntOrIntVectorTy(),
2544            "Shifts only work with integral types!", &B);
2545     Assert(B.getType() == B.getOperand(0)->getType(),
2546            "Shift return type must be same as operands!", &B);
2547     break;
2548   default:
2549     llvm_unreachable("Unknown BinaryOperator opcode!");
2550   }
2551
2552   visitInstruction(B);
2553 }
2554
2555 void Verifier::visitICmpInst(ICmpInst &IC) {
2556   // Check that the operands are the same type
2557   Type *Op0Ty = IC.getOperand(0)->getType();
2558   Type *Op1Ty = IC.getOperand(1)->getType();
2559   Assert(Op0Ty == Op1Ty,
2560          "Both operands to ICmp instruction are not of the same type!", &IC);
2561   // Check that the operands are the right type
2562   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2563          "Invalid operand types for ICmp instruction", &IC);
2564   // Check that the predicate is valid.
2565   Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2566              IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2567          "Invalid predicate in ICmp instruction!", &IC);
2568
2569   visitInstruction(IC);
2570 }
2571
2572 void Verifier::visitFCmpInst(FCmpInst &FC) {
2573   // Check that the operands are the same type
2574   Type *Op0Ty = FC.getOperand(0)->getType();
2575   Type *Op1Ty = FC.getOperand(1)->getType();
2576   Assert(Op0Ty == Op1Ty,
2577          "Both operands to FCmp instruction are not of the same type!", &FC);
2578   // Check that the operands are the right type
2579   Assert(Op0Ty->isFPOrFPVectorTy(),
2580          "Invalid operand types for FCmp instruction", &FC);
2581   // Check that the predicate is valid.
2582   Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2583              FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2584          "Invalid predicate in FCmp instruction!", &FC);
2585
2586   visitInstruction(FC);
2587 }
2588
2589 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2590   Assert(
2591       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2592       "Invalid extractelement operands!", &EI);
2593   visitInstruction(EI);
2594 }
2595
2596 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2597   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2598                                             IE.getOperand(2)),
2599          "Invalid insertelement operands!", &IE);
2600   visitInstruction(IE);
2601 }
2602
2603 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2604   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2605                                             SV.getOperand(2)),
2606          "Invalid shufflevector operands!", &SV);
2607   visitInstruction(SV);
2608 }
2609
2610 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2611   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2612
2613   Assert(isa<PointerType>(TargetTy),
2614          "GEP base pointer is not a vector or a vector of pointers", &GEP);
2615   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2616   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2617   Type *ElTy =
2618       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2619   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2620
2621   Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2622              GEP.getResultElementType() == ElTy,
2623          "GEP is not of right type for indices!", &GEP, ElTy);
2624
2625   if (GEP.getType()->isVectorTy()) {
2626     // Additional checks for vector GEPs.
2627     unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2628     if (GEP.getPointerOperandType()->isVectorTy())
2629       Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2630              "Vector GEP result width doesn't match operand's", &GEP);
2631     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2632       Type *IndexTy = Idxs[i]->getType();
2633       if (IndexTy->isVectorTy()) {
2634         unsigned IndexWidth = IndexTy->getVectorNumElements();
2635         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2636       }
2637       Assert(IndexTy->getScalarType()->isIntegerTy(),
2638              "All GEP indices should be of integer type");
2639     }
2640   }
2641   visitInstruction(GEP);
2642 }
2643
2644 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2645   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2646 }
2647
2648 void Verifier::visitRangeMetadata(Instruction& I,
2649                                   MDNode* Range, Type* Ty) {
2650   assert(Range &&
2651          Range == I.getMetadata(LLVMContext::MD_range) &&
2652          "precondition violation");
2653
2654   unsigned NumOperands = Range->getNumOperands();
2655   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2656   unsigned NumRanges = NumOperands / 2;
2657   Assert(NumRanges >= 1, "It should have at least one range!", Range);
2658
2659   ConstantRange LastRange(1); // Dummy initial value
2660   for (unsigned i = 0; i < NumRanges; ++i) {
2661     ConstantInt *Low =
2662         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2663     Assert(Low, "The lower limit must be an integer!", Low);
2664     ConstantInt *High =
2665         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2666     Assert(High, "The upper limit must be an integer!", High);
2667     Assert(High->getType() == Low->getType() && High->getType() == Ty,
2668            "Range types must match instruction type!", &I);
2669
2670     APInt HighV = High->getValue();
2671     APInt LowV = Low->getValue();
2672     ConstantRange CurRange(LowV, HighV);
2673     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2674            "Range must not be empty!", Range);
2675     if (i != 0) {
2676       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2677              "Intervals are overlapping", Range);
2678       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2679              Range);
2680       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2681              Range);
2682     }
2683     LastRange = ConstantRange(LowV, HighV);
2684   }
2685   if (NumRanges > 2) {
2686     APInt FirstLow =
2687         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2688     APInt FirstHigh =
2689         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2690     ConstantRange FirstRange(FirstLow, FirstHigh);
2691     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2692            "Intervals are overlapping", Range);
2693     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2694            Range);
2695   }
2696 }
2697
2698 void Verifier::visitLoadInst(LoadInst &LI) {
2699   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2700   Assert(PTy, "Load operand must be a pointer.", &LI);
2701   Type *ElTy = LI.getType();
2702   Assert(LI.getAlignment() <= Value::MaximumAlignment,
2703          "huge alignment values are unsupported", &LI);
2704   if (LI.isAtomic()) {
2705     Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2706            "Load cannot have Release ordering", &LI);
2707     Assert(LI.getAlignment() != 0,
2708            "Atomic load must specify explicit alignment", &LI);
2709     if (!ElTy->isPointerTy()) {
2710       Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2711              &LI, ElTy);
2712       unsigned Size = ElTy->getPrimitiveSizeInBits();
2713       Assert(Size >= 8 && !(Size & (Size - 1)),
2714              "atomic load operand must be power-of-two byte-sized integer", &LI,
2715              ElTy);
2716     }
2717   } else {
2718     Assert(LI.getSynchScope() == CrossThread,
2719            "Non-atomic load cannot have SynchronizationScope specified", &LI);
2720   }
2721
2722   visitInstruction(LI);
2723 }
2724
2725 void Verifier::visitStoreInst(StoreInst &SI) {
2726   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2727   Assert(PTy, "Store operand must be a pointer.", &SI);
2728   Type *ElTy = PTy->getElementType();
2729   Assert(ElTy == SI.getOperand(0)->getType(),
2730          "Stored value type does not match pointer operand type!", &SI, ElTy);
2731   Assert(SI.getAlignment() <= Value::MaximumAlignment,
2732          "huge alignment values are unsupported", &SI);
2733   if (SI.isAtomic()) {
2734     Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2735            "Store cannot have Acquire ordering", &SI);
2736     Assert(SI.getAlignment() != 0,
2737            "Atomic store must specify explicit alignment", &SI);
2738     if (!ElTy->isPointerTy()) {
2739       Assert(ElTy->isIntegerTy(),
2740              "atomic store operand must have integer type!", &SI, ElTy);
2741       unsigned Size = ElTy->getPrimitiveSizeInBits();
2742       Assert(Size >= 8 && !(Size & (Size - 1)),
2743              "atomic store operand must be power-of-two byte-sized integer",
2744              &SI, ElTy);
2745     }
2746   } else {
2747     Assert(SI.getSynchScope() == CrossThread,
2748            "Non-atomic store cannot have SynchronizationScope specified", &SI);
2749   }
2750   visitInstruction(SI);
2751 }
2752
2753 void Verifier::visitAllocaInst(AllocaInst &AI) {
2754   SmallPtrSet<Type*, 4> Visited;
2755   PointerType *PTy = AI.getType();
2756   Assert(PTy->getAddressSpace() == 0,
2757          "Allocation instruction pointer not in the generic address space!",
2758          &AI);
2759   Assert(AI.getAllocatedType()->isSized(&Visited),
2760          "Cannot allocate unsized type", &AI);
2761   Assert(AI.getArraySize()->getType()->isIntegerTy(),
2762          "Alloca array size must have integer type", &AI);
2763   Assert(AI.getAlignment() <= Value::MaximumAlignment,
2764          "huge alignment values are unsupported", &AI);
2765
2766   visitInstruction(AI);
2767 }
2768
2769 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2770
2771   // FIXME: more conditions???
2772   Assert(CXI.getSuccessOrdering() != NotAtomic,
2773          "cmpxchg instructions must be atomic.", &CXI);
2774   Assert(CXI.getFailureOrdering() != NotAtomic,
2775          "cmpxchg instructions must be atomic.", &CXI);
2776   Assert(CXI.getSuccessOrdering() != Unordered,
2777          "cmpxchg instructions cannot be unordered.", &CXI);
2778   Assert(CXI.getFailureOrdering() != Unordered,
2779          "cmpxchg instructions cannot be unordered.", &CXI);
2780   Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2781          "cmpxchg instructions be at least as constrained on success as fail",
2782          &CXI);
2783   Assert(CXI.getFailureOrdering() != Release &&
2784              CXI.getFailureOrdering() != AcquireRelease,
2785          "cmpxchg failure ordering cannot include release semantics", &CXI);
2786
2787   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2788   Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2789   Type *ElTy = PTy->getElementType();
2790   Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2791          ElTy);
2792   unsigned Size = ElTy->getPrimitiveSizeInBits();
2793   Assert(Size >= 8 && !(Size & (Size - 1)),
2794          "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2795   Assert(ElTy == CXI.getOperand(1)->getType(),
2796          "Expected value type does not match pointer operand type!", &CXI,
2797          ElTy);
2798   Assert(ElTy == CXI.getOperand(2)->getType(),
2799          "Stored value type does not match pointer operand type!", &CXI, ElTy);
2800   visitInstruction(CXI);
2801 }
2802
2803 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2804   Assert(RMWI.getOrdering() != NotAtomic,
2805          "atomicrmw instructions must be atomic.", &RMWI);
2806   Assert(RMWI.getOrdering() != Unordered,
2807          "atomicrmw instructions cannot be unordered.", &RMWI);
2808   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2809   Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2810   Type *ElTy = PTy->getElementType();
2811   Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2812          &RMWI, ElTy);
2813   unsigned Size = ElTy->getPrimitiveSizeInBits();
2814   Assert(Size >= 8 && !(Size & (Size - 1)),
2815          "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2816          ElTy);
2817   Assert(ElTy == RMWI.getOperand(1)->getType(),
2818          "Argument value type does not match pointer operand type!", &RMWI,
2819          ElTy);
2820   Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2821              RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2822          "Invalid binary operation!", &RMWI);
2823   visitInstruction(RMWI);
2824 }
2825
2826 void Verifier::visitFenceInst(FenceInst &FI) {
2827   const AtomicOrdering Ordering = FI.getOrdering();
2828   Assert(Ordering == Acquire || Ordering == Release ||
2829              Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2830          "fence instructions may only have "
2831          "acquire, release, acq_rel, or seq_cst ordering.",
2832          &FI);
2833   visitInstruction(FI);
2834 }
2835
2836 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2837   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2838                                           EVI.getIndices()) == EVI.getType(),
2839          "Invalid ExtractValueInst operands!", &EVI);
2840
2841   visitInstruction(EVI);
2842 }
2843
2844 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2845   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2846                                           IVI.getIndices()) ==
2847              IVI.getOperand(1)->getType(),
2848          "Invalid InsertValueInst operands!", &IVI);
2849
2850   visitInstruction(IVI);
2851 }
2852
2853 void Verifier::visitEHPadPredecessors(Instruction &I) {
2854   assert(I.isEHPad());
2855
2856   BasicBlock *BB = I.getParent();
2857   Function *F = BB->getParent();
2858
2859   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2860
2861   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2862     // The landingpad instruction defines its parent as a landing pad block. The
2863     // landing pad block may be branched to only by the unwind edge of an
2864     // invoke.
2865     for (BasicBlock *PredBB : predecessors(BB)) {
2866       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2867       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2868              "Block containing LandingPadInst must be jumped to "
2869              "only by the unwind edge of an invoke.",
2870              LPI);
2871     }
2872     return;
2873   }
2874
2875   for (BasicBlock *PredBB : predecessors(BB)) {
2876     TerminatorInst *TI = PredBB->getTerminator();
2877     if (auto *II = dyn_cast<InvokeInst>(TI))
2878       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
2879              "EH pad must be jumped to via an unwind edge", &I, II);
2880     else if (auto *CPI = dyn_cast<CatchPadInst>(TI))
2881       Assert(CPI->getUnwindDest() == BB && CPI->getNormalDest() != BB,
2882              "EH pad must be jumped to via an unwind edge", &I, CPI);
2883     else if (isa<CatchEndPadInst>(TI))
2884       ;
2885     else if (isa<CleanupReturnInst>(TI))
2886       ;
2887     else if (isa<CleanupEndPadInst>(TI))
2888       ;
2889     else if (isa<TerminatePadInst>(TI))
2890       ;
2891     else
2892       Assert(false, "EH pad must be jumped to via an unwind edge", &I, TI);
2893   }
2894 }
2895
2896 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2897   // The landingpad instruction is ill-formed if it doesn't have any clauses and
2898   // isn't a cleanup.
2899   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2900          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2901
2902   visitEHPadPredecessors(LPI);
2903
2904   if (!LandingPadResultTy)
2905     LandingPadResultTy = LPI.getType();
2906   else
2907     Assert(LandingPadResultTy == LPI.getType(),
2908            "The landingpad instruction should have a consistent result type "
2909            "inside a function.",
2910            &LPI);
2911
2912   Function *F = LPI.getParent()->getParent();
2913   Assert(F->hasPersonalityFn(),
2914          "LandingPadInst needs to be in a function with a personality.", &LPI);
2915
2916   // The landingpad instruction must be the first non-PHI instruction in the
2917   // block.
2918   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2919          "LandingPadInst not the first non-PHI instruction in the block.",
2920          &LPI);
2921
2922   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2923     Constant *Clause = LPI.getClause(i);
2924     if (LPI.isCatch(i)) {
2925       Assert(isa<PointerType>(Clause->getType()),
2926              "Catch operand does not have pointer type!", &LPI);
2927     } else {
2928       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2929       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2930              "Filter operand is not an array of constants!", &LPI);
2931     }
2932   }
2933
2934   visitInstruction(LPI);
2935 }
2936
2937 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
2938   visitEHPadPredecessors(CPI);
2939
2940   BasicBlock *BB = CPI.getParent();
2941   Function *F = BB->getParent();
2942   Assert(F->hasPersonalityFn(),
2943          "CatchPadInst needs to be in a function with a personality.", &CPI);
2944
2945   // The catchpad instruction must be the first non-PHI instruction in the
2946   // block.
2947   Assert(BB->getFirstNonPHI() == &CPI,
2948          "CatchPadInst not the first non-PHI instruction in the block.",
2949          &CPI);
2950
2951   if (!BB->getSinglePredecessor())
2952     for (BasicBlock *PredBB : predecessors(BB)) {
2953       Assert(!isa<CatchPadInst>(PredBB->getTerminator()),
2954              "CatchPadInst with CatchPadInst predecessor cannot have any other "
2955              "predecessors.",
2956              &CPI);
2957     }
2958
2959   BasicBlock *UnwindDest = CPI.getUnwindDest();
2960   Instruction *I = UnwindDest->getFirstNonPHI();
2961   Assert(
2962       isa<CatchPadInst>(I) || isa<CatchEndPadInst>(I),
2963       "CatchPadInst must unwind to a CatchPadInst or a CatchEndPadInst.",
2964       &CPI);
2965
2966   visitTerminatorInst(CPI);
2967 }
2968
2969 void Verifier::visitCatchEndPadInst(CatchEndPadInst &CEPI) {
2970   visitEHPadPredecessors(CEPI);
2971
2972   BasicBlock *BB = CEPI.getParent();
2973   Function *F = BB->getParent();
2974   Assert(F->hasPersonalityFn(),
2975          "CatchEndPadInst needs to be in a function with a personality.",
2976          &CEPI);
2977
2978   // The catchendpad instruction must be the first non-PHI instruction in the
2979   // block.
2980   Assert(BB->getFirstNonPHI() == &CEPI,
2981          "CatchEndPadInst not the first non-PHI instruction in the block.",
2982          &CEPI);
2983
2984   unsigned CatchPadsSeen = 0;
2985   for (BasicBlock *PredBB : predecessors(BB))
2986     if (isa<CatchPadInst>(PredBB->getTerminator()))
2987       ++CatchPadsSeen;
2988
2989   Assert(CatchPadsSeen <= 1, "CatchEndPadInst must have no more than one "
2990                                "CatchPadInst predecessor.",
2991          &CEPI);
2992
2993   if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
2994     Instruction *I = UnwindDest->getFirstNonPHI();
2995     Assert(
2996         I->isEHPad() && !isa<LandingPadInst>(I),
2997         "CatchEndPad must unwind to an EH block which is not a landingpad.",
2998         &CEPI);
2999   }
3000
3001   visitTerminatorInst(CEPI);
3002 }
3003
3004 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3005   visitEHPadPredecessors(CPI);
3006
3007   BasicBlock *BB = CPI.getParent();
3008
3009   Function *F = BB->getParent();
3010   Assert(F->hasPersonalityFn(),
3011          "CleanupPadInst needs to be in a function with a personality.", &CPI);
3012
3013   // The cleanuppad instruction must be the first non-PHI instruction in the
3014   // block.
3015   Assert(BB->getFirstNonPHI() == &CPI,
3016          "CleanupPadInst not the first non-PHI instruction in the block.",
3017          &CPI);
3018
3019   User *FirstUser = nullptr;
3020   BasicBlock *FirstUnwindDest = nullptr;
3021   for (User *U : CPI.users()) {
3022     BasicBlock *UnwindDest;
3023     if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(U)) {
3024       UnwindDest = CRI->getUnwindDest();
3025     } else {
3026       UnwindDest = cast<CleanupEndPadInst>(U)->getUnwindDest();
3027     }
3028
3029     if (!FirstUser) {
3030       FirstUser = U;
3031       FirstUnwindDest = UnwindDest;
3032     } else {
3033       Assert(UnwindDest == FirstUnwindDest,
3034              "Cleanuprets/cleanupendpads from the same cleanuppad must "
3035              "have the same unwind destination",
3036              FirstUser, U);
3037     }
3038   }
3039
3040   visitInstruction(CPI);
3041 }
3042
3043 void Verifier::visitCleanupEndPadInst(CleanupEndPadInst &CEPI) {
3044   visitEHPadPredecessors(CEPI);
3045
3046   BasicBlock *BB = CEPI.getParent();
3047   Function *F = BB->getParent();
3048   Assert(F->hasPersonalityFn(),
3049          "CleanupEndPadInst needs to be in a function with a personality.",
3050          &CEPI);
3051
3052   // The cleanupendpad instruction must be the first non-PHI instruction in the
3053   // block.
3054   Assert(BB->getFirstNonPHI() == &CEPI,
3055          "CleanupEndPadInst not the first non-PHI instruction in the block.",
3056          &CEPI);
3057
3058   if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
3059     Instruction *I = UnwindDest->getFirstNonPHI();
3060     Assert(
3061         I->isEHPad() && !isa<LandingPadInst>(I),
3062         "CleanupEndPad must unwind to an EH block which is not a landingpad.",
3063         &CEPI);
3064   }
3065
3066   visitTerminatorInst(CEPI);
3067 }
3068
3069 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3070   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3071     Instruction *I = UnwindDest->getFirstNonPHI();
3072     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3073            "CleanupReturnInst must unwind to an EH block which is not a "
3074            "landingpad.",
3075            &CRI);
3076   }
3077
3078   visitTerminatorInst(CRI);
3079 }
3080
3081 void Verifier::visitTerminatePadInst(TerminatePadInst &TPI) {
3082   visitEHPadPredecessors(TPI);
3083
3084   BasicBlock *BB = TPI.getParent();
3085   Function *F = BB->getParent();
3086   Assert(F->hasPersonalityFn(),
3087          "TerminatePadInst needs to be in a function with a personality.",
3088          &TPI);
3089
3090   // The terminatepad instruction must be the first non-PHI instruction in the
3091   // block.
3092   Assert(BB->getFirstNonPHI() == &TPI,
3093          "TerminatePadInst not the first non-PHI instruction in the block.",
3094          &TPI);
3095
3096   if (BasicBlock *UnwindDest = TPI.getUnwindDest()) {
3097     Instruction *I = UnwindDest->getFirstNonPHI();
3098     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3099            "TerminatePadInst must unwind to an EH block which is not a "
3100            "landingpad.",
3101            &TPI);
3102   }
3103
3104   visitTerminatorInst(TPI);
3105 }
3106
3107 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3108   Instruction *Op = cast<Instruction>(I.getOperand(i));
3109   // If the we have an invalid invoke, don't try to compute the dominance.
3110   // We already reject it in the invoke specific checks and the dominance
3111   // computation doesn't handle multiple edges.
3112   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3113     if (II->getNormalDest() == II->getUnwindDest())
3114       return;
3115   }
3116
3117   const Use &U = I.getOperandUse(i);
3118   Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3119          "Instruction does not dominate all uses!", Op, &I);
3120 }
3121
3122 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3123   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3124          "apply only to pointer types", &I);
3125   Assert(isa<LoadInst>(I),
3126          "dereferenceable, dereferenceable_or_null apply only to load"
3127          " instructions, use attributes for calls or invokes", &I);
3128   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3129          "take one operand!", &I);
3130   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3131   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3132          "dereferenceable_or_null metadata value must be an i64!", &I);
3133 }
3134
3135 /// verifyInstruction - Verify that an instruction is well formed.
3136 ///
3137 void Verifier::visitInstruction(Instruction &I) {
3138   BasicBlock *BB = I.getParent();
3139   Assert(BB, "Instruction not embedded in basic block!", &I);
3140
3141   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
3142     for (User *U : I.users()) {
3143       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3144              "Only PHI nodes may reference their own value!", &I);
3145     }
3146   }
3147
3148   // Check that void typed values don't have names
3149   Assert(!I.getType()->isVoidTy() || !I.hasName(),
3150          "Instruction has a name, but provides a void value!", &I);
3151
3152   // Check that the return value of the instruction is either void or a legal
3153   // value type.
3154   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3155          "Instruction returns a non-scalar type!", &I);
3156
3157   // Check that the instruction doesn't produce metadata. Calls are already
3158   // checked against the callee type.
3159   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3160          "Invalid use of metadata!", &I);
3161
3162   // Check that all uses of the instruction, if they are instructions
3163   // themselves, actually have parent basic blocks.  If the use is not an
3164   // instruction, it is an error!
3165   for (Use &U : I.uses()) {
3166     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3167       Assert(Used->getParent() != nullptr,
3168              "Instruction referencing"
3169              " instruction not embedded in a basic block!",
3170              &I, Used);
3171     else {
3172       CheckFailed("Use of instruction is not an instruction!", U);
3173       return;
3174     }
3175   }
3176
3177   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3178     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3179
3180     // Check to make sure that only first-class-values are operands to
3181     // instructions.
3182     if (!I.getOperand(i)->getType()->isFirstClassType()) {
3183       Assert(0, "Instruction operands must be first-class values!", &I);
3184     }
3185
3186     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3187       // Check to make sure that the "address of" an intrinsic function is never
3188       // taken.
3189       Assert(
3190           !F->isIntrinsic() ||
3191               i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3192           "Cannot take the address of an intrinsic!", &I);
3193       Assert(
3194           !F->isIntrinsic() || isa<CallInst>(I) ||
3195               F->getIntrinsicID() == Intrinsic::donothing ||
3196               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3197               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3198               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3199           "Cannot invoke an intrinsinc other than"
3200           " donothing or patchpoint",
3201           &I);
3202       Assert(F->getParent() == M, "Referencing function in another module!",
3203              &I, M, F, F->getParent());
3204     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3205       Assert(OpBB->getParent() == BB->getParent(),
3206              "Referring to a basic block in another function!", &I);
3207     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3208       Assert(OpArg->getParent() == BB->getParent(),
3209              "Referring to an argument in another function!", &I);
3210     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3211       Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent());
3212     } else if (isa<Instruction>(I.getOperand(i))) {
3213       verifyDominatesUse(I, i);
3214     } else if (isa<InlineAsm>(I.getOperand(i))) {
3215       Assert((i + 1 == e && isa<CallInst>(I)) ||
3216                  (i + 3 == e && isa<InvokeInst>(I)),
3217              "Cannot take the address of an inline asm!", &I);
3218     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3219       if (CE->getType()->isPtrOrPtrVectorTy()) {
3220         // If we have a ConstantExpr pointer, we need to see if it came from an
3221         // illegal bitcast (inttoptr <constant int> )
3222         SmallVector<const ConstantExpr *, 4> Stack;
3223         SmallPtrSet<const ConstantExpr *, 4> Visited;
3224         Stack.push_back(CE);
3225
3226         while (!Stack.empty()) {
3227           const ConstantExpr *V = Stack.pop_back_val();
3228           if (!Visited.insert(V).second)
3229             continue;
3230
3231           VerifyConstantExprBitcastType(V);
3232
3233           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
3234             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
3235               Stack.push_back(Op);
3236           }
3237         }
3238       }
3239     }
3240   }
3241
3242   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3243     Assert(I.getType()->isFPOrFPVectorTy(),
3244            "fpmath requires a floating point result!", &I);
3245     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3246     if (ConstantFP *CFP0 =
3247             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3248       APFloat Accuracy = CFP0->getValueAPF();
3249       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3250              "fpmath accuracy not a positive number!", &I);
3251     } else {
3252       Assert(false, "invalid fpmath accuracy!", &I);
3253     }
3254   }
3255
3256   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3257     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3258            "Ranges are only for loads, calls and invokes!", &I);
3259     visitRangeMetadata(I, Range, I.getType());
3260   }
3261
3262   if (I.getMetadata(LLVMContext::MD_nonnull)) {
3263     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3264            &I);
3265     Assert(isa<LoadInst>(I),
3266            "nonnull applies only to load instructions, use attributes"
3267            " for calls or invokes",
3268            &I);
3269   }
3270
3271   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3272     visitDereferenceableMetadata(I, MD);
3273
3274   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3275     visitDereferenceableMetadata(I, MD);
3276
3277   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3278     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3279            &I);
3280     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3281            "use attributes for calls or invokes", &I);
3282     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3283     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3284     Assert(CI && CI->getType()->isIntegerTy(64),
3285            "align metadata value must be an i64!", &I);
3286     uint64_t Align = CI->getZExtValue();
3287     Assert(isPowerOf2_64(Align),
3288            "align metadata value must be a power of 2!", &I);
3289     Assert(Align <= Value::MaximumAlignment,
3290            "alignment is larger that implementation defined limit", &I);
3291   }
3292
3293   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3294     Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3295     visitMDNode(*N);
3296   }
3297
3298   InstsInThisBlock.insert(&I);
3299 }
3300
3301 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3302 /// intrinsic argument or return value) matches the type constraints specified
3303 /// by the .td file (e.g. an "any integer" argument really is an integer).
3304 ///
3305 /// This return true on error but does not print a message.
3306 bool Verifier::VerifyIntrinsicType(Type *Ty,
3307                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
3308                                    SmallVectorImpl<Type*> &ArgTys) {
3309   using namespace Intrinsic;
3310
3311   // If we ran out of descriptors, there are too many arguments.
3312   if (Infos.empty()) return true;
3313   IITDescriptor D = Infos.front();
3314   Infos = Infos.slice(1);
3315
3316   switch (D.Kind) {
3317   case IITDescriptor::Void: return !Ty->isVoidTy();
3318   case IITDescriptor::VarArg: return true;
3319   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
3320   case IITDescriptor::Token: return !Ty->isTokenTy();
3321   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3322   case IITDescriptor::Half: return !Ty->isHalfTy();
3323   case IITDescriptor::Float: return !Ty->isFloatTy();
3324   case IITDescriptor::Double: return !Ty->isDoubleTy();
3325   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3326   case IITDescriptor::Vector: {
3327     VectorType *VT = dyn_cast<VectorType>(Ty);
3328     return !VT || VT->getNumElements() != D.Vector_Width ||
3329            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3330   }
3331   case IITDescriptor::Pointer: {
3332     PointerType *PT = dyn_cast<PointerType>(Ty);
3333     return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3334            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3335   }
3336
3337   case IITDescriptor::Struct: {
3338     StructType *ST = dyn_cast<StructType>(Ty);
3339     if (!ST || ST->getNumElements() != D.Struct_NumElements)
3340       return true;
3341
3342     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3343       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3344         return true;
3345     return false;
3346   }
3347
3348   case IITDescriptor::Argument:
3349     // Two cases here - If this is the second occurrence of an argument, verify
3350     // that the later instance matches the previous instance.
3351     if (D.getArgumentNumber() < ArgTys.size())
3352       return Ty != ArgTys[D.getArgumentNumber()];
3353
3354     // Otherwise, if this is the first instance of an argument, record it and
3355     // verify the "Any" kind.
3356     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3357     ArgTys.push_back(Ty);
3358
3359     switch (D.getArgumentKind()) {
3360     case IITDescriptor::AK_Any:        return false; // Success
3361     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3362     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
3363     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
3364     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3365     }
3366     llvm_unreachable("all argument kinds not covered");
3367
3368   case IITDescriptor::ExtendArgument: {
3369     // This may only be used when referring to a previous vector argument.
3370     if (D.getArgumentNumber() >= ArgTys.size())
3371       return true;
3372
3373     Type *NewTy = ArgTys[D.getArgumentNumber()];
3374     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3375       NewTy = VectorType::getExtendedElementVectorType(VTy);
3376     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3377       NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3378     else
3379       return true;
3380
3381     return Ty != NewTy;
3382   }
3383   case IITDescriptor::TruncArgument: {
3384     // This may only be used when referring to a previous vector argument.
3385     if (D.getArgumentNumber() >= ArgTys.size())
3386       return true;
3387
3388     Type *NewTy = ArgTys[D.getArgumentNumber()];
3389     if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3390       NewTy = VectorType::getTruncatedElementVectorType(VTy);
3391     else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3392       NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3393     else
3394       return true;
3395
3396     return Ty != NewTy;
3397   }
3398   case IITDescriptor::HalfVecArgument:
3399     // This may only be used when referring to a previous vector argument.
3400     return D.getArgumentNumber() >= ArgTys.size() ||
3401            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3402            VectorType::getHalfElementsVectorType(
3403                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3404   case IITDescriptor::SameVecWidthArgument: {
3405     if (D.getArgumentNumber() >= ArgTys.size())
3406       return true;
3407     VectorType * ReferenceType =
3408       dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3409     VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3410     if (!ThisArgType || !ReferenceType || 
3411         (ReferenceType->getVectorNumElements() !=
3412          ThisArgType->getVectorNumElements()))
3413       return true;
3414     return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3415                                Infos, ArgTys);
3416   }
3417   case IITDescriptor::PtrToArgument: {
3418     if (D.getArgumentNumber() >= ArgTys.size())
3419       return true;
3420     Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3421     PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3422     return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3423   }
3424   case IITDescriptor::VecOfPtrsToElt: {
3425     if (D.getArgumentNumber() >= ArgTys.size())
3426       return true;
3427     VectorType * ReferenceType =
3428       dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3429     VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3430     if (!ThisArgVecTy || !ReferenceType || 
3431         (ReferenceType->getVectorNumElements() !=
3432          ThisArgVecTy->getVectorNumElements()))
3433       return true;
3434     PointerType *ThisArgEltTy =
3435       dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3436     if (!ThisArgEltTy)
3437       return true;
3438     return ThisArgEltTy->getElementType() !=
3439            ReferenceType->getVectorElementType();
3440   }
3441   }
3442   llvm_unreachable("unhandled");
3443 }
3444
3445 /// \brief Verify if the intrinsic has variable arguments.
3446 /// This method is intended to be called after all the fixed arguments have been
3447 /// verified first.
3448 ///
3449 /// This method returns true on error and does not print an error message.
3450 bool
3451 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3452                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3453   using namespace Intrinsic;
3454
3455   // If there are no descriptors left, then it can't be a vararg.
3456   if (Infos.empty())
3457     return isVarArg;
3458
3459   // There should be only one descriptor remaining at this point.
3460   if (Infos.size() != 1)
3461     return true;
3462
3463   // Check and verify the descriptor.
3464   IITDescriptor D = Infos.front();
3465   Infos = Infos.slice(1);
3466   if (D.Kind == IITDescriptor::VarArg)
3467     return !isVarArg;
3468
3469   return true;
3470 }
3471
3472 /// Allow intrinsics to be verified in different ways.
3473 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3474   Function *IF = CS.getCalledFunction();
3475   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3476          IF);
3477
3478   // Verify that the intrinsic prototype lines up with what the .td files
3479   // describe.
3480   FunctionType *IFTy = IF->getFunctionType();
3481   bool IsVarArg = IFTy->isVarArg();
3482
3483   SmallVector<Intrinsic::IITDescriptor, 8> Table;
3484   getIntrinsicInfoTableEntries(ID, Table);
3485   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3486
3487   SmallVector<Type *, 4> ArgTys;
3488   Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3489          "Intrinsic has incorrect return type!", IF);
3490   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3491     Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3492            "Intrinsic has incorrect argument type!", IF);
3493
3494   // Verify if the intrinsic call matches the vararg property.
3495   if (IsVarArg)
3496     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3497            "Intrinsic was not defined with variable arguments!", IF);
3498   else
3499     Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3500            "Callsite was not defined with variable arguments!", IF);
3501
3502   // All descriptors should be absorbed by now.
3503   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3504
3505   // Now that we have the intrinsic ID and the actual argument types (and we
3506   // know they are legal for the intrinsic!) get the intrinsic name through the
3507   // usual means.  This allows us to verify the mangling of argument types into
3508   // the name.
3509   const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3510   Assert(ExpectedName == IF->getName(),
3511          "Intrinsic name not mangled correctly for type arguments! "
3512          "Should be: " +
3513              ExpectedName,
3514          IF);
3515
3516   // If the intrinsic takes MDNode arguments, verify that they are either global
3517   // or are local to *this* function.
3518   for (Value *V : CS.args()) 
3519     if (auto *MD = dyn_cast<MetadataAsValue>(V))
3520       visitMetadataAsValue(*MD, CS.getCaller());
3521
3522   switch (ID) {
3523   default:
3524     break;
3525   case Intrinsic::ctlz:  // llvm.ctlz
3526   case Intrinsic::cttz:  // llvm.cttz
3527     Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3528            "is_zero_undef argument of bit counting intrinsics must be a "
3529            "constant int",
3530            CS);
3531     break;
3532   case Intrinsic::dbg_declare: // llvm.dbg.declare
3533     Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3534            "invalid llvm.dbg.declare intrinsic call 1", CS);
3535     visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3536     break;
3537   case Intrinsic::dbg_value: // llvm.dbg.value
3538     visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3539     break;
3540   case Intrinsic::memcpy:
3541   case Intrinsic::memmove:
3542   case Intrinsic::memset: {
3543     ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3544     Assert(AlignCI,
3545            "alignment argument of memory intrinsics must be a constant int",
3546            CS);
3547     const APInt &AlignVal = AlignCI->getValue();
3548     Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3549            "alignment argument of memory intrinsics must be a power of 2", CS);
3550     Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3551            "isvolatile argument of memory intrinsics must be a constant int",
3552            CS);
3553     break;
3554   }
3555   case Intrinsic::gcroot:
3556   case Intrinsic::gcwrite:
3557   case Intrinsic::gcread:
3558     if (ID == Intrinsic::gcroot) {
3559       AllocaInst *AI =
3560         dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3561       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3562       Assert(isa<Constant>(CS.getArgOperand(1)),
3563              "llvm.gcroot parameter #2 must be a constant.", CS);
3564       if (!AI->getAllocatedType()->isPointerTy()) {
3565         Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3566                "llvm.gcroot parameter #1 must either be a pointer alloca, "
3567                "or argument #2 must be a non-null constant.",
3568                CS);
3569       }
3570     }
3571
3572     Assert(CS.getParent()->getParent()->hasGC(),
3573            "Enclosing function does not use GC.", CS);
3574     break;
3575   case Intrinsic::init_trampoline:
3576     Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3577            "llvm.init_trampoline parameter #2 must resolve to a function.",
3578            CS);
3579     break;
3580   case Intrinsic::prefetch:
3581     Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3582                isa<ConstantInt>(CS.getArgOperand(2)) &&
3583                cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3584                cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3585            "invalid arguments to llvm.prefetch", CS);
3586     break;
3587   case Intrinsic::stackprotector:
3588     Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3589            "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3590     break;
3591   case Intrinsic::lifetime_start:
3592   case Intrinsic::lifetime_end:
3593   case Intrinsic::invariant_start:
3594     Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3595            "size argument of memory use markers must be a constant integer",
3596            CS);
3597     break;
3598   case Intrinsic::invariant_end:
3599     Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3600            "llvm.invariant.end parameter #2 must be a constant integer", CS);
3601     break;
3602
3603   case Intrinsic::localescape: {
3604     BasicBlock *BB = CS.getParent();
3605     Assert(BB == &BB->getParent()->front(),
3606            "llvm.localescape used outside of entry block", CS);
3607     Assert(!SawFrameEscape,
3608            "multiple calls to llvm.localescape in one function", CS);
3609     for (Value *Arg : CS.args()) {
3610       if (isa<ConstantPointerNull>(Arg))
3611         continue; // Null values are allowed as placeholders.
3612       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3613       Assert(AI && AI->isStaticAlloca(),
3614              "llvm.localescape only accepts static allocas", CS);
3615     }
3616     FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3617     SawFrameEscape = true;
3618     break;
3619   }
3620   case Intrinsic::localrecover: {
3621     Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3622     Function *Fn = dyn_cast<Function>(FnArg);
3623     Assert(Fn && !Fn->isDeclaration(),
3624            "llvm.localrecover first "
3625            "argument must be function defined in this module",
3626            CS);
3627     auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3628     Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3629            CS);
3630     auto &Entry = FrameEscapeInfo[Fn];
3631     Entry.second = unsigned(
3632         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3633     break;
3634   }
3635
3636   case Intrinsic::experimental_gc_statepoint:
3637     Assert(!CS.isInlineAsm(),
3638            "gc.statepoint support for inline assembly unimplemented", CS);
3639     Assert(CS.getParent()->getParent()->hasGC(),
3640            "Enclosing function does not use GC.", CS);
3641
3642     VerifyStatepoint(CS);
3643     break;
3644   case Intrinsic::experimental_gc_result_int:
3645   case Intrinsic::experimental_gc_result_float:
3646   case Intrinsic::experimental_gc_result_ptr:
3647   case Intrinsic::experimental_gc_result: {
3648     Assert(CS.getParent()->getParent()->hasGC(),
3649            "Enclosing function does not use GC.", CS);
3650     // Are we tied to a statepoint properly?
3651     CallSite StatepointCS(CS.getArgOperand(0));
3652     const Function *StatepointFn =
3653       StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3654     Assert(StatepointFn && StatepointFn->isDeclaration() &&
3655                StatepointFn->getIntrinsicID() ==
3656                    Intrinsic::experimental_gc_statepoint,
3657            "gc.result operand #1 must be from a statepoint", CS,
3658            CS.getArgOperand(0));
3659
3660     // Assert that result type matches wrapped callee.
3661     const Value *Target = StatepointCS.getArgument(2);
3662     auto *PT = cast<PointerType>(Target->getType());
3663     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3664     Assert(CS.getType() == TargetFuncType->getReturnType(),
3665            "gc.result result type does not match wrapped callee", CS);
3666     break;
3667   }
3668   case Intrinsic::experimental_gc_relocate: {
3669     Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3670
3671     // Check that this relocate is correctly tied to the statepoint
3672
3673     // This is case for relocate on the unwinding path of an invoke statepoint
3674     if (ExtractValueInst *ExtractValue =
3675           dyn_cast<ExtractValueInst>(CS.getArgOperand(0))) {
3676       Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3677              "gc relocate on unwind path incorrectly linked to the statepoint",
3678              CS);
3679
3680       const BasicBlock *InvokeBB =
3681         ExtractValue->getParent()->getUniquePredecessor();
3682
3683       // Landingpad relocates should have only one predecessor with invoke
3684       // statepoint terminator
3685       Assert(InvokeBB, "safepoints should have unique landingpads",
3686              ExtractValue->getParent());
3687       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3688              InvokeBB);
3689       Assert(isStatepoint(InvokeBB->getTerminator()),
3690              "gc relocate should be linked to a statepoint", InvokeBB);
3691     }
3692     else {
3693       // In all other cases relocate should be tied to the statepoint directly.
3694       // This covers relocates on a normal return path of invoke statepoint and
3695       // relocates of a call statepoint
3696       auto Token = CS.getArgOperand(0);
3697       Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3698              "gc relocate is incorrectly tied to the statepoint", CS, Token);
3699     }
3700
3701     // Verify rest of the relocate arguments
3702
3703     GCRelocateOperands Ops(CS);
3704     ImmutableCallSite StatepointCS(Ops.getStatepoint());
3705
3706     // Both the base and derived must be piped through the safepoint
3707     Value* Base = CS.getArgOperand(1);
3708     Assert(isa<ConstantInt>(Base),
3709            "gc.relocate operand #2 must be integer offset", CS);
3710
3711     Value* Derived = CS.getArgOperand(2);
3712     Assert(isa<ConstantInt>(Derived),
3713            "gc.relocate operand #3 must be integer offset", CS);
3714
3715     const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3716     const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3717     // Check the bounds
3718     Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3719            "gc.relocate: statepoint base index out of bounds", CS);
3720     Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3721            "gc.relocate: statepoint derived index out of bounds", CS);
3722
3723     // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3724     // section of the statepoint's argument
3725     Assert(StatepointCS.arg_size() > 0,
3726            "gc.statepoint: insufficient arguments");
3727     Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3728            "gc.statement: number of call arguments must be constant integer");
3729     const unsigned NumCallArgs =
3730         cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3731     Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3732            "gc.statepoint: mismatch in number of call arguments");
3733     Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3734            "gc.statepoint: number of transition arguments must be "
3735            "a constant integer");
3736     const int NumTransitionArgs =
3737         cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3738             ->getZExtValue();
3739     const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3740     Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3741            "gc.statepoint: number of deoptimization arguments must be "
3742            "a constant integer");
3743     const int NumDeoptArgs =
3744       cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3745     const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3746     const int GCParamArgsEnd = StatepointCS.arg_size();
3747     Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3748            "gc.relocate: statepoint base index doesn't fall within the "
3749            "'gc parameters' section of the statepoint call",
3750            CS);
3751     Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3752            "gc.relocate: statepoint derived index doesn't fall within the "
3753            "'gc parameters' section of the statepoint call",
3754            CS);
3755
3756     // Relocated value must be a pointer type, but gc_relocate does not need to return the
3757     // same pointer type as the relocated pointer. It can be casted to the correct type later
3758     // if it's desired. However, they must have the same address space.
3759     GCRelocateOperands Operands(CS);
3760     Assert(Operands.getDerivedPtr()->getType()->isPointerTy(),
3761            "gc.relocate: relocated value must be a gc pointer", CS);
3762
3763     // gc_relocate return type must be a pointer type, and is verified earlier in
3764     // VerifyIntrinsicType().
3765     Assert(cast<PointerType>(CS.getType())->getAddressSpace() ==
3766            cast<PointerType>(Operands.getDerivedPtr()->getType())->getAddressSpace(),
3767            "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3768     break;
3769   }
3770   case Intrinsic::eh_exceptioncode:
3771   case Intrinsic::eh_exceptionpointer: {
3772     Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3773            "eh.exceptionpointer argument must be a catchpad", CS);
3774     break;
3775   }
3776   };
3777 }
3778
3779 /// \brief Carefully grab the subprogram from a local scope.
3780 ///
3781 /// This carefully grabs the subprogram from a local scope, avoiding the
3782 /// built-in assertions that would typically fire.
3783 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3784   if (!LocalScope)
3785     return nullptr;
3786
3787   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3788     return SP;
3789
3790   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3791     return getSubprogram(LB->getRawScope());
3792
3793   // Just return null; broken scope chains are checked elsewhere.
3794   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3795   return nullptr;
3796 }
3797
3798 template <class DbgIntrinsicTy>
3799 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3800   auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3801   Assert(isa<ValueAsMetadata>(MD) ||
3802              (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3803          "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3804   Assert(isa<DILocalVariable>(DII.getRawVariable()),
3805          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3806          DII.getRawVariable());
3807   Assert(isa<DIExpression>(DII.getRawExpression()),
3808          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3809          DII.getRawExpression());
3810
3811   // Ignore broken !dbg attachments; they're checked elsewhere.
3812   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3813     if (!isa<DILocation>(N))
3814       return;
3815
3816   BasicBlock *BB = DII.getParent();
3817   Function *F = BB ? BB->getParent() : nullptr;
3818
3819   // The scopes for variables and !dbg attachments must agree.
3820   DILocalVariable *Var = DII.getVariable();
3821   DILocation *Loc = DII.getDebugLoc();
3822   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3823          &DII, BB, F);
3824
3825   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3826   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3827   if (!VarSP || !LocSP)
3828     return; // Broken scope chains are checked elsewhere.
3829
3830   Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3831                              " variable and !dbg attachment",
3832          &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3833          Loc->getScope()->getSubprogram());
3834 }
3835
3836 template <class MapTy>
3837 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3838   // Be careful of broken types (checked elsewhere).
3839   const Metadata *RawType = V.getRawType();
3840   while (RawType) {
3841     // Try to get the size directly.
3842     if (auto *T = dyn_cast<DIType>(RawType))
3843       if (uint64_t Size = T->getSizeInBits())
3844         return Size;
3845
3846     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3847       // Look at the base type.
3848       RawType = DT->getRawBaseType();
3849       continue;
3850     }
3851
3852     if (auto *S = dyn_cast<MDString>(RawType)) {
3853       // Don't error on missing types (checked elsewhere).
3854       RawType = Map.lookup(S);
3855       continue;
3856     }
3857
3858     // Missing type or size.
3859     break;
3860   }
3861
3862   // Fail gracefully.
3863   return 0;
3864 }
3865
3866 template <class MapTy>
3867 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3868                                         const MapTy &TypeRefs) {
3869   DILocalVariable *V;
3870   DIExpression *E;
3871   if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3872     V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
3873     E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
3874   } else {
3875     auto *DDI = cast<DbgDeclareInst>(&I);
3876     V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
3877     E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
3878   }
3879
3880   // We don't know whether this intrinsic verified correctly.
3881   if (!V || !E || !E->isValid())
3882     return;
3883
3884   // Nothing to do if this isn't a bit piece expression.
3885   if (!E->isBitPiece())
3886     return;
3887
3888   // The frontend helps out GDB by emitting the members of local anonymous
3889   // unions as artificial local variables with shared storage. When SROA splits
3890   // the storage for artificial local variables that are smaller than the entire
3891   // union, the overhang piece will be outside of the allotted space for the
3892   // variable and this check fails.
3893   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
3894   if (V->isArtificial())
3895     return;
3896
3897   // If there's no size, the type is broken, but that should be checked
3898   // elsewhere.
3899   uint64_t VarSize = getVariableSize(*V, TypeRefs);
3900   if (!VarSize)
3901     return;
3902
3903   unsigned PieceSize = E->getBitPieceSize();
3904   unsigned PieceOffset = E->getBitPieceOffset();
3905   Assert(PieceSize + PieceOffset <= VarSize,
3906          "piece is larger than or outside of variable", &I, V, E);
3907   Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3908 }
3909
3910 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3911   // This is in its own function so we get an error for each bad type ref (not
3912   // just the first).
3913   Assert(false, "unresolved type ref", S, N);
3914 }
3915
3916 void Verifier::verifyTypeRefs() {
3917   auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3918   if (!CUs)
3919     return;
3920
3921   // Visit all the compile units again to map the type references.
3922   SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
3923   for (auto *CU : CUs->operands())
3924     if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
3925       for (DIType *Op : Ts)
3926         if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
3927           if (auto *S = T->getRawIdentifier()) {
3928             UnresolvedTypeRefs.erase(S);
3929             TypeRefs.insert(std::make_pair(S, T));
3930           }
3931
3932   // Verify debug info intrinsic bit piece expressions.  This needs a second
3933   // pass through the intructions, since we haven't built TypeRefs yet when
3934   // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
3935   // later/now would queue up some that could be later deleted.
3936   for (const Function &F : *M)
3937     for (const BasicBlock &BB : F)
3938       for (const Instruction &I : BB)
3939         if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
3940           verifyBitPieceExpression(*DII, TypeRefs);
3941
3942   // Return early if all typerefs were resolved.
3943   if (UnresolvedTypeRefs.empty())
3944     return;
3945
3946   // Sort the unresolved references by name so the output is deterministic.
3947   typedef std::pair<const MDString *, const MDNode *> TypeRef;
3948   SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3949                                       UnresolvedTypeRefs.end());
3950   std::sort(Unresolved.begin(), Unresolved.end(),
3951             [](const TypeRef &LHS, const TypeRef &RHS) {
3952     return LHS.first->getString() < RHS.first->getString();
3953   });
3954
3955   // Visit the unresolved refs (printing out the errors).
3956   for (const TypeRef &TR : Unresolved)
3957     visitUnresolvedTypeRef(TR.first, TR.second);
3958 }
3959
3960 //===----------------------------------------------------------------------===//
3961 //  Implement the public interfaces to this file...
3962 //===----------------------------------------------------------------------===//
3963
3964 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3965   Function &F = const_cast<Function &>(f);
3966   assert(!F.isDeclaration() && "Cannot verify external functions");
3967
3968   raw_null_ostream NullStr;
3969   Verifier V(OS ? *OS : NullStr);
3970
3971   // Note that this function's return value is inverted from what you would
3972   // expect of a function called "verify".
3973   return !V.verify(F);
3974 }
3975
3976 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3977   raw_null_ostream NullStr;
3978   Verifier V(OS ? *OS : NullStr);
3979
3980   bool Broken = false;
3981   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3982     if (!I->isDeclaration() && !I->isMaterializable())
3983       Broken |= !V.verify(*I);
3984
3985   // Note that this function's return value is inverted from what you would
3986   // expect of a function called "verify".
3987   return !V.verify(M) || Broken;
3988 }
3989
3990 namespace {
3991 struct VerifierLegacyPass : public FunctionPass {
3992   static char ID;
3993
3994   Verifier V;
3995   bool FatalErrors;
3996
3997   VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3998     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3999   }
4000   explicit VerifierLegacyPass(bool FatalErrors)
4001       : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
4002     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
4003   }
4004
4005   bool runOnFunction(Function &F) override {
4006     if (!V.verify(F) && FatalErrors)
4007       report_fatal_error("Broken function found, compilation aborted!");
4008
4009     return false;
4010   }
4011
4012   bool doFinalization(Module &M) override {
4013     if (!V.verify(M) && FatalErrors)
4014       report_fatal_error("Broken module found, compilation aborted!");
4015
4016     return false;
4017   }
4018
4019   void getAnalysisUsage(AnalysisUsage &AU) const override {
4020     AU.setPreservesAll();
4021   }
4022 };
4023 }
4024
4025 char VerifierLegacyPass::ID = 0;
4026 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
4027
4028 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
4029   return new VerifierLegacyPass(FatalErrors);
4030 }
4031
4032 PreservedAnalyses VerifierPass::run(Module &M) {
4033   if (verifyModule(M, &dbgs()) && FatalErrors)
4034     report_fatal_error("Broken module found, compilation aborted!");
4035
4036   return PreservedAnalyses::all();
4037 }
4038
4039 PreservedAnalyses VerifierPass::run(Function &F) {
4040   if (verifyFunction(F, &dbgs()) && FatalErrors)
4041     report_fatal_error("Broken function found, compilation aborted!");
4042
4043   return PreservedAnalyses::all();
4044 }