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