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