1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
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.
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
42 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
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"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
92 explicit VerifierSupport(raw_ostream &OS)
93 : OS(OS), M(nullptr), Broken(false), EverBroken(false) {}
96 void Write(const Value *V) {
99 if (isa<Instruction>(V)) {
102 V->printAsOperand(OS, true, M);
107 void Write(const Metadata *MD) {
114 void Write(const NamedMDNode *NMD) {
121 void Write(Type *T) {
127 void Write(const Comdat *C) {
133 template <typename T1, typename... Ts>
134 void WriteTs(const T1 &V1, const Ts &... Vs) {
139 template <typename... Ts> void WriteTs() {}
142 /// \brief A check failed, so printout out the condition and the message.
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;
151 /// \brief A check failed (with values to print).
153 /// This calls the Message-only version so that the above is easier to set a
155 template <typename T1, typename... Ts>
156 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
157 CheckFailed(Message);
162 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
163 friend class InstVisitor<Verifier>;
165 LLVMContext *Context;
168 /// \brief When verifying a basic block, keep track of all of the
169 /// instructions we have seen so far.
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;
175 /// \brief Keep track of the metadata nodes that have been checked already.
176 SmallPtrSet<const Metadata *, 32> MDNodes;
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;
183 /// \brief Whether we've seen a call to @llvm.frameescape in this function
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;
192 explicit Verifier(raw_ostream &OS)
193 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
194 SawFrameEscape(false) {}
196 bool verify(const Function &F) {
198 Context = &M->getContext();
200 // First ensure the function is well-enough formed to compute dominance
203 OS << "Function '" << F.getName()
204 << "' does not contain an entry block!\n";
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);
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));
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;
234 bool verify(const Module &M) {
236 Context = &M.getContext();
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);
243 // Check to make sure function prototypes are okay.
244 if (I->isDeclaration())
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();
252 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
254 visitGlobalVariable(*I);
256 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
258 visitGlobalAlias(*I);
260 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
261 E = M.named_metadata_end();
263 visitNamedMDNode(*I);
265 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
266 visitComdat(SMEC.getValue());
269 visitModuleIdents(M);
271 // Verify debug info last.
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);
299 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
300 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
301 #include "llvm/IR/Metadata.def"
302 void visitMDScope(const MDScope &N);
303 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
304 void visitMDVariable(const MDVariable &N);
305 void visitMDLexicalBlockBase(const MDLexicalBlockBase &N);
306 void visitMDTemplateParameter(const MDTemplateParameter &N);
308 // InstVisitor overrides...
309 using InstVisitor<Verifier>::visit;
310 void visit(Instruction &I);
312 void visitTruncInst(TruncInst &I);
313 void visitZExtInst(ZExtInst &I);
314 void visitSExtInst(SExtInst &I);
315 void visitFPTruncInst(FPTruncInst &I);
316 void visitFPExtInst(FPExtInst &I);
317 void visitFPToUIInst(FPToUIInst &I);
318 void visitFPToSIInst(FPToSIInst &I);
319 void visitUIToFPInst(UIToFPInst &I);
320 void visitSIToFPInst(SIToFPInst &I);
321 void visitIntToPtrInst(IntToPtrInst &I);
322 void visitPtrToIntInst(PtrToIntInst &I);
323 void visitBitCastInst(BitCastInst &I);
324 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
325 void visitPHINode(PHINode &PN);
326 void visitBinaryOperator(BinaryOperator &B);
327 void visitICmpInst(ICmpInst &IC);
328 void visitFCmpInst(FCmpInst &FC);
329 void visitExtractElementInst(ExtractElementInst &EI);
330 void visitInsertElementInst(InsertElementInst &EI);
331 void visitShuffleVectorInst(ShuffleVectorInst &EI);
332 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
333 void visitCallInst(CallInst &CI);
334 void visitInvokeInst(InvokeInst &II);
335 void visitGetElementPtrInst(GetElementPtrInst &GEP);
336 void visitLoadInst(LoadInst &LI);
337 void visitStoreInst(StoreInst &SI);
338 void verifyDominatesUse(Instruction &I, unsigned i);
339 void visitInstruction(Instruction &I);
340 void visitTerminatorInst(TerminatorInst &I);
341 void visitBranchInst(BranchInst &BI);
342 void visitReturnInst(ReturnInst &RI);
343 void visitSwitchInst(SwitchInst &SI);
344 void visitIndirectBrInst(IndirectBrInst &BI);
345 void visitSelectInst(SelectInst &SI);
346 void visitUserOp1(Instruction &I);
347 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
348 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
349 template <class DbgIntrinsicTy>
350 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
351 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
352 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
353 void visitFenceInst(FenceInst &FI);
354 void visitAllocaInst(AllocaInst &AI);
355 void visitExtractValueInst(ExtractValueInst &EVI);
356 void visitInsertValueInst(InsertValueInst &IVI);
357 void visitLandingPadInst(LandingPadInst &LPI);
359 void VerifyCallSite(CallSite CS);
360 void verifyMustTailCall(CallInst &CI);
361 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
362 unsigned ArgNo, std::string &Suffix);
363 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
364 SmallVectorImpl<Type *> &ArgTys);
365 bool VerifyIntrinsicIsVarArg(bool isVarArg,
366 ArrayRef<Intrinsic::IITDescriptor> &Infos);
367 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
368 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
370 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
371 bool isReturnValue, const Value *V);
372 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
375 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
376 void VerifyStatepoint(ImmutableCallSite CS);
377 void verifyFrameRecoverIndices();
379 // Module-level debug info verification...
380 void verifyDebugInfo();
381 void processInstructions(DebugInfoFinder &Finder);
382 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
384 } // End anonymous namespace
386 // Assert - We know that cond should be true, if not print an error message.
387 #define Assert(C, ...) \
388 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
390 void Verifier::visit(Instruction &I) {
391 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
392 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
393 InstVisitor<Verifier>::visit(I);
397 void Verifier::visitGlobalValue(const GlobalValue &GV) {
398 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
399 GV.hasExternalWeakLinkage(),
400 "Global is external, but doesn't have external or weak linkage!", &GV);
402 Assert(GV.getAlignment() <= Value::MaximumAlignment,
403 "huge alignment values are unsupported", &GV);
404 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
405 "Only global variables can have appending linkage!", &GV);
407 if (GV.hasAppendingLinkage()) {
408 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
409 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
410 "Only global arrays can have appending linkage!", GVar);
414 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
415 if (GV.hasInitializer()) {
416 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
417 "Global variable initializer type does not match global "
421 // If the global has common linkage, it must have a zero initializer and
422 // cannot be constant.
423 if (GV.hasCommonLinkage()) {
424 Assert(GV.getInitializer()->isNullValue(),
425 "'common' global must have a zero initializer!", &GV);
426 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
428 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
431 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
432 "invalid linkage type for global declaration", &GV);
435 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
436 GV.getName() == "llvm.global_dtors")) {
437 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
438 "invalid linkage for intrinsic global variable", &GV);
439 // Don't worry about emitting an error for it not being an array,
440 // visitGlobalValue will complain on appending non-array.
441 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
442 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
443 PointerType *FuncPtrTy =
444 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
445 // FIXME: Reject the 2-field form in LLVM 4.0.
447 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
448 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
449 STy->getTypeAtIndex(1) == FuncPtrTy,
450 "wrong type for intrinsic global variable", &GV);
451 if (STy->getNumElements() == 3) {
452 Type *ETy = STy->getTypeAtIndex(2);
453 Assert(ETy->isPointerTy() &&
454 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
455 "wrong type for intrinsic global variable", &GV);
460 if (GV.hasName() && (GV.getName() == "llvm.used" ||
461 GV.getName() == "llvm.compiler.used")) {
462 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
463 "invalid linkage for intrinsic global variable", &GV);
464 Type *GVType = GV.getType()->getElementType();
465 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
466 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
467 Assert(PTy, "wrong type for intrinsic global variable", &GV);
468 if (GV.hasInitializer()) {
469 const Constant *Init = GV.getInitializer();
470 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
471 Assert(InitArray, "wrong initalizer for intrinsic global variable",
473 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
474 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
475 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
477 "invalid llvm.used member", V);
478 Assert(V->hasName(), "members of llvm.used must be named", V);
484 Assert(!GV.hasDLLImportStorageClass() ||
485 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
486 GV.hasAvailableExternallyLinkage(),
487 "Global is marked as dllimport, but not external", &GV);
489 if (!GV.hasInitializer()) {
490 visitGlobalValue(GV);
494 // Walk any aggregate initializers looking for bitcasts between address spaces
495 SmallPtrSet<const Value *, 4> Visited;
496 SmallVector<const Value *, 4> WorkStack;
497 WorkStack.push_back(cast<Value>(GV.getInitializer()));
499 while (!WorkStack.empty()) {
500 const Value *V = WorkStack.pop_back_val();
501 if (!Visited.insert(V).second)
504 if (const User *U = dyn_cast<User>(V)) {
505 WorkStack.append(U->op_begin(), U->op_end());
508 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
509 VerifyConstantExprBitcastType(CE);
515 visitGlobalValue(GV);
518 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
519 SmallPtrSet<const GlobalAlias*, 4> Visited;
521 visitAliaseeSubExpr(Visited, GA, C);
524 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
525 const GlobalAlias &GA, const Constant &C) {
526 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
527 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
529 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
530 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
532 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
535 // Only continue verifying subexpressions of GlobalAliases.
536 // Do not recurse into global initializers.
541 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
542 VerifyConstantExprBitcastType(CE);
544 for (const Use &U : C.operands()) {
546 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
547 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
548 else if (const auto *C2 = dyn_cast<Constant>(V))
549 visitAliaseeSubExpr(Visited, GA, *C2);
553 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
554 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
555 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
556 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
557 "weak_odr, or external linkage!",
559 const Constant *Aliasee = GA.getAliasee();
560 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
561 Assert(GA.getType() == Aliasee->getType(),
562 "Alias and aliasee types should match!", &GA);
564 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
565 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
567 visitAliaseeSubExpr(GA, *Aliasee);
569 visitGlobalValue(GA);
572 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
573 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
574 MDNode *MD = NMD.getOperand(i);
578 if (NMD.getName() == "llvm.dbg.cu") {
579 Assert(isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
586 void Verifier::visitMDNode(const MDNode &MD) {
587 // Only visit each node once. Metadata can be mutually recursive, so this
588 // avoids infinite recursion here, as well as being an optimization.
589 if (!MDNodes.insert(&MD).second)
592 switch (MD.getMetadataID()) {
594 llvm_unreachable("Invalid MDNode subclass");
595 case Metadata::MDTupleKind:
597 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
598 case Metadata::CLASS##Kind: \
599 visit##CLASS(cast<CLASS>(MD)); \
601 #include "llvm/IR/Metadata.def"
604 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
605 Metadata *Op = MD.getOperand(i);
608 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
610 if (auto *N = dyn_cast<MDNode>(Op)) {
614 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
615 visitValueAsMetadata(*V, nullptr);
620 // Check these last, so we diagnose problems in operands first.
621 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
622 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
625 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
626 Assert(MD.getValue(), "Expected valid value", &MD);
627 Assert(!MD.getValue()->getType()->isMetadataTy(),
628 "Unexpected metadata round-trip through values", &MD, MD.getValue());
630 auto *L = dyn_cast<LocalAsMetadata>(&MD);
634 Assert(F, "function-local metadata used outside a function", L);
636 // If this was an instruction, bb, or argument, verify that it is in the
637 // function that we expect.
638 Function *ActualF = nullptr;
639 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
640 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
641 ActualF = I->getParent()->getParent();
642 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
643 ActualF = BB->getParent();
644 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
645 ActualF = A->getParent();
646 assert(ActualF && "Unimplemented function local metadata case!");
648 Assert(ActualF == F, "function-local metadata used in wrong function", L);
651 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
652 Metadata *MD = MDV.getMetadata();
653 if (auto *N = dyn_cast<MDNode>(MD)) {
658 // Only visit each node once. Metadata can be mutually recursive, so this
659 // avoids infinite recursion here, as well as being an optimization.
660 if (!MDNodes.insert(MD).second)
663 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
664 visitValueAsMetadata(*V, F);
667 /// \brief Check if a value can be a reference to a type.
668 static bool isTypeRef(const Metadata *MD) {
671 if (auto *S = dyn_cast<MDString>(MD))
672 return !S->getString().empty();
673 return isa<MDType>(MD);
676 /// \brief Check if a value can be a ScopeRef.
677 static bool isScopeRef(const Metadata *MD) {
680 if (auto *S = dyn_cast<MDString>(MD))
681 return !S->getString().empty();
682 return isa<MDScope>(MD);
685 /// \brief Check if a value can be a debug info ref.
686 static bool isDIRef(const Metadata *MD) {
689 if (auto *S = dyn_cast<MDString>(MD))
690 return !S->getString().empty();
691 return isa<DebugNode>(MD);
695 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
696 for (Metadata *MD : N.operands()) {
709 bool isValidMetadataArray(const MDTuple &N) {
710 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
714 bool isValidMetadataNullArray(const MDTuple &N) {
715 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
718 void Verifier::visitMDLocation(const MDLocation &N) {
719 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
720 "location requires a valid scope", &N, N.getRawScope());
721 if (auto *IA = N.getRawInlinedAt())
722 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
725 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
726 Assert(N.getTag(), "invalid tag", &N);
729 void Verifier::visitMDScope(const MDScope &N) {
730 if (auto *F = N.getRawFile())
731 Assert(isa<MDFile>(F), "invalid file", &N, F);
734 void Verifier::visitMDSubrange(const MDSubrange &N) {
735 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
736 Assert(N.getCount() >= -1, "invalid subrange count", &N);
739 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
740 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
743 void Verifier::visitMDBasicType(const MDBasicType &N) {
744 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
745 N.getTag() == dwarf::DW_TAG_unspecified_type,
749 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
750 // Common scope checks.
753 Assert(isScopeRef(N.getScope()), "invalid scope", &N, N.getScope());
754 Assert(isTypeRef(N.getBaseType()), "invalid base type", &N, N.getBaseType());
757 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
758 // Common derived type checks.
759 visitMDDerivedTypeBase(N);
761 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
762 N.getTag() == dwarf::DW_TAG_pointer_type ||
763 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
764 N.getTag() == dwarf::DW_TAG_reference_type ||
765 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
766 N.getTag() == dwarf::DW_TAG_const_type ||
767 N.getTag() == dwarf::DW_TAG_volatile_type ||
768 N.getTag() == dwarf::DW_TAG_restrict_type ||
769 N.getTag() == dwarf::DW_TAG_member ||
770 N.getTag() == dwarf::DW_TAG_inheritance ||
771 N.getTag() == dwarf::DW_TAG_friend,
775 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
776 // Common derived type checks.
777 visitMDDerivedTypeBase(N);
779 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
780 N.getTag() == dwarf::DW_TAG_structure_type ||
781 N.getTag() == dwarf::DW_TAG_union_type ||
782 N.getTag() == dwarf::DW_TAG_enumeration_type ||
783 N.getTag() == dwarf::DW_TAG_subroutine_type ||
784 N.getTag() == dwarf::DW_TAG_class_type,
787 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
788 "invalid composite elements", &N, N.getRawElements());
789 Assert(isTypeRef(N.getRawVTableHolder()), "invalid vtable holder", &N,
790 N.getRawVTableHolder());
791 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
792 "invalid composite elements", &N, N.getRawElements());
795 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
796 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
797 if (auto *Types = N.getRawTypeArray()) {
798 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
799 for (Metadata *Ty : N.getTypeArray()->operands()) {
800 Assert(isTypeRef(Ty), "invalid subroutine type ref", &N, Types, Ty);
805 void Verifier::visitMDFile(const MDFile &N) {
806 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
809 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
810 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
812 if (auto *Array = N.getRawEnumTypes()) {
813 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
814 for (Metadata *Op : N.getEnumTypes()->operands()) {
815 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
816 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
817 "invalid enum type", &N, N.getEnumTypes(), Op);
820 if (auto *Array = N.getRawRetainedTypes()) {
821 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
822 for (Metadata *Op : N.getRetainedTypes()->operands()) {
823 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
826 if (auto *Array = N.getRawSubprograms()) {
827 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
828 for (Metadata *Op : N.getSubprograms()->operands()) {
829 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
832 if (auto *Array = N.getRawGlobalVariables()) {
833 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
834 for (Metadata *Op : N.getGlobalVariables()->operands()) {
835 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
839 if (auto *Array = N.getRawImportedEntities()) {
840 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
841 for (Metadata *Op : N.getImportedEntities()->operands()) {
842 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
848 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
849 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
850 Assert(isScopeRef(N.getRawScope()), "invalid scope", &N, N.getRawScope());
851 if (auto *T = N.getRawType())
852 Assert(isa<MDSubroutineType>(T), "invalid subroutine type", &N, T);
853 Assert(isTypeRef(N.getRawContainingType()), "invalid containing type", &N,
854 N.getRawContainingType());
855 if (auto *RawF = N.getRawFunction()) {
856 auto *FMD = dyn_cast<ConstantAsMetadata>(RawF);
857 auto *F = FMD ? FMD->getValue() : nullptr;
858 auto *FT = F ? dyn_cast<PointerType>(F->getType()) : nullptr;
859 Assert(F && FT && isa<FunctionType>(FT->getElementType()),
860 "invalid function", &N, F, FT);
862 if (N.getRawTemplateParams()) {
863 auto *Params = dyn_cast<MDTuple>(N.getRawTemplateParams());
864 Assert(Params, "invalid template params", &N, Params);
865 for (Metadata *Op : Params->operands()) {
866 Assert(Op && isa<MDTemplateParameter>(Op), "invalid template parameter",
870 if (auto *S = N.getRawDeclaration()) {
871 Assert(isa<MDSubprogram>(S) && !cast<MDSubprogram>(S)->isDefinition(),
872 "invalid subprogram declaration", &N, S);
874 if (N.getRawVariables()) {
875 auto *Vars = dyn_cast<MDTuple>(N.getRawVariables());
876 Assert(Vars, "invalid variable list", &N, Vars);
877 for (Metadata *Op : Vars->operands()) {
878 Assert(Op && isa<MDLocalVariable>(Op), "invalid local variable", &N, Vars,
884 void Verifier::visitMDLexicalBlockBase(const MDLexicalBlockBase &N) {
885 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
886 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
887 "invalid local scope", &N, N.getRawScope());
890 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
891 visitMDLexicalBlockBase(N);
893 Assert(N.getLine() || !N.getColumn(),
894 "cannot have column info without line info", &N);
897 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
898 visitMDLexicalBlockBase(N);
901 void Verifier::visitMDNamespace(const MDNamespace &N) {
902 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
903 if (auto *S = N.getRawScope())
904 Assert(isa<MDScope>(S), "invalid scope ref", &N, S);
907 void Verifier::visitMDTemplateParameter(const MDTemplateParameter &N) {
908 Assert(isTypeRef(N.getType()), "invalid type ref", &N, N.getType());
911 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
912 visitMDTemplateParameter(N);
914 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
918 void Verifier::visitMDTemplateValueParameter(
919 const MDTemplateValueParameter &N) {
920 visitMDTemplateParameter(N);
922 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
923 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
924 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
928 void Verifier::visitMDVariable(const MDVariable &N) {
929 if (auto *S = N.getRawScope())
930 Assert(isa<MDScope>(S), "invalid scope", &N, S);
931 Assert(isTypeRef(N.getRawType()), "invalid type ref", &N, N.getRawType());
932 if (auto *F = N.getRawFile())
933 Assert(isa<MDFile>(F), "invalid file", &N, F);
936 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
937 // Checks common to all variables.
940 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
941 if (auto *V = N.getRawVariable()) {
942 Assert(isa<ConstantAsMetadata>(V) &&
943 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
944 "invalid global varaible ref", &N, V);
946 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
947 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
952 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
953 // Checks common to all variables.
956 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
957 N.getTag() == dwarf::DW_TAG_arg_variable,
959 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
960 "local variable requires a valid scope", &N, N.getRawScope());
961 if (auto *IA = N.getRawInlinedAt())
962 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
966 void Verifier::visitMDExpression(const MDExpression &N) {
967 Assert(N.isValid(), "invalid expression", &N);
970 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
971 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
972 if (auto *T = N.getRawType())
973 Assert(isa<MDType>(T), "invalid type ref", &N, T);
974 if (auto *F = N.getRawFile())
975 Assert(isa<MDFile>(F), "invalid file", &N, F);
978 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
979 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
980 N.getTag() == dwarf::DW_TAG_imported_declaration,
982 if (auto *S = N.getRawScope())
983 Assert(isa<MDScope>(S), "invalid scope for imported entity", &N, S);
984 Assert(isDIRef(N.getEntity()), "invalid imported entity", &N, N.getEntity());
987 void Verifier::visitComdat(const Comdat &C) {
988 // The Module is invalid if the GlobalValue has private linkage. Entities
989 // with private linkage don't have entries in the symbol table.
990 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
991 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
995 void Verifier::visitModuleIdents(const Module &M) {
996 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1000 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1001 // Scan each llvm.ident entry and make sure that this requirement is met.
1002 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1003 const MDNode *N = Idents->getOperand(i);
1004 Assert(N->getNumOperands() == 1,
1005 "incorrect number of operands in llvm.ident metadata", N);
1006 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1007 ("invalid value for llvm.ident metadata entry operand"
1008 "(the operand should be a string)"),
1013 void Verifier::visitModuleFlags(const Module &M) {
1014 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1017 // Scan each flag, and track the flags and requirements.
1018 DenseMap<const MDString*, const MDNode*> SeenIDs;
1019 SmallVector<const MDNode*, 16> Requirements;
1020 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1021 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1024 // Validate that the requirements in the module are valid.
1025 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1026 const MDNode *Requirement = Requirements[I];
1027 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1028 const Metadata *ReqValue = Requirement->getOperand(1);
1030 const MDNode *Op = SeenIDs.lookup(Flag);
1032 CheckFailed("invalid requirement on flag, flag is not present in module",
1037 if (Op->getOperand(2) != ReqValue) {
1038 CheckFailed(("invalid requirement on flag, "
1039 "flag does not have the required value"),
1047 Verifier::visitModuleFlag(const MDNode *Op,
1048 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1049 SmallVectorImpl<const MDNode *> &Requirements) {
1050 // Each module flag should have three arguments, the merge behavior (a
1051 // constant int), the flag ID (an MDString), and the value.
1052 Assert(Op->getNumOperands() == 3,
1053 "incorrect number of operands in module flag", Op);
1054 Module::ModFlagBehavior MFB;
1055 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1057 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1058 "invalid behavior operand in module flag (expected constant integer)",
1061 "invalid behavior operand in module flag (unexpected constant)",
1064 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1065 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1068 // Sanity check the values for behaviors with additional requirements.
1071 case Module::Warning:
1072 case Module::Override:
1073 // These behavior types accept any value.
1076 case Module::Require: {
1077 // The value should itself be an MDNode with two operands, a flag ID (an
1078 // MDString), and a value.
1079 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1080 Assert(Value && Value->getNumOperands() == 2,
1081 "invalid value for 'require' module flag (expected metadata pair)",
1083 Assert(isa<MDString>(Value->getOperand(0)),
1084 ("invalid value for 'require' module flag "
1085 "(first value operand should be a string)"),
1086 Value->getOperand(0));
1088 // Append it to the list of requirements, to check once all module flags are
1090 Requirements.push_back(Value);
1094 case Module::Append:
1095 case Module::AppendUnique: {
1096 // These behavior types require the operand be an MDNode.
1097 Assert(isa<MDNode>(Op->getOperand(2)),
1098 "invalid value for 'append'-type module flag "
1099 "(expected a metadata node)",
1105 // Unless this is a "requires" flag, check the ID is unique.
1106 if (MFB != Module::Require) {
1107 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1109 "module flag identifiers must be unique (or of 'require' type)", ID);
1113 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1114 bool isFunction, const Value *V) {
1115 unsigned Slot = ~0U;
1116 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1117 if (Attrs.getSlotIndex(I) == Idx) {
1122 assert(Slot != ~0U && "Attribute set inconsistency!");
1124 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1126 if (I->isStringAttribute())
1129 if (I->getKindAsEnum() == Attribute::NoReturn ||
1130 I->getKindAsEnum() == Attribute::NoUnwind ||
1131 I->getKindAsEnum() == Attribute::NoInline ||
1132 I->getKindAsEnum() == Attribute::AlwaysInline ||
1133 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1134 I->getKindAsEnum() == Attribute::StackProtect ||
1135 I->getKindAsEnum() == Attribute::StackProtectReq ||
1136 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1137 I->getKindAsEnum() == Attribute::NoRedZone ||
1138 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1139 I->getKindAsEnum() == Attribute::Naked ||
1140 I->getKindAsEnum() == Attribute::InlineHint ||
1141 I->getKindAsEnum() == Attribute::StackAlignment ||
1142 I->getKindAsEnum() == Attribute::UWTable ||
1143 I->getKindAsEnum() == Attribute::NonLazyBind ||
1144 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1145 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1146 I->getKindAsEnum() == Attribute::SanitizeThread ||
1147 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1148 I->getKindAsEnum() == Attribute::MinSize ||
1149 I->getKindAsEnum() == Attribute::NoDuplicate ||
1150 I->getKindAsEnum() == Attribute::Builtin ||
1151 I->getKindAsEnum() == Attribute::NoBuiltin ||
1152 I->getKindAsEnum() == Attribute::Cold ||
1153 I->getKindAsEnum() == Attribute::OptimizeNone ||
1154 I->getKindAsEnum() == Attribute::JumpTable) {
1156 CheckFailed("Attribute '" + I->getAsString() +
1157 "' only applies to functions!", V);
1160 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1161 I->getKindAsEnum() == Attribute::ReadNone) {
1163 CheckFailed("Attribute '" + I->getAsString() +
1164 "' does not apply to function returns");
1167 } else if (isFunction) {
1168 CheckFailed("Attribute '" + I->getAsString() +
1169 "' does not apply to functions!", V);
1175 // VerifyParameterAttrs - Check the given attributes for an argument or return
1176 // value of the specified type. The value V is printed in error messages.
1177 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1178 bool isReturnValue, const Value *V) {
1179 if (!Attrs.hasAttributes(Idx))
1182 VerifyAttributeTypes(Attrs, Idx, false, V);
1185 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1186 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1187 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1188 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1189 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1190 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1191 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1192 "'returned' do not apply to return values!",
1195 // Check for mutually incompatible attributes. Only inreg is compatible with
1197 unsigned AttrCount = 0;
1198 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1199 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1200 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1201 Attrs.hasAttribute(Idx, Attribute::InReg);
1202 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1203 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1204 "and 'sret' are incompatible!",
1207 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1208 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1210 "'inalloca and readonly' are incompatible!",
1213 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1214 Attrs.hasAttribute(Idx, Attribute::Returned)),
1216 "'sret and returned' are incompatible!",
1219 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1220 Attrs.hasAttribute(Idx, Attribute::SExt)),
1222 "'zeroext and signext' are incompatible!",
1225 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1226 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1228 "'readnone and readonly' are incompatible!",
1231 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1232 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1234 "'noinline and alwaysinline' are incompatible!",
1237 Assert(!AttrBuilder(Attrs, Idx)
1238 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1239 "Wrong types for attribute: " +
1240 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1243 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1244 SmallPtrSet<const Type*, 4> Visited;
1245 if (!PTy->getElementType()->isSized(&Visited)) {
1246 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1247 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1248 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1252 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1253 "Attribute 'byval' only applies to parameters with pointer type!",
1258 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1259 // The value V is printed in error messages.
1260 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1262 if (Attrs.isEmpty())
1265 bool SawNest = false;
1266 bool SawReturned = false;
1267 bool SawSRet = false;
1269 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1270 unsigned Idx = Attrs.getSlotIndex(i);
1274 Ty = FT->getReturnType();
1275 else if (Idx-1 < FT->getNumParams())
1276 Ty = FT->getParamType(Idx-1);
1278 break; // VarArgs attributes, verified elsewhere.
1280 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1285 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1286 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1290 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1291 Assert(!SawReturned, "More than one parameter has attribute returned!",
1293 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1295 "argument and return types for 'returned' attribute",
1300 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1301 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1302 Assert(Idx == 1 || Idx == 2,
1303 "Attribute 'sret' is not on first or second parameter!", V);
1307 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1308 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1313 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1316 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1319 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1320 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1321 "Attributes 'readnone and readonly' are incompatible!", V);
1324 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1325 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1326 Attribute::AlwaysInline)),
1327 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1329 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1330 Attribute::OptimizeNone)) {
1331 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1332 "Attribute 'optnone' requires 'noinline'!", V);
1334 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1335 Attribute::OptimizeForSize),
1336 "Attributes 'optsize and optnone' are incompatible!", V);
1338 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1339 "Attributes 'minsize and optnone' are incompatible!", V);
1342 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1343 Attribute::JumpTable)) {
1344 const GlobalValue *GV = cast<GlobalValue>(V);
1345 Assert(GV->hasUnnamedAddr(),
1346 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1350 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1351 if (CE->getOpcode() != Instruction::BitCast)
1354 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1356 "Invalid bitcast", CE);
1359 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1360 if (Attrs.getNumSlots() == 0)
1363 unsigned LastSlot = Attrs.getNumSlots() - 1;
1364 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1365 if (LastIndex <= Params
1366 || (LastIndex == AttributeSet::FunctionIndex
1367 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1373 /// \brief Verify that statepoint intrinsic is well formed.
1374 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1375 assert(CS.getCalledFunction() &&
1376 CS.getCalledFunction()->getIntrinsicID() ==
1377 Intrinsic::experimental_gc_statepoint);
1379 const Instruction &CI = *CS.getInstruction();
1381 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1382 "gc.statepoint must read and write memory to preserve "
1383 "reordering restrictions required by safepoint semantics",
1386 const Value *Target = CS.getArgument(0);
1387 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1388 Assert(PT && PT->getElementType()->isFunctionTy(),
1389 "gc.statepoint callee must be of function pointer type", &CI, Target);
1390 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1392 const Value *NumCallArgsV = CS.getArgument(1);
1393 Assert(isa<ConstantInt>(NumCallArgsV),
1394 "gc.statepoint number of arguments to underlying call "
1395 "must be constant integer",
1397 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1398 Assert(NumCallArgs >= 0,
1399 "gc.statepoint number of arguments to underlying call "
1402 const int NumParams = (int)TargetFuncType->getNumParams();
1403 if (TargetFuncType->isVarArg()) {
1404 Assert(NumCallArgs >= NumParams,
1405 "gc.statepoint mismatch in number of vararg call args", &CI);
1407 // TODO: Remove this limitation
1408 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1409 "gc.statepoint doesn't support wrapping non-void "
1410 "vararg functions yet",
1413 Assert(NumCallArgs == NumParams,
1414 "gc.statepoint mismatch in number of call args", &CI);
1416 const Value *Unused = CS.getArgument(2);
1417 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1418 "gc.statepoint parameter #3 must be zero", &CI);
1420 // Verify that the types of the call parameter arguments match
1421 // the type of the wrapped callee.
1422 for (int i = 0; i < NumParams; i++) {
1423 Type *ParamType = TargetFuncType->getParamType(i);
1424 Type *ArgType = CS.getArgument(3+i)->getType();
1425 Assert(ArgType == ParamType,
1426 "gc.statepoint call argument does not match wrapped "
1430 const int EndCallArgsInx = 2+NumCallArgs;
1431 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1432 Assert(isa<ConstantInt>(NumDeoptArgsV),
1433 "gc.statepoint number of deoptimization arguments "
1434 "must be constant integer",
1436 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1437 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1441 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1442 "gc.statepoint too few arguments according to length fields", &CI);
1444 // Check that the only uses of this gc.statepoint are gc.result or
1445 // gc.relocate calls which are tied to this statepoint and thus part
1446 // of the same statepoint sequence
1447 for (const User *U : CI.users()) {
1448 const CallInst *Call = dyn_cast<const CallInst>(U);
1449 Assert(Call, "illegal use of statepoint token", &CI, U);
1450 if (!Call) continue;
1451 Assert(isGCRelocate(Call) || isGCResult(Call),
1452 "gc.result or gc.relocate are the only value uses"
1453 "of a gc.statepoint",
1455 if (isGCResult(Call)) {
1456 Assert(Call->getArgOperand(0) == &CI,
1457 "gc.result connected to wrong gc.statepoint", &CI, Call);
1458 } else if (isGCRelocate(Call)) {
1459 Assert(Call->getArgOperand(0) == &CI,
1460 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1464 // Note: It is legal for a single derived pointer to be listed multiple
1465 // times. It's non-optimal, but it is legal. It can also happen after
1466 // insertion if we strip a bitcast away.
1467 // Note: It is really tempting to check that each base is relocated and
1468 // that a derived pointer is never reused as a base pointer. This turns
1469 // out to be problematic since optimizations run after safepoint insertion
1470 // can recognize equality properties that the insertion logic doesn't know
1471 // about. See example statepoint.ll in the verifier subdirectory
1474 void Verifier::verifyFrameRecoverIndices() {
1475 for (auto &Counts : FrameEscapeInfo) {
1476 Function *F = Counts.first;
1477 unsigned EscapedObjectCount = Counts.second.first;
1478 unsigned MaxRecoveredIndex = Counts.second.second;
1479 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1480 "all indices passed to llvm.framerecover must be less than the "
1481 "number of arguments passed ot llvm.frameescape in the parent "
1487 // visitFunction - Verify that a function is ok.
1489 void Verifier::visitFunction(const Function &F) {
1490 // Check function arguments.
1491 FunctionType *FT = F.getFunctionType();
1492 unsigned NumArgs = F.arg_size();
1494 Assert(Context == &F.getContext(),
1495 "Function context does not match Module context!", &F);
1497 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1498 Assert(FT->getNumParams() == NumArgs,
1499 "# formal arguments must match # of arguments for function type!", &F,
1501 Assert(F.getReturnType()->isFirstClassType() ||
1502 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1503 "Functions cannot return aggregate values!", &F);
1505 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1506 "Invalid struct return type!", &F);
1508 AttributeSet Attrs = F.getAttributes();
1510 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1511 "Attribute after last parameter!", &F);
1513 // Check function attributes.
1514 VerifyFunctionAttrs(FT, Attrs, &F);
1516 // On function declarations/definitions, we do not support the builtin
1517 // attribute. We do not check this in VerifyFunctionAttrs since that is
1518 // checking for Attributes that can/can not ever be on functions.
1519 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1520 "Attribute 'builtin' can only be applied to a callsite.", &F);
1522 // Check that this function meets the restrictions on this calling convention.
1523 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1524 // restrictions can be lifted.
1525 switch (F.getCallingConv()) {
1527 case CallingConv::C:
1529 case CallingConv::Fast:
1530 case CallingConv::Cold:
1531 case CallingConv::Intel_OCL_BI:
1532 case CallingConv::PTX_Kernel:
1533 case CallingConv::PTX_Device:
1534 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1535 "perfect forwarding!",
1540 bool isLLVMdotName = F.getName().size() >= 5 &&
1541 F.getName().substr(0, 5) == "llvm.";
1543 // Check that the argument values match the function type for this function...
1545 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1547 Assert(I->getType() == FT->getParamType(i),
1548 "Argument value does not match function argument type!", I,
1549 FT->getParamType(i));
1550 Assert(I->getType()->isFirstClassType(),
1551 "Function arguments must have first-class types!", I);
1553 Assert(!I->getType()->isMetadataTy(),
1554 "Function takes metadata but isn't an intrinsic", I, &F);
1557 if (F.isMaterializable()) {
1558 // Function has a body somewhere we can't see.
1559 } else if (F.isDeclaration()) {
1560 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1561 "invalid linkage type for function declaration", &F);
1563 // Verify that this function (which has a body) is not named "llvm.*". It
1564 // is not legal to define intrinsics.
1565 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1567 // Check the entry node
1568 const BasicBlock *Entry = &F.getEntryBlock();
1569 Assert(pred_empty(Entry),
1570 "Entry block to function must not have predecessors!", Entry);
1572 // The address of the entry block cannot be taken, unless it is dead.
1573 if (Entry->hasAddressTaken()) {
1574 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1575 "blockaddress may not be used with the entry block!", Entry);
1579 // If this function is actually an intrinsic, verify that it is only used in
1580 // direct call/invokes, never having its "address taken".
1581 if (F.getIntrinsicID()) {
1583 if (F.hasAddressTaken(&U))
1584 Assert(0, "Invalid user of intrinsic instruction!", U);
1587 Assert(!F.hasDLLImportStorageClass() ||
1588 (F.isDeclaration() && F.hasExternalLinkage()) ||
1589 F.hasAvailableExternallyLinkage(),
1590 "Function is marked as dllimport, but not external.", &F);
1593 // verifyBasicBlock - Verify that a basic block is well formed...
1595 void Verifier::visitBasicBlock(BasicBlock &BB) {
1596 InstsInThisBlock.clear();
1598 // Ensure that basic blocks have terminators!
1599 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1601 // Check constraints that this basic block imposes on all of the PHI nodes in
1603 if (isa<PHINode>(BB.front())) {
1604 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1605 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1606 std::sort(Preds.begin(), Preds.end());
1608 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1609 // Ensure that PHI nodes have at least one entry!
1610 Assert(PN->getNumIncomingValues() != 0,
1611 "PHI nodes must have at least one entry. If the block is dead, "
1612 "the PHI should be removed!",
1614 Assert(PN->getNumIncomingValues() == Preds.size(),
1615 "PHINode should have one entry for each predecessor of its "
1616 "parent basic block!",
1619 // Get and sort all incoming values in the PHI node...
1621 Values.reserve(PN->getNumIncomingValues());
1622 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1623 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1624 PN->getIncomingValue(i)));
1625 std::sort(Values.begin(), Values.end());
1627 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1628 // Check to make sure that if there is more than one entry for a
1629 // particular basic block in this PHI node, that the incoming values are
1632 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1633 Values[i].second == Values[i - 1].second,
1634 "PHI node has multiple entries for the same basic block with "
1635 "different incoming values!",
1636 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1638 // Check to make sure that the predecessors and PHI node entries are
1640 Assert(Values[i].first == Preds[i],
1641 "PHI node entries do not match predecessors!", PN,
1642 Values[i].first, Preds[i]);
1647 // Check that all instructions have their parent pointers set up correctly.
1650 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1654 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1655 // Ensure that terminators only exist at the end of the basic block.
1656 Assert(&I == I.getParent()->getTerminator(),
1657 "Terminator found in the middle of a basic block!", I.getParent());
1658 visitInstruction(I);
1661 void Verifier::visitBranchInst(BranchInst &BI) {
1662 if (BI.isConditional()) {
1663 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1664 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1666 visitTerminatorInst(BI);
1669 void Verifier::visitReturnInst(ReturnInst &RI) {
1670 Function *F = RI.getParent()->getParent();
1671 unsigned N = RI.getNumOperands();
1672 if (F->getReturnType()->isVoidTy())
1674 "Found return instr that returns non-void in Function of void "
1676 &RI, F->getReturnType());
1678 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1679 "Function return type does not match operand "
1680 "type of return inst!",
1681 &RI, F->getReturnType());
1683 // Check to make sure that the return value has necessary properties for
1685 visitTerminatorInst(RI);
1688 void Verifier::visitSwitchInst(SwitchInst &SI) {
1689 // Check to make sure that all of the constants in the switch instruction
1690 // have the same type as the switched-on value.
1691 Type *SwitchTy = SI.getCondition()->getType();
1692 SmallPtrSet<ConstantInt*, 32> Constants;
1693 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1694 Assert(i.getCaseValue()->getType() == SwitchTy,
1695 "Switch constants must all be same type as switch value!", &SI);
1696 Assert(Constants.insert(i.getCaseValue()).second,
1697 "Duplicate integer as switch case", &SI, i.getCaseValue());
1700 visitTerminatorInst(SI);
1703 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1704 Assert(BI.getAddress()->getType()->isPointerTy(),
1705 "Indirectbr operand must have pointer type!", &BI);
1706 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1707 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1708 "Indirectbr destinations must all have pointer type!", &BI);
1710 visitTerminatorInst(BI);
1713 void Verifier::visitSelectInst(SelectInst &SI) {
1714 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1716 "Invalid operands for select instruction!", &SI);
1718 Assert(SI.getTrueValue()->getType() == SI.getType(),
1719 "Select values must have same type as select instruction!", &SI);
1720 visitInstruction(SI);
1723 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1724 /// a pass, if any exist, it's an error.
1726 void Verifier::visitUserOp1(Instruction &I) {
1727 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1730 void Verifier::visitTruncInst(TruncInst &I) {
1731 // Get the source and destination types
1732 Type *SrcTy = I.getOperand(0)->getType();
1733 Type *DestTy = I.getType();
1735 // Get the size of the types in bits, we'll need this later
1736 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1737 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1739 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1740 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1741 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1742 "trunc source and destination must both be a vector or neither", &I);
1743 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1745 visitInstruction(I);
1748 void Verifier::visitZExtInst(ZExtInst &I) {
1749 // Get the source and destination types
1750 Type *SrcTy = I.getOperand(0)->getType();
1751 Type *DestTy = I.getType();
1753 // Get the size of the types in bits, we'll need this later
1754 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1755 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1756 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1757 "zext source and destination must both be a vector or neither", &I);
1758 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1759 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1761 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1763 visitInstruction(I);
1766 void Verifier::visitSExtInst(SExtInst &I) {
1767 // Get the source and destination types
1768 Type *SrcTy = I.getOperand(0)->getType();
1769 Type *DestTy = I.getType();
1771 // Get the size of the types in bits, we'll need this later
1772 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1773 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1775 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1776 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1777 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1778 "sext source and destination must both be a vector or neither", &I);
1779 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1781 visitInstruction(I);
1784 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1785 // Get the source and destination types
1786 Type *SrcTy = I.getOperand(0)->getType();
1787 Type *DestTy = I.getType();
1788 // Get the size of the types in bits, we'll need this later
1789 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1790 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1792 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1793 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1794 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1795 "fptrunc source and destination must both be a vector or neither", &I);
1796 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1798 visitInstruction(I);
1801 void Verifier::visitFPExtInst(FPExtInst &I) {
1802 // Get the source and destination types
1803 Type *SrcTy = I.getOperand(0)->getType();
1804 Type *DestTy = I.getType();
1806 // Get the size of the types in bits, we'll need this later
1807 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1808 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1810 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1811 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1812 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1813 "fpext source and destination must both be a vector or neither", &I);
1814 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1816 visitInstruction(I);
1819 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1820 // Get the source and destination types
1821 Type *SrcTy = I.getOperand(0)->getType();
1822 Type *DestTy = I.getType();
1824 bool SrcVec = SrcTy->isVectorTy();
1825 bool DstVec = DestTy->isVectorTy();
1827 Assert(SrcVec == DstVec,
1828 "UIToFP source and dest must both be vector or scalar", &I);
1829 Assert(SrcTy->isIntOrIntVectorTy(),
1830 "UIToFP source must be integer or integer vector", &I);
1831 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1834 if (SrcVec && DstVec)
1835 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1836 cast<VectorType>(DestTy)->getNumElements(),
1837 "UIToFP source and dest vector length mismatch", &I);
1839 visitInstruction(I);
1842 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1843 // Get the source and destination types
1844 Type *SrcTy = I.getOperand(0)->getType();
1845 Type *DestTy = I.getType();
1847 bool SrcVec = SrcTy->isVectorTy();
1848 bool DstVec = DestTy->isVectorTy();
1850 Assert(SrcVec == DstVec,
1851 "SIToFP source and dest must both be vector or scalar", &I);
1852 Assert(SrcTy->isIntOrIntVectorTy(),
1853 "SIToFP source must be integer or integer vector", &I);
1854 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1857 if (SrcVec && DstVec)
1858 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1859 cast<VectorType>(DestTy)->getNumElements(),
1860 "SIToFP source and dest vector length mismatch", &I);
1862 visitInstruction(I);
1865 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1866 // Get the source and destination types
1867 Type *SrcTy = I.getOperand(0)->getType();
1868 Type *DestTy = I.getType();
1870 bool SrcVec = SrcTy->isVectorTy();
1871 bool DstVec = DestTy->isVectorTy();
1873 Assert(SrcVec == DstVec,
1874 "FPToUI source and dest must both be vector or scalar", &I);
1875 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1877 Assert(DestTy->isIntOrIntVectorTy(),
1878 "FPToUI result must be integer or integer vector", &I);
1880 if (SrcVec && DstVec)
1881 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1882 cast<VectorType>(DestTy)->getNumElements(),
1883 "FPToUI source and dest vector length mismatch", &I);
1885 visitInstruction(I);
1888 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1889 // Get the source and destination types
1890 Type *SrcTy = I.getOperand(0)->getType();
1891 Type *DestTy = I.getType();
1893 bool SrcVec = SrcTy->isVectorTy();
1894 bool DstVec = DestTy->isVectorTy();
1896 Assert(SrcVec == DstVec,
1897 "FPToSI source and dest must both be vector or scalar", &I);
1898 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
1900 Assert(DestTy->isIntOrIntVectorTy(),
1901 "FPToSI result must be integer or integer vector", &I);
1903 if (SrcVec && DstVec)
1904 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1905 cast<VectorType>(DestTy)->getNumElements(),
1906 "FPToSI source and dest vector length mismatch", &I);
1908 visitInstruction(I);
1911 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1912 // Get the source and destination types
1913 Type *SrcTy = I.getOperand(0)->getType();
1914 Type *DestTy = I.getType();
1916 Assert(SrcTy->getScalarType()->isPointerTy(),
1917 "PtrToInt source must be pointer", &I);
1918 Assert(DestTy->getScalarType()->isIntegerTy(),
1919 "PtrToInt result must be integral", &I);
1920 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
1923 if (SrcTy->isVectorTy()) {
1924 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1925 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1926 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1927 "PtrToInt Vector width mismatch", &I);
1930 visitInstruction(I);
1933 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1934 // Get the source and destination types
1935 Type *SrcTy = I.getOperand(0)->getType();
1936 Type *DestTy = I.getType();
1938 Assert(SrcTy->getScalarType()->isIntegerTy(),
1939 "IntToPtr source must be an integral", &I);
1940 Assert(DestTy->getScalarType()->isPointerTy(),
1941 "IntToPtr result must be a pointer", &I);
1942 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
1944 if (SrcTy->isVectorTy()) {
1945 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1946 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1947 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1948 "IntToPtr Vector width mismatch", &I);
1950 visitInstruction(I);
1953 void Verifier::visitBitCastInst(BitCastInst &I) {
1955 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1956 "Invalid bitcast", &I);
1957 visitInstruction(I);
1960 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1961 Type *SrcTy = I.getOperand(0)->getType();
1962 Type *DestTy = I.getType();
1964 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
1966 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
1968 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1969 "AddrSpaceCast must be between different address spaces", &I);
1970 if (SrcTy->isVectorTy())
1971 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1972 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1973 visitInstruction(I);
1976 /// visitPHINode - Ensure that a PHI node is well formed.
1978 void Verifier::visitPHINode(PHINode &PN) {
1979 // Ensure that the PHI nodes are all grouped together at the top of the block.
1980 // This can be tested by checking whether the instruction before this is
1981 // either nonexistent (because this is begin()) or is a PHI node. If not,
1982 // then there is some other instruction before a PHI.
1983 Assert(&PN == &PN.getParent()->front() ||
1984 isa<PHINode>(--BasicBlock::iterator(&PN)),
1985 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
1987 // Check that all of the values of the PHI node have the same type as the
1988 // result, and that the incoming blocks are really basic blocks.
1989 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1990 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
1991 "PHI node operands are not the same type as the result!", &PN);
1994 // All other PHI node constraints are checked in the visitBasicBlock method.
1996 visitInstruction(PN);
1999 void Verifier::VerifyCallSite(CallSite CS) {
2000 Instruction *I = CS.getInstruction();
2002 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2003 "Called function must be a pointer!", I);
2004 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2006 Assert(FPTy->getElementType()->isFunctionTy(),
2007 "Called function is not pointer to function type!", I);
2008 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
2010 // Verify that the correct number of arguments are being passed
2011 if (FTy->isVarArg())
2012 Assert(CS.arg_size() >= FTy->getNumParams(),
2013 "Called function requires more parameters than were provided!", I);
2015 Assert(CS.arg_size() == FTy->getNumParams(),
2016 "Incorrect number of arguments passed to called function!", I);
2018 // Verify that all arguments to the call match the function type.
2019 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2020 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2021 "Call parameter type does not match function signature!",
2022 CS.getArgument(i), FTy->getParamType(i), I);
2024 AttributeSet Attrs = CS.getAttributes();
2026 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2027 "Attribute after last parameter!", I);
2029 // Verify call attributes.
2030 VerifyFunctionAttrs(FTy, Attrs, I);
2032 // Conservatively check the inalloca argument.
2033 // We have a bug if we can find that there is an underlying alloca without
2035 if (CS.hasInAllocaArgument()) {
2036 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2037 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2038 Assert(AI->isUsedWithInAlloca(),
2039 "inalloca argument for call has mismatched alloca", AI, I);
2042 if (FTy->isVarArg()) {
2043 // FIXME? is 'nest' even legal here?
2044 bool SawNest = false;
2045 bool SawReturned = false;
2047 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2048 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2050 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2054 // Check attributes on the varargs part.
2055 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2056 Type *Ty = CS.getArgument(Idx-1)->getType();
2057 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2059 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2060 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2064 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2065 Assert(!SawReturned, "More than one parameter has attribute returned!",
2067 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2068 "Incompatible argument and return types for 'returned' "
2074 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2075 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2077 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2078 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2082 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2083 if (CS.getCalledFunction() == nullptr ||
2084 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2085 for (FunctionType::param_iterator PI = FTy->param_begin(),
2086 PE = FTy->param_end(); PI != PE; ++PI)
2087 Assert(!(*PI)->isMetadataTy(),
2088 "Function has metadata parameter but isn't an intrinsic", I);
2091 visitInstruction(*I);
2094 /// Two types are "congruent" if they are identical, or if they are both pointer
2095 /// types with different pointee types and the same address space.
2096 static bool isTypeCongruent(Type *L, Type *R) {
2099 PointerType *PL = dyn_cast<PointerType>(L);
2100 PointerType *PR = dyn_cast<PointerType>(R);
2103 return PL->getAddressSpace() == PR->getAddressSpace();
2106 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2107 static const Attribute::AttrKind ABIAttrs[] = {
2108 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2109 Attribute::InReg, Attribute::Returned};
2111 for (auto AK : ABIAttrs) {
2112 if (Attrs.hasAttribute(I + 1, AK))
2113 Copy.addAttribute(AK);
2115 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2116 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2120 void Verifier::verifyMustTailCall(CallInst &CI) {
2121 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2123 // - The caller and callee prototypes must match. Pointer types of
2124 // parameters or return types may differ in pointee type, but not
2126 Function *F = CI.getParent()->getParent();
2127 auto GetFnTy = [](Value *V) {
2128 return cast<FunctionType>(
2129 cast<PointerType>(V->getType())->getElementType());
2131 FunctionType *CallerTy = GetFnTy(F);
2132 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2133 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2134 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2135 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2136 "cannot guarantee tail call due to mismatched varargs", &CI);
2137 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2138 "cannot guarantee tail call due to mismatched return types", &CI);
2139 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2141 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2142 "cannot guarantee tail call due to mismatched parameter types", &CI);
2145 // - The calling conventions of the caller and callee must match.
2146 Assert(F->getCallingConv() == CI.getCallingConv(),
2147 "cannot guarantee tail call due to mismatched calling conv", &CI);
2149 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2150 // returned, and inalloca, must match.
2151 AttributeSet CallerAttrs = F->getAttributes();
2152 AttributeSet CalleeAttrs = CI.getAttributes();
2153 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2154 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2155 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2156 Assert(CallerABIAttrs == CalleeABIAttrs,
2157 "cannot guarantee tail call due to mismatched ABI impacting "
2158 "function attributes",
2159 &CI, CI.getOperand(I));
2162 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2163 // or a pointer bitcast followed by a ret instruction.
2164 // - The ret instruction must return the (possibly bitcasted) value
2165 // produced by the call or void.
2166 Value *RetVal = &CI;
2167 Instruction *Next = CI.getNextNode();
2169 // Handle the optional bitcast.
2170 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2171 Assert(BI->getOperand(0) == RetVal,
2172 "bitcast following musttail call must use the call", BI);
2174 Next = BI->getNextNode();
2177 // Check the return.
2178 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2179 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2181 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2182 "musttail call result must be returned", Ret);
2185 void Verifier::visitCallInst(CallInst &CI) {
2186 VerifyCallSite(&CI);
2188 if (CI.isMustTailCall())
2189 verifyMustTailCall(CI);
2191 if (Function *F = CI.getCalledFunction())
2192 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2193 visitIntrinsicFunctionCall(ID, CI);
2196 void Verifier::visitInvokeInst(InvokeInst &II) {
2197 VerifyCallSite(&II);
2199 // Verify that there is a landingpad instruction as the first non-PHI
2200 // instruction of the 'unwind' destination.
2201 Assert(II.getUnwindDest()->isLandingPad(),
2202 "The unwind destination does not have a landingpad instruction!", &II);
2204 if (Function *F = II.getCalledFunction())
2205 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2206 // CallInst as an input parameter. It not woth updating this whole
2207 // function only to support statepoint verification.
2208 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2209 VerifyStatepoint(ImmutableCallSite(&II));
2211 visitTerminatorInst(II);
2214 /// visitBinaryOperator - Check that both arguments to the binary operator are
2215 /// of the same type!
2217 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2218 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2219 "Both operands to a binary operator are not of the same type!", &B);
2221 switch (B.getOpcode()) {
2222 // Check that integer arithmetic operators are only used with
2223 // integral operands.
2224 case Instruction::Add:
2225 case Instruction::Sub:
2226 case Instruction::Mul:
2227 case Instruction::SDiv:
2228 case Instruction::UDiv:
2229 case Instruction::SRem:
2230 case Instruction::URem:
2231 Assert(B.getType()->isIntOrIntVectorTy(),
2232 "Integer arithmetic operators only work with integral types!", &B);
2233 Assert(B.getType() == B.getOperand(0)->getType(),
2234 "Integer arithmetic operators must have same type "
2235 "for operands and result!",
2238 // Check that floating-point arithmetic operators are only used with
2239 // floating-point operands.
2240 case Instruction::FAdd:
2241 case Instruction::FSub:
2242 case Instruction::FMul:
2243 case Instruction::FDiv:
2244 case Instruction::FRem:
2245 Assert(B.getType()->isFPOrFPVectorTy(),
2246 "Floating-point arithmetic operators only work with "
2247 "floating-point types!",
2249 Assert(B.getType() == B.getOperand(0)->getType(),
2250 "Floating-point arithmetic operators must have same type "
2251 "for operands and result!",
2254 // Check that logical operators are only used with integral operands.
2255 case Instruction::And:
2256 case Instruction::Or:
2257 case Instruction::Xor:
2258 Assert(B.getType()->isIntOrIntVectorTy(),
2259 "Logical operators only work with integral types!", &B);
2260 Assert(B.getType() == B.getOperand(0)->getType(),
2261 "Logical operators must have same type for operands and result!",
2264 case Instruction::Shl:
2265 case Instruction::LShr:
2266 case Instruction::AShr:
2267 Assert(B.getType()->isIntOrIntVectorTy(),
2268 "Shifts only work with integral types!", &B);
2269 Assert(B.getType() == B.getOperand(0)->getType(),
2270 "Shift return type must be same as operands!", &B);
2273 llvm_unreachable("Unknown BinaryOperator opcode!");
2276 visitInstruction(B);
2279 void Verifier::visitICmpInst(ICmpInst &IC) {
2280 // Check that the operands are the same type
2281 Type *Op0Ty = IC.getOperand(0)->getType();
2282 Type *Op1Ty = IC.getOperand(1)->getType();
2283 Assert(Op0Ty == Op1Ty,
2284 "Both operands to ICmp instruction are not of the same type!", &IC);
2285 // Check that the operands are the right type
2286 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2287 "Invalid operand types for ICmp instruction", &IC);
2288 // Check that the predicate is valid.
2289 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2290 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2291 "Invalid predicate in ICmp instruction!", &IC);
2293 visitInstruction(IC);
2296 void Verifier::visitFCmpInst(FCmpInst &FC) {
2297 // Check that the operands are the same type
2298 Type *Op0Ty = FC.getOperand(0)->getType();
2299 Type *Op1Ty = FC.getOperand(1)->getType();
2300 Assert(Op0Ty == Op1Ty,
2301 "Both operands to FCmp instruction are not of the same type!", &FC);
2302 // Check that the operands are the right type
2303 Assert(Op0Ty->isFPOrFPVectorTy(),
2304 "Invalid operand types for FCmp instruction", &FC);
2305 // Check that the predicate is valid.
2306 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2307 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2308 "Invalid predicate in FCmp instruction!", &FC);
2310 visitInstruction(FC);
2313 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2315 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2316 "Invalid extractelement operands!", &EI);
2317 visitInstruction(EI);
2320 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2321 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2323 "Invalid insertelement operands!", &IE);
2324 visitInstruction(IE);
2327 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2328 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2330 "Invalid shufflevector operands!", &SV);
2331 visitInstruction(SV);
2334 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2335 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2337 Assert(isa<PointerType>(TargetTy),
2338 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2339 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2340 "GEP into unsized type!", &GEP);
2341 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2342 GEP.getType()->isVectorTy(),
2343 "Vector GEP must return a vector value", &GEP);
2345 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2347 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
2348 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2350 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2351 cast<PointerType>(GEP.getType()->getScalarType())
2352 ->getElementType() == ElTy,
2353 "GEP is not of right type for indices!", &GEP, ElTy);
2355 if (GEP.getPointerOperandType()->isVectorTy()) {
2356 // Additional checks for vector GEPs.
2357 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2358 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2359 "Vector GEP result width doesn't match operand's", &GEP);
2360 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2361 Type *IndexTy = Idxs[i]->getType();
2362 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2364 unsigned IndexWidth = IndexTy->getVectorNumElements();
2365 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2368 visitInstruction(GEP);
2371 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2372 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2375 void Verifier::visitRangeMetadata(Instruction& I,
2376 MDNode* Range, Type* Ty) {
2378 Range == I.getMetadata(LLVMContext::MD_range) &&
2379 "precondition violation");
2381 unsigned NumOperands = Range->getNumOperands();
2382 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2383 unsigned NumRanges = NumOperands / 2;
2384 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2386 ConstantRange LastRange(1); // Dummy initial value
2387 for (unsigned i = 0; i < NumRanges; ++i) {
2389 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2390 Assert(Low, "The lower limit must be an integer!", Low);
2392 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2393 Assert(High, "The upper limit must be an integer!", High);
2394 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2395 "Range types must match instruction type!", &I);
2397 APInt HighV = High->getValue();
2398 APInt LowV = Low->getValue();
2399 ConstantRange CurRange(LowV, HighV);
2400 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2401 "Range must not be empty!", Range);
2403 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2404 "Intervals are overlapping", Range);
2405 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2407 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2410 LastRange = ConstantRange(LowV, HighV);
2412 if (NumRanges > 2) {
2414 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2416 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2417 ConstantRange FirstRange(FirstLow, FirstHigh);
2418 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2419 "Intervals are overlapping", Range);
2420 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2425 void Verifier::visitLoadInst(LoadInst &LI) {
2426 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2427 Assert(PTy, "Load operand must be a pointer.", &LI);
2428 Type *ElTy = PTy->getElementType();
2429 Assert(ElTy == LI.getType(),
2430 "Load result type does not match pointer operand type!", &LI, ElTy);
2431 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2432 "huge alignment values are unsupported", &LI);
2433 if (LI.isAtomic()) {
2434 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2435 "Load cannot have Release ordering", &LI);
2436 Assert(LI.getAlignment() != 0,
2437 "Atomic load must specify explicit alignment", &LI);
2438 if (!ElTy->isPointerTy()) {
2439 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2441 unsigned Size = ElTy->getPrimitiveSizeInBits();
2442 Assert(Size >= 8 && !(Size & (Size - 1)),
2443 "atomic load operand must be power-of-two byte-sized integer", &LI,
2447 Assert(LI.getSynchScope() == CrossThread,
2448 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2451 visitInstruction(LI);
2454 void Verifier::visitStoreInst(StoreInst &SI) {
2455 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2456 Assert(PTy, "Store operand must be a pointer.", &SI);
2457 Type *ElTy = PTy->getElementType();
2458 Assert(ElTy == SI.getOperand(0)->getType(),
2459 "Stored value type does not match pointer operand type!", &SI, ElTy);
2460 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2461 "huge alignment values are unsupported", &SI);
2462 if (SI.isAtomic()) {
2463 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2464 "Store cannot have Acquire ordering", &SI);
2465 Assert(SI.getAlignment() != 0,
2466 "Atomic store must specify explicit alignment", &SI);
2467 if (!ElTy->isPointerTy()) {
2468 Assert(ElTy->isIntegerTy(),
2469 "atomic store operand must have integer type!", &SI, ElTy);
2470 unsigned Size = ElTy->getPrimitiveSizeInBits();
2471 Assert(Size >= 8 && !(Size & (Size - 1)),
2472 "atomic store operand must be power-of-two byte-sized integer",
2476 Assert(SI.getSynchScope() == CrossThread,
2477 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2479 visitInstruction(SI);
2482 void Verifier::visitAllocaInst(AllocaInst &AI) {
2483 SmallPtrSet<const Type*, 4> Visited;
2484 PointerType *PTy = AI.getType();
2485 Assert(PTy->getAddressSpace() == 0,
2486 "Allocation instruction pointer not in the generic address space!",
2488 Assert(PTy->getElementType()->isSized(&Visited),
2489 "Cannot allocate unsized type", &AI);
2490 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2491 "Alloca array size must have integer type", &AI);
2492 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2493 "huge alignment values are unsupported", &AI);
2495 visitInstruction(AI);
2498 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2500 // FIXME: more conditions???
2501 Assert(CXI.getSuccessOrdering() != NotAtomic,
2502 "cmpxchg instructions must be atomic.", &CXI);
2503 Assert(CXI.getFailureOrdering() != NotAtomic,
2504 "cmpxchg instructions must be atomic.", &CXI);
2505 Assert(CXI.getSuccessOrdering() != Unordered,
2506 "cmpxchg instructions cannot be unordered.", &CXI);
2507 Assert(CXI.getFailureOrdering() != Unordered,
2508 "cmpxchg instructions cannot be unordered.", &CXI);
2509 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2510 "cmpxchg instructions be at least as constrained on success as fail",
2512 Assert(CXI.getFailureOrdering() != Release &&
2513 CXI.getFailureOrdering() != AcquireRelease,
2514 "cmpxchg failure ordering cannot include release semantics", &CXI);
2516 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2517 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2518 Type *ElTy = PTy->getElementType();
2519 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2521 unsigned Size = ElTy->getPrimitiveSizeInBits();
2522 Assert(Size >= 8 && !(Size & (Size - 1)),
2523 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2524 Assert(ElTy == CXI.getOperand(1)->getType(),
2525 "Expected value type does not match pointer operand type!", &CXI,
2527 Assert(ElTy == CXI.getOperand(2)->getType(),
2528 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2529 visitInstruction(CXI);
2532 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2533 Assert(RMWI.getOrdering() != NotAtomic,
2534 "atomicrmw instructions must be atomic.", &RMWI);
2535 Assert(RMWI.getOrdering() != Unordered,
2536 "atomicrmw instructions cannot be unordered.", &RMWI);
2537 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2538 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2539 Type *ElTy = PTy->getElementType();
2540 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2542 unsigned Size = ElTy->getPrimitiveSizeInBits();
2543 Assert(Size >= 8 && !(Size & (Size - 1)),
2544 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2546 Assert(ElTy == RMWI.getOperand(1)->getType(),
2547 "Argument value type does not match pointer operand type!", &RMWI,
2549 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2550 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2551 "Invalid binary operation!", &RMWI);
2552 visitInstruction(RMWI);
2555 void Verifier::visitFenceInst(FenceInst &FI) {
2556 const AtomicOrdering Ordering = FI.getOrdering();
2557 Assert(Ordering == Acquire || Ordering == Release ||
2558 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2559 "fence instructions may only have "
2560 "acquire, release, acq_rel, or seq_cst ordering.",
2562 visitInstruction(FI);
2565 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2566 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2567 EVI.getIndices()) == EVI.getType(),
2568 "Invalid ExtractValueInst operands!", &EVI);
2570 visitInstruction(EVI);
2573 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2574 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2575 IVI.getIndices()) ==
2576 IVI.getOperand(1)->getType(),
2577 "Invalid InsertValueInst operands!", &IVI);
2579 visitInstruction(IVI);
2582 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2583 BasicBlock *BB = LPI.getParent();
2585 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2587 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2588 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2590 // The landingpad instruction defines its parent as a landing pad block. The
2591 // landing pad block may be branched to only by the unwind edge of an invoke.
2592 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2593 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2594 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2595 "Block containing LandingPadInst must be jumped to "
2596 "only by the unwind edge of an invoke.",
2600 // The landingpad instruction must be the first non-PHI instruction in the
2602 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2603 "LandingPadInst not the first non-PHI instruction in the block.",
2606 // The personality functions for all landingpad instructions within the same
2607 // function should match.
2609 Assert(LPI.getPersonalityFn() == PersonalityFn,
2610 "Personality function doesn't match others in function", &LPI);
2611 PersonalityFn = LPI.getPersonalityFn();
2613 // All operands must be constants.
2614 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2616 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2617 Constant *Clause = LPI.getClause(i);
2618 if (LPI.isCatch(i)) {
2619 Assert(isa<PointerType>(Clause->getType()),
2620 "Catch operand does not have pointer type!", &LPI);
2622 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2623 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2624 "Filter operand is not an array of constants!", &LPI);
2628 visitInstruction(LPI);
2631 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2632 Instruction *Op = cast<Instruction>(I.getOperand(i));
2633 // If the we have an invalid invoke, don't try to compute the dominance.
2634 // We already reject it in the invoke specific checks and the dominance
2635 // computation doesn't handle multiple edges.
2636 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2637 if (II->getNormalDest() == II->getUnwindDest())
2641 const Use &U = I.getOperandUse(i);
2642 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2643 "Instruction does not dominate all uses!", Op, &I);
2646 /// verifyInstruction - Verify that an instruction is well formed.
2648 void Verifier::visitInstruction(Instruction &I) {
2649 BasicBlock *BB = I.getParent();
2650 Assert(BB, "Instruction not embedded in basic block!", &I);
2652 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2653 for (User *U : I.users()) {
2654 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2655 "Only PHI nodes may reference their own value!", &I);
2659 // Check that void typed values don't have names
2660 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2661 "Instruction has a name, but provides a void value!", &I);
2663 // Check that the return value of the instruction is either void or a legal
2665 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2666 "Instruction returns a non-scalar type!", &I);
2668 // Check that the instruction doesn't produce metadata. Calls are already
2669 // checked against the callee type.
2670 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2671 "Invalid use of metadata!", &I);
2673 // Check that all uses of the instruction, if they are instructions
2674 // themselves, actually have parent basic blocks. If the use is not an
2675 // instruction, it is an error!
2676 for (Use &U : I.uses()) {
2677 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2678 Assert(Used->getParent() != nullptr,
2679 "Instruction referencing"
2680 " instruction not embedded in a basic block!",
2683 CheckFailed("Use of instruction is not an instruction!", U);
2688 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2689 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2691 // Check to make sure that only first-class-values are operands to
2693 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2694 Assert(0, "Instruction operands must be first-class values!", &I);
2697 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2698 // Check to make sure that the "address of" an intrinsic function is never
2701 !F->isIntrinsic() ||
2702 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2703 "Cannot take the address of an intrinsic!", &I);
2705 !F->isIntrinsic() || isa<CallInst>(I) ||
2706 F->getIntrinsicID() == Intrinsic::donothing ||
2707 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2708 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2709 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2710 "Cannot invoke an intrinsinc other than"
2711 " donothing or patchpoint",
2713 Assert(F->getParent() == M, "Referencing function in another module!",
2715 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2716 Assert(OpBB->getParent() == BB->getParent(),
2717 "Referring to a basic block in another function!", &I);
2718 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2719 Assert(OpArg->getParent() == BB->getParent(),
2720 "Referring to an argument in another function!", &I);
2721 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2722 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2723 } else if (isa<Instruction>(I.getOperand(i))) {
2724 verifyDominatesUse(I, i);
2725 } else if (isa<InlineAsm>(I.getOperand(i))) {
2726 Assert((i + 1 == e && isa<CallInst>(I)) ||
2727 (i + 3 == e && isa<InvokeInst>(I)),
2728 "Cannot take the address of an inline asm!", &I);
2729 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2730 if (CE->getType()->isPtrOrPtrVectorTy()) {
2731 // If we have a ConstantExpr pointer, we need to see if it came from an
2732 // illegal bitcast (inttoptr <constant int> )
2733 SmallVector<const ConstantExpr *, 4> Stack;
2734 SmallPtrSet<const ConstantExpr *, 4> Visited;
2735 Stack.push_back(CE);
2737 while (!Stack.empty()) {
2738 const ConstantExpr *V = Stack.pop_back_val();
2739 if (!Visited.insert(V).second)
2742 VerifyConstantExprBitcastType(V);
2744 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2745 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2746 Stack.push_back(Op);
2753 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2754 Assert(I.getType()->isFPOrFPVectorTy(),
2755 "fpmath requires a floating point result!", &I);
2756 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2757 if (ConstantFP *CFP0 =
2758 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2759 APFloat Accuracy = CFP0->getValueAPF();
2760 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2761 "fpmath accuracy not a positive number!", &I);
2763 Assert(false, "invalid fpmath accuracy!", &I);
2767 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2768 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2769 "Ranges are only for loads, calls and invokes!", &I);
2770 visitRangeMetadata(I, Range, I.getType());
2773 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2774 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2776 Assert(isa<LoadInst>(I),
2777 "nonnull applies only to load instructions, use attributes"
2778 " for calls or invokes",
2782 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2783 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2787 InstsInThisBlock.insert(&I);
2790 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2791 /// intrinsic argument or return value) matches the type constraints specified
2792 /// by the .td file (e.g. an "any integer" argument really is an integer).
2794 /// This return true on error but does not print a message.
2795 bool Verifier::VerifyIntrinsicType(Type *Ty,
2796 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2797 SmallVectorImpl<Type*> &ArgTys) {
2798 using namespace Intrinsic;
2800 // If we ran out of descriptors, there are too many arguments.
2801 if (Infos.empty()) return true;
2802 IITDescriptor D = Infos.front();
2803 Infos = Infos.slice(1);
2806 case IITDescriptor::Void: return !Ty->isVoidTy();
2807 case IITDescriptor::VarArg: return true;
2808 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2809 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2810 case IITDescriptor::Half: return !Ty->isHalfTy();
2811 case IITDescriptor::Float: return !Ty->isFloatTy();
2812 case IITDescriptor::Double: return !Ty->isDoubleTy();
2813 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2814 case IITDescriptor::Vector: {
2815 VectorType *VT = dyn_cast<VectorType>(Ty);
2816 return !VT || VT->getNumElements() != D.Vector_Width ||
2817 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2819 case IITDescriptor::Pointer: {
2820 PointerType *PT = dyn_cast<PointerType>(Ty);
2821 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2822 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2825 case IITDescriptor::Struct: {
2826 StructType *ST = dyn_cast<StructType>(Ty);
2827 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2830 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2831 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2836 case IITDescriptor::Argument:
2837 // Two cases here - If this is the second occurrence of an argument, verify
2838 // that the later instance matches the previous instance.
2839 if (D.getArgumentNumber() < ArgTys.size())
2840 return Ty != ArgTys[D.getArgumentNumber()];
2842 // Otherwise, if this is the first instance of an argument, record it and
2843 // verify the "Any" kind.
2844 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2845 ArgTys.push_back(Ty);
2847 switch (D.getArgumentKind()) {
2848 case IITDescriptor::AK_Any: return false; // Success
2849 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2850 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2851 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2852 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2854 llvm_unreachable("all argument kinds not covered");
2856 case IITDescriptor::ExtendArgument: {
2857 // This may only be used when referring to a previous vector argument.
2858 if (D.getArgumentNumber() >= ArgTys.size())
2861 Type *NewTy = ArgTys[D.getArgumentNumber()];
2862 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2863 NewTy = VectorType::getExtendedElementVectorType(VTy);
2864 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2865 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2871 case IITDescriptor::TruncArgument: {
2872 // This may only be used when referring to a previous vector argument.
2873 if (D.getArgumentNumber() >= ArgTys.size())
2876 Type *NewTy = ArgTys[D.getArgumentNumber()];
2877 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2878 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2879 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2880 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2886 case IITDescriptor::HalfVecArgument:
2887 // This may only be used when referring to a previous vector argument.
2888 return D.getArgumentNumber() >= ArgTys.size() ||
2889 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2890 VectorType::getHalfElementsVectorType(
2891 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2892 case IITDescriptor::SameVecWidthArgument: {
2893 if (D.getArgumentNumber() >= ArgTys.size())
2895 VectorType * ReferenceType =
2896 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2897 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2898 if (!ThisArgType || !ReferenceType ||
2899 (ReferenceType->getVectorNumElements() !=
2900 ThisArgType->getVectorNumElements()))
2902 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2905 case IITDescriptor::PtrToArgument: {
2906 if (D.getArgumentNumber() >= ArgTys.size())
2908 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2909 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2910 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2912 case IITDescriptor::VecOfPtrsToElt: {
2913 if (D.getArgumentNumber() >= ArgTys.size())
2915 VectorType * ReferenceType =
2916 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2917 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2918 if (!ThisArgVecTy || !ReferenceType ||
2919 (ReferenceType->getVectorNumElements() !=
2920 ThisArgVecTy->getVectorNumElements()))
2922 PointerType *ThisArgEltTy =
2923 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2926 return (!(ThisArgEltTy->getElementType() ==
2927 ReferenceType->getVectorElementType()));
2930 llvm_unreachable("unhandled");
2933 /// \brief Verify if the intrinsic has variable arguments.
2934 /// This method is intended to be called after all the fixed arguments have been
2937 /// This method returns true on error and does not print an error message.
2939 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2940 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2941 using namespace Intrinsic;
2943 // If there are no descriptors left, then it can't be a vararg.
2947 // There should be only one descriptor remaining at this point.
2948 if (Infos.size() != 1)
2951 // Check and verify the descriptor.
2952 IITDescriptor D = Infos.front();
2953 Infos = Infos.slice(1);
2954 if (D.Kind == IITDescriptor::VarArg)
2960 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2962 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2963 Function *IF = CI.getCalledFunction();
2964 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2967 // Verify that the intrinsic prototype lines up with what the .td files
2969 FunctionType *IFTy = IF->getFunctionType();
2970 bool IsVarArg = IFTy->isVarArg();
2972 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2973 getIntrinsicInfoTableEntries(ID, Table);
2974 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2976 SmallVector<Type *, 4> ArgTys;
2977 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2978 "Intrinsic has incorrect return type!", IF);
2979 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2980 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2981 "Intrinsic has incorrect argument type!", IF);
2983 // Verify if the intrinsic call matches the vararg property.
2985 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2986 "Intrinsic was not defined with variable arguments!", IF);
2988 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2989 "Callsite was not defined with variable arguments!", IF);
2991 // All descriptors should be absorbed by now.
2992 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2994 // Now that we have the intrinsic ID and the actual argument types (and we
2995 // know they are legal for the intrinsic!) get the intrinsic name through the
2996 // usual means. This allows us to verify the mangling of argument types into
2998 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2999 Assert(ExpectedName == IF->getName(),
3000 "Intrinsic name not mangled correctly for type arguments! "
3005 // If the intrinsic takes MDNode arguments, verify that they are either global
3006 // or are local to *this* function.
3007 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
3008 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
3009 visitMetadataAsValue(*MD, CI.getParent()->getParent());
3014 case Intrinsic::ctlz: // llvm.ctlz
3015 case Intrinsic::cttz: // llvm.cttz
3016 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3017 "is_zero_undef argument of bit counting intrinsics must be a "
3021 case Intrinsic::dbg_declare: // llvm.dbg.declare
3022 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
3023 "invalid llvm.dbg.declare intrinsic call 1", &CI);
3024 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
3026 case Intrinsic::dbg_value: // llvm.dbg.value
3027 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
3029 case Intrinsic::memcpy:
3030 case Intrinsic::memmove:
3031 case Intrinsic::memset: {
3032 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
3034 "alignment argument of memory intrinsics must be a constant int",
3036 const APInt &AlignVal = AlignCI->getValue();
3037 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3038 "alignment argument of memory intrinsics must be a power of 2", &CI);
3039 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
3040 "isvolatile argument of memory intrinsics must be a constant int",
3044 case Intrinsic::gcroot:
3045 case Intrinsic::gcwrite:
3046 case Intrinsic::gcread:
3047 if (ID == Intrinsic::gcroot) {
3049 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3050 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
3051 Assert(isa<Constant>(CI.getArgOperand(1)),
3052 "llvm.gcroot parameter #2 must be a constant.", &CI);
3053 if (!AI->getType()->getElementType()->isPointerTy()) {
3054 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
3055 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3056 "or argument #2 must be a non-null constant.",
3061 Assert(CI.getParent()->getParent()->hasGC(),
3062 "Enclosing function does not use GC.", &CI);
3064 case Intrinsic::init_trampoline:
3065 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
3066 "llvm.init_trampoline parameter #2 must resolve to a function.",
3069 case Intrinsic::prefetch:
3070 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
3071 isa<ConstantInt>(CI.getArgOperand(2)) &&
3072 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
3073 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
3074 "invalid arguments to llvm.prefetch", &CI);
3076 case Intrinsic::stackprotector:
3077 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
3078 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
3080 case Intrinsic::lifetime_start:
3081 case Intrinsic::lifetime_end:
3082 case Intrinsic::invariant_start:
3083 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
3084 "size argument of memory use markers must be a constant integer",
3087 case Intrinsic::invariant_end:
3088 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
3089 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
3092 case Intrinsic::frameescape: {
3093 BasicBlock *BB = CI.getParent();
3094 Assert(BB == &BB->getParent()->front(),
3095 "llvm.frameescape used outside of entry block", &CI);
3096 Assert(!SawFrameEscape,
3097 "multiple calls to llvm.frameescape in one function", &CI);
3098 for (Value *Arg : CI.arg_operands()) {
3099 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3100 Assert(AI && AI->isStaticAlloca(),
3101 "llvm.frameescape only accepts static allocas", &CI);
3103 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3104 SawFrameEscape = true;
3107 case Intrinsic::framerecover: {
3108 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3109 Function *Fn = dyn_cast<Function>(FnArg);
3110 Assert(Fn && !Fn->isDeclaration(),
3111 "llvm.framerecover first "
3112 "argument must be function defined in this module",
3114 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3115 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3117 auto &Entry = FrameEscapeInfo[Fn];
3118 Entry.second = unsigned(
3119 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3123 case Intrinsic::eh_parentframe: {
3124 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3125 Assert(AI && AI->isStaticAlloca(),
3126 "llvm.eh.parentframe requires a static alloca", &CI);
3130 case Intrinsic::eh_unwindhelp: {
3131 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3132 Assert(AI && AI->isStaticAlloca(),
3133 "llvm.eh.unwindhelp requires a static alloca", &CI);
3137 case Intrinsic::experimental_gc_statepoint:
3138 Assert(!CI.isInlineAsm(),
3139 "gc.statepoint support for inline assembly unimplemented", &CI);
3140 Assert(CI.getParent()->getParent()->hasGC(),
3141 "Enclosing function does not use GC.", &CI);
3143 VerifyStatepoint(ImmutableCallSite(&CI));
3145 case Intrinsic::experimental_gc_result_int:
3146 case Intrinsic::experimental_gc_result_float:
3147 case Intrinsic::experimental_gc_result_ptr:
3148 case Intrinsic::experimental_gc_result: {
3149 Assert(CI.getParent()->getParent()->hasGC(),
3150 "Enclosing function does not use GC.", &CI);
3151 // Are we tied to a statepoint properly?
3152 CallSite StatepointCS(CI.getArgOperand(0));
3153 const Function *StatepointFn =
3154 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3155 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3156 StatepointFn->getIntrinsicID() ==
3157 Intrinsic::experimental_gc_statepoint,
3158 "gc.result operand #1 must be from a statepoint", &CI,
3159 CI.getArgOperand(0));
3161 // Assert that result type matches wrapped callee.
3162 const Value *Target = StatepointCS.getArgument(0);
3163 const PointerType *PT = cast<PointerType>(Target->getType());
3164 const FunctionType *TargetFuncType =
3165 cast<FunctionType>(PT->getElementType());
3166 Assert(CI.getType() == TargetFuncType->getReturnType(),
3167 "gc.result result type does not match wrapped callee", &CI);
3170 case Intrinsic::experimental_gc_relocate: {
3171 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3173 // Check that this relocate is correctly tied to the statepoint
3175 // This is case for relocate on the unwinding path of an invoke statepoint
3176 if (ExtractValueInst *ExtractValue =
3177 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3178 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3179 "gc relocate on unwind path incorrectly linked to the statepoint",
3182 const BasicBlock *invokeBB =
3183 ExtractValue->getParent()->getUniquePredecessor();
3185 // Landingpad relocates should have only one predecessor with invoke
3186 // statepoint terminator
3187 Assert(invokeBB, "safepoints should have unique landingpads",
3188 ExtractValue->getParent());
3189 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3191 Assert(isStatepoint(invokeBB->getTerminator()),
3192 "gc relocate should be linked to a statepoint", invokeBB);
3195 // In all other cases relocate should be tied to the statepoint directly.
3196 // This covers relocates on a normal return path of invoke statepoint and
3197 // relocates of a call statepoint
3198 auto Token = CI.getArgOperand(0);
3199 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3200 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3203 // Verify rest of the relocate arguments
3205 GCRelocateOperands ops(&CI);
3206 ImmutableCallSite StatepointCS(ops.statepoint());
3208 // Both the base and derived must be piped through the safepoint
3209 Value* Base = CI.getArgOperand(1);
3210 Assert(isa<ConstantInt>(Base),
3211 "gc.relocate operand #2 must be integer offset", &CI);
3213 Value* Derived = CI.getArgOperand(2);
3214 Assert(isa<ConstantInt>(Derived),
3215 "gc.relocate operand #3 must be integer offset", &CI);
3217 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3218 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3220 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3221 "gc.relocate: statepoint base index out of bounds", &CI);
3222 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3223 "gc.relocate: statepoint derived index out of bounds", &CI);
3225 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3226 // section of the statepoint's argument
3227 Assert(StatepointCS.arg_size() > 0,
3228 "gc.statepoint: insufficient arguments");
3229 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3230 "gc.statement: number of call arguments must be constant integer");
3231 const unsigned NumCallArgs =
3232 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3233 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3234 "gc.statepoint: mismatch in number of call arguments");
3235 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3236 "gc.statepoint: number of deoptimization arguments must be "
3237 "a constant integer");
3238 const int NumDeoptArgs =
3239 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3240 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3241 const int GCParamArgsEnd = StatepointCS.arg_size();
3242 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3243 "gc.relocate: statepoint base index doesn't fall within the "
3244 "'gc parameters' section of the statepoint call",
3246 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3247 "gc.relocate: statepoint derived index doesn't fall within the "
3248 "'gc parameters' section of the statepoint call",
3251 // Assert that the result type matches the type of the relocated pointer
3252 GCRelocateOperands Operands(&CI);
3253 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3254 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3260 template <class DbgIntrinsicTy>
3261 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3262 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3263 Assert(isa<ValueAsMetadata>(MD) ||
3264 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3265 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3266 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3267 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3268 DII.getRawVariable());
3269 Assert(isa<MDExpression>(DII.getRawExpression()),
3270 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3271 DII.getRawExpression());
3274 void Verifier::verifyDebugInfo() {
3275 // Run the debug info verifier only if the regular verifier succeeds, since
3276 // sometimes checks that have already failed will cause crashes here.
3277 if (EverBroken || !VerifyDebugInfo)
3280 DebugInfoFinder Finder;
3281 Finder.processModule(*M);
3282 processInstructions(Finder);
3284 // Verify Debug Info.
3286 // NOTE: The loud braces are necessary for MSVC compatibility.
3287 for (DICompileUnit CU : Finder.compile_units()) {
3288 Assert(CU.Verify(), "DICompileUnit does not Verify!", CU);
3290 for (DISubprogram S : Finder.subprograms()) {
3291 Assert(S.Verify(), "DISubprogram does not Verify!", S);
3293 for (DIGlobalVariable GV : Finder.global_variables()) {
3294 Assert(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3296 for (DIType T : Finder.types()) {
3297 Assert(T.Verify(), "DIType does not Verify!", T);
3299 for (DIScope S : Finder.scopes()) {
3300 Assert(S.Verify(), "DIScope does not Verify!", S);
3304 void Verifier::processInstructions(DebugInfoFinder &Finder) {
3305 for (const Function &F : *M)
3306 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3307 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3308 Finder.processLocation(*M, DILocation(MD));
3309 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3310 processCallInst(Finder, *CI);
3314 void Verifier::processCallInst(DebugInfoFinder &Finder, const CallInst &CI) {
3315 if (Function *F = CI.getCalledFunction())
3316 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3318 case Intrinsic::dbg_declare:
3319 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
3321 case Intrinsic::dbg_value:
3322 Finder.processValue(*M, cast<DbgValueInst>(&CI));
3329 //===----------------------------------------------------------------------===//
3330 // Implement the public interfaces to this file...
3331 //===----------------------------------------------------------------------===//
3333 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3334 Function &F = const_cast<Function &>(f);
3335 assert(!F.isDeclaration() && "Cannot verify external functions");
3337 raw_null_ostream NullStr;
3338 Verifier V(OS ? *OS : NullStr);
3340 // Note that this function's return value is inverted from what you would
3341 // expect of a function called "verify".
3342 return !V.verify(F);
3345 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3346 raw_null_ostream NullStr;
3347 Verifier V(OS ? *OS : NullStr);
3349 bool Broken = false;
3350 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3351 if (!I->isDeclaration() && !I->isMaterializable())
3352 Broken |= !V.verify(*I);
3354 // Note that this function's return value is inverted from what you would
3355 // expect of a function called "verify".
3356 return !V.verify(M) || Broken;
3360 struct VerifierLegacyPass : public FunctionPass {
3366 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3367 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3369 explicit VerifierLegacyPass(bool FatalErrors)
3370 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3371 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3374 bool runOnFunction(Function &F) override {
3375 if (!V.verify(F) && FatalErrors)
3376 report_fatal_error("Broken function found, compilation aborted!");
3381 bool doFinalization(Module &M) override {
3382 if (!V.verify(M) && FatalErrors)
3383 report_fatal_error("Broken module found, compilation aborted!");
3388 void getAnalysisUsage(AnalysisUsage &AU) const override {
3389 AU.setPreservesAll();
3394 char VerifierLegacyPass::ID = 0;
3395 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3397 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3398 return new VerifierLegacyPass(FatalErrors);
3401 PreservedAnalyses VerifierPass::run(Module &M) {
3402 if (verifyModule(M, &dbgs()) && FatalErrors)
3403 report_fatal_error("Broken module found, compilation aborted!");
3405 return PreservedAnalyses::all();
3408 PreservedAnalyses VerifierPass::run(Function &F) {
3409 if (verifyFunction(F, &dbgs()) && FatalErrors)
3410 report_fatal_error("Broken function found, compilation aborted!");
3412 return PreservedAnalyses::all();