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