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