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