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/APFloat.h" 49 #include "llvm/ADT/APInt.h" 50 #include "llvm/ADT/ArrayRef.h" 51 #include "llvm/ADT/DenseMap.h" 52 #include "llvm/ADT/ilist.h" 53 #include "llvm/ADT/MapVector.h" 54 #include "llvm/ADT/Optional.h" 55 #include "llvm/ADT/STLExtras.h" 56 #include "llvm/ADT/SmallPtrSet.h" 57 #include "llvm/ADT/SmallSet.h" 58 #include "llvm/ADT/SmallVector.h" 59 #include "llvm/ADT/StringMap.h" 60 #include "llvm/ADT/StringRef.h" 61 #include "llvm/ADT/Twine.h" 62 #include "llvm/IR/Argument.h" 63 #include "llvm/IR/Attributes.h" 64 #include "llvm/IR/BasicBlock.h" 65 #include "llvm/IR/CFG.h" 66 #include "llvm/IR/CallSite.h" 67 #include "llvm/IR/CallingConv.h" 68 #include "llvm/IR/Comdat.h" 69 #include "llvm/IR/Constant.h" 70 #include "llvm/IR/ConstantRange.h" 71 #include "llvm/IR/Constants.h" 72 #include "llvm/IR/DataLayout.h" 73 #include "llvm/IR/DebugInfo.h" 74 #include "llvm/IR/DebugInfoMetadata.h" 75 #include "llvm/IR/DebugLoc.h" 76 #include "llvm/IR/DerivedTypes.h" 77 #include "llvm/IR/DiagnosticInfo.h" 78 #include "llvm/IR/Dominators.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GlobalAlias.h" 81 #include "llvm/IR/GlobalValue.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/InstVisitor.h" 88 #include "llvm/IR/IntrinsicInst.h" 89 #include "llvm/IR/Intrinsics.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/Metadata.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/ModuleSlotTracker.h" 94 #include "llvm/IR/PassManager.h" 95 #include "llvm/IR/Statepoint.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/Use.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/Pass.h" 101 #include "llvm/Support/AtomicOrdering.h" 102 #include "llvm/Support/Casting.h" 103 #include "llvm/Support/CommandLine.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/Dwarf.h" 106 #include "llvm/Support/ErrorHandling.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include <algorithm> 110 #include <cassert> 111 #include <cstdint> 112 #include <memory> 113 #include <string> 114 #include <utility> 115 116 using namespace llvm; 117 118 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true)); 119 120 namespace { 121 122 struct VerifierSupport { 123 raw_ostream *OS; 124 const Module &M; 125 ModuleSlotTracker MST; 126 const DataLayout &DL; 127 LLVMContext &Context; 128 129 /// Track the brokenness of the module while recursively visiting. 130 bool Broken = false; 131 /// Broken debug info can be "recovered" from by stripping the debug info. 132 bool BrokenDebugInfo = false; 133 /// Whether to treat broken debug info as an error. 134 bool TreatBrokenDebugInfoAsError = true; 135 136 explicit VerifierSupport(raw_ostream *OS, const Module &M) 137 : OS(OS), M(M), MST(&M), DL(M.getDataLayout()), Context(M.getContext()) {} 138 139 private: 140 void Write(const Module *M) { 141 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 142 } 143 144 void Write(const Value *V) { 145 if (!V) 146 return; 147 if (isa<Instruction>(V)) { 148 V->print(*OS, MST); 149 *OS << '\n'; 150 } else { 151 V->printAsOperand(*OS, true, MST); 152 *OS << '\n'; 153 } 154 } 155 156 void Write(ImmutableCallSite CS) { 157 Write(CS.getInstruction()); 158 } 159 160 void Write(const Metadata *MD) { 161 if (!MD) 162 return; 163 MD->print(*OS, MST, &M); 164 *OS << '\n'; 165 } 166 167 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 168 Write(MD.get()); 169 } 170 171 void Write(const NamedMDNode *NMD) { 172 if (!NMD) 173 return; 174 NMD->print(*OS, MST); 175 *OS << '\n'; 176 } 177 178 void Write(Type *T) { 179 if (!T) 180 return; 181 *OS << ' ' << *T; 182 } 183 184 void Write(const Comdat *C) { 185 if (!C) 186 return; 187 *OS << *C; 188 } 189 190 void Write(const APInt *AI) { 191 if (!AI) 192 return; 193 *OS << *AI << '\n'; 194 } 195 196 void Write(const unsigned i) { *OS << i << '\n'; } 197 198 template <typename T> void Write(ArrayRef<T> Vs) { 199 for (const T &V : Vs) 200 Write(V); 201 } 202 203 template <typename T1, typename... Ts> 204 void WriteTs(const T1 &V1, const Ts &... Vs) { 205 Write(V1); 206 WriteTs(Vs...); 207 } 208 209 template <typename... Ts> void WriteTs() {} 210 211 public: 212 /// \brief A check failed, so printout out the condition and the message. 213 /// 214 /// This provides a nice place to put a breakpoint if you want to see why 215 /// something is not correct. 216 void CheckFailed(const Twine &Message) { 217 if (OS) 218 *OS << Message << '\n'; 219 Broken = true; 220 } 221 222 /// \brief A check failed (with values to print). 223 /// 224 /// This calls the Message-only version so that the above is easier to set a 225 /// breakpoint on. 226 template <typename T1, typename... Ts> 227 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 228 CheckFailed(Message); 229 if (OS) 230 WriteTs(V1, Vs...); 231 } 232 233 /// A debug info check failed. 234 void DebugInfoCheckFailed(const Twine &Message) { 235 if (OS) 236 *OS << Message << '\n'; 237 Broken |= TreatBrokenDebugInfoAsError; 238 BrokenDebugInfo = true; 239 } 240 241 /// A debug info check failed (with values to print). 242 template <typename T1, typename... Ts> 243 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, 244 const Ts &... Vs) { 245 DebugInfoCheckFailed(Message); 246 if (OS) 247 WriteTs(V1, Vs...); 248 } 249 }; 250 251 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 252 friend class InstVisitor<Verifier>; 253 254 DominatorTree DT; 255 256 /// \brief When verifying a basic block, keep track of all of the 257 /// instructions we have seen so far. 258 /// 259 /// This allows us to do efficient dominance checks for the case when an 260 /// instruction has an operand that is an instruction in the same block. 261 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 262 263 /// \brief Keep track of the metadata nodes that have been checked already. 264 SmallPtrSet<const Metadata *, 32> MDNodes; 265 266 /// Track all DICompileUnits visited. 267 SmallPtrSet<const Metadata *, 2> CUVisited; 268 269 /// \brief The result type for a landingpad. 270 Type *LandingPadResultTy; 271 272 /// \brief Whether we've seen a call to @llvm.localescape in this function 273 /// already. 274 bool SawFrameEscape; 275 276 /// Stores the count of how many objects were passed to llvm.localescape for a 277 /// given function and the largest index passed to llvm.localrecover. 278 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 279 280 // Maps catchswitches and cleanuppads that unwind to siblings to the 281 // terminators that indicate the unwind, used to detect cycles therein. 282 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo; 283 284 /// Cache of constants visited in search of ConstantExprs. 285 SmallPtrSet<const Constant *, 32> ConstantExprVisited; 286 287 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic. 288 SmallVector<const Function *, 4> DeoptimizeDeclarations; 289 290 // Verify that this GlobalValue is only used in this module. 291 // This map is used to avoid visiting uses twice. We can arrive at a user 292 // twice, if they have multiple operands. In particular for very large 293 // constant expressions, we can arrive at a particular user many times. 294 SmallPtrSet<const Value *, 32> GlobalValueVisited; 295 296 /// Cache of TBAA base nodes that have already been visited. This cachce maps 297 /// a node that has been visited to a pair (IsInvalid, BitWidth) where 298 /// 299 /// \c IsInvalid is true iff the node is invalid. 300 /// \c BitWidth, if non-zero, is the bitwidth of the integer used to denoting 301 /// the offset of the access. If zero, only a zero offset is allowed. 302 /// 303 /// \c BitWidth has no meaning if \c IsInvalid is true. 304 typedef std::pair<bool, unsigned> TBAABaseNodeSummary; 305 DenseMap<MDNode *, TBAABaseNodeSummary> TBAABaseNodes; 306 307 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I); 308 309 public: 310 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError, 311 const Module &M) 312 : VerifierSupport(OS, M), LandingPadResultTy(nullptr), 313 SawFrameEscape(false) { 314 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError; 315 } 316 317 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; } 318 319 bool verify(const Function &F) { 320 assert(F.getParent() == &M && 321 "An instance of this class only works with a specific module!"); 322 323 // First ensure the function is well-enough formed to compute dominance 324 // information, and directly compute a dominance tree. We don't rely on the 325 // pass manager to provide this as it isolates us from a potentially 326 // out-of-date dominator tree and makes it significantly more complex to run 327 // this code outside of a pass manager. 328 // FIXME: It's really gross that we have to cast away constness here. 329 if (!F.empty()) 330 DT.recalculate(const_cast<Function &>(F)); 331 332 for (const BasicBlock &BB : F) { 333 if (!BB.empty() && BB.back().isTerminator()) 334 continue; 335 336 if (OS) { 337 *OS << "Basic Block in function '" << F.getName() 338 << "' does not have terminator!\n"; 339 BB.printAsOperand(*OS, true, MST); 340 *OS << "\n"; 341 } 342 return false; 343 } 344 345 Broken = false; 346 // FIXME: We strip const here because the inst visitor strips const. 347 visit(const_cast<Function &>(F)); 348 verifySiblingFuncletUnwinds(); 349 InstsInThisBlock.clear(); 350 LandingPadResultTy = nullptr; 351 SawFrameEscape = false; 352 SiblingFuncletInfo.clear(); 353 354 return !Broken; 355 } 356 357 /// Verify the module that this instance of \c Verifier was initialized with. 358 bool verify() { 359 Broken = false; 360 361 // Collect all declarations of the llvm.experimental.deoptimize intrinsic. 362 for (const Function &F : M) 363 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize) 364 DeoptimizeDeclarations.push_back(&F); 365 366 // Now that we've visited every function, verify that we never asked to 367 // recover a frame index that wasn't escaped. 368 verifyFrameRecoverIndices(); 369 for (const GlobalVariable &GV : M.globals()) 370 visitGlobalVariable(GV); 371 372 for (const GlobalAlias &GA : M.aliases()) 373 visitGlobalAlias(GA); 374 375 for (const NamedMDNode &NMD : M.named_metadata()) 376 visitNamedMDNode(NMD); 377 378 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 379 visitComdat(SMEC.getValue()); 380 381 visitModuleFlags(M); 382 visitModuleIdents(M); 383 384 verifyCompileUnits(); 385 386 verifyDeoptimizeCallingConvs(); 387 388 return !Broken; 389 } 390 391 private: 392 // Verification methods... 393 void visitGlobalValue(const GlobalValue &GV); 394 void visitGlobalVariable(const GlobalVariable &GV); 395 void visitGlobalAlias(const GlobalAlias &GA); 396 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 397 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 398 const GlobalAlias &A, const Constant &C); 399 void visitNamedMDNode(const NamedMDNode &NMD); 400 void visitMDNode(const MDNode &MD); 401 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 402 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 403 void visitComdat(const Comdat &C); 404 void visitModuleIdents(const Module &M); 405 void visitModuleFlags(const Module &M); 406 void visitModuleFlag(const MDNode *Op, 407 DenseMap<const MDString *, const MDNode *> &SeenIDs, 408 SmallVectorImpl<const MDNode *> &Requirements); 409 void visitFunction(const Function &F); 410 void visitBasicBlock(BasicBlock &BB); 411 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty); 412 void visitDereferenceableMetadata(Instruction &I, MDNode *MD); 413 void visitTBAAMetadata(Instruction &I, MDNode *MD); 414 415 /// \name Helper functions used by \c visitTBAAMetadata. 416 /// @{ 417 MDNode *getFieldNodeFromTBAABaseNode(Instruction &I, MDNode *BaseNode, 418 APInt &Offset); 419 TBAABaseNodeSummary verifyTBAABaseNode(Instruction &I, MDNode *BaseNode); 420 TBAABaseNodeSummary verifyTBAABaseNodeImpl(Instruction &I, MDNode *BaseNode); 421 /// @} 422 423 template <class Ty> bool isValidMetadataArray(const MDTuple &N); 424 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 425 #include "llvm/IR/Metadata.def" 426 void visitDIScope(const DIScope &N); 427 void visitDIVariable(const DIVariable &N); 428 void visitDILexicalBlockBase(const DILexicalBlockBase &N); 429 void visitDITemplateParameter(const DITemplateParameter &N); 430 431 void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 432 433 // InstVisitor overrides... 434 using InstVisitor<Verifier>::visit; 435 void visit(Instruction &I); 436 437 void visitTruncInst(TruncInst &I); 438 void visitZExtInst(ZExtInst &I); 439 void visitSExtInst(SExtInst &I); 440 void visitFPTruncInst(FPTruncInst &I); 441 void visitFPExtInst(FPExtInst &I); 442 void visitFPToUIInst(FPToUIInst &I); 443 void visitFPToSIInst(FPToSIInst &I); 444 void visitUIToFPInst(UIToFPInst &I); 445 void visitSIToFPInst(SIToFPInst &I); 446 void visitIntToPtrInst(IntToPtrInst &I); 447 void visitPtrToIntInst(PtrToIntInst &I); 448 void visitBitCastInst(BitCastInst &I); 449 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 450 void visitPHINode(PHINode &PN); 451 void visitBinaryOperator(BinaryOperator &B); 452 void visitICmpInst(ICmpInst &IC); 453 void visitFCmpInst(FCmpInst &FC); 454 void visitExtractElementInst(ExtractElementInst &EI); 455 void visitInsertElementInst(InsertElementInst &EI); 456 void visitShuffleVectorInst(ShuffleVectorInst &EI); 457 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 458 void visitCallInst(CallInst &CI); 459 void visitInvokeInst(InvokeInst &II); 460 void visitGetElementPtrInst(GetElementPtrInst &GEP); 461 void visitLoadInst(LoadInst &LI); 462 void visitStoreInst(StoreInst &SI); 463 void verifyDominatesUse(Instruction &I, unsigned i); 464 void visitInstruction(Instruction &I); 465 void visitTerminatorInst(TerminatorInst &I); 466 void visitBranchInst(BranchInst &BI); 467 void visitReturnInst(ReturnInst &RI); 468 void visitSwitchInst(SwitchInst &SI); 469 void visitIndirectBrInst(IndirectBrInst &BI); 470 void visitSelectInst(SelectInst &SI); 471 void visitUserOp1(Instruction &I); 472 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 473 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS); 474 template <class DbgIntrinsicTy> 475 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII); 476 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 477 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 478 void visitFenceInst(FenceInst &FI); 479 void visitAllocaInst(AllocaInst &AI); 480 void visitExtractValueInst(ExtractValueInst &EVI); 481 void visitInsertValueInst(InsertValueInst &IVI); 482 void visitEHPadPredecessors(Instruction &I); 483 void visitLandingPadInst(LandingPadInst &LPI); 484 void visitResumeInst(ResumeInst &RI); 485 void visitCatchPadInst(CatchPadInst &CPI); 486 void visitCatchReturnInst(CatchReturnInst &CatchReturn); 487 void visitCleanupPadInst(CleanupPadInst &CPI); 488 void visitFuncletPadInst(FuncletPadInst &FPI); 489 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 490 void visitCleanupReturnInst(CleanupReturnInst &CRI); 491 492 void verifyCallSite(CallSite CS); 493 void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal); 494 void verifySwiftErrorValue(const Value *SwiftErrorVal); 495 void verifyMustTailCall(CallInst &CI); 496 bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT, 497 unsigned ArgNo, std::string &Suffix); 498 bool verifyAttributeCount(AttributeSet Attrs, unsigned Params); 499 void verifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction, 500 const Value *V); 501 void verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 502 bool isReturnValue, const Value *V); 503 void verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 504 const Value *V); 505 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs); 506 507 void visitConstantExprsRecursively(const Constant *EntryC); 508 void visitConstantExpr(const ConstantExpr *CE); 509 void verifyStatepoint(ImmutableCallSite CS); 510 void verifyFrameRecoverIndices(); 511 void verifySiblingFuncletUnwinds(); 512 513 void verifyFragmentExpression(const DbgInfoIntrinsic &I); 514 515 /// Module-level debug info verification... 516 void verifyCompileUnits(); 517 518 /// Module-level verification that all @llvm.experimental.deoptimize 519 /// declarations share the same calling convention. 520 void verifyDeoptimizeCallingConvs(); 521 }; 522 523 } // end anonymous namespace 524 525 /// We know that cond should be true, if not print an error message. 526 #define Assert(C, ...) \ 527 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 528 529 /// We know that a debug info condition should be true, if not print 530 /// an error message. 531 #define AssertDI(C, ...) \ 532 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false) 533 534 void Verifier::visit(Instruction &I) { 535 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 536 Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 537 InstVisitor<Verifier>::visit(I); 538 } 539 540 // Helper to recursively iterate over indirect users. By 541 // returning false, the callback can ask to stop recursing 542 // further. 543 static void forEachUser(const Value *User, 544 SmallPtrSet<const Value *, 32> &Visited, 545 llvm::function_ref<bool(const Value *)> Callback) { 546 if (!Visited.insert(User).second) 547 return; 548 for (const Value *TheNextUser : User->materialized_users()) 549 if (Callback(TheNextUser)) 550 forEachUser(TheNextUser, Visited, Callback); 551 } 552 553 void Verifier::visitGlobalValue(const GlobalValue &GV) { 554 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(), 555 "Global is external, but doesn't have external or weak linkage!", &GV); 556 557 Assert(GV.getAlignment() <= Value::MaximumAlignment, 558 "huge alignment values are unsupported", &GV); 559 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 560 "Only global variables can have appending linkage!", &GV); 561 562 if (GV.hasAppendingLinkage()) { 563 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 564 Assert(GVar && GVar->getValueType()->isArrayTy(), 565 "Only global arrays can have appending linkage!", GVar); 566 } 567 568 if (GV.isDeclarationForLinker()) 569 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 570 571 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool { 572 if (const Instruction *I = dyn_cast<Instruction>(V)) { 573 if (!I->getParent() || !I->getParent()->getParent()) 574 CheckFailed("Global is referenced by parentless instruction!", &GV, &M, 575 I); 576 else if (I->getParent()->getParent()->getParent() != &M) 577 CheckFailed("Global is referenced in a different module!", &GV, &M, I, 578 I->getParent()->getParent(), 579 I->getParent()->getParent()->getParent()); 580 return false; 581 } else if (const Function *F = dyn_cast<Function>(V)) { 582 if (F->getParent() != &M) 583 CheckFailed("Global is used by function in a different module", &GV, &M, 584 F, F->getParent()); 585 return false; 586 } 587 return true; 588 }); 589 } 590 591 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 592 if (GV.hasInitializer()) { 593 Assert(GV.getInitializer()->getType() == GV.getValueType(), 594 "Global variable initializer type does not match global " 595 "variable type!", 596 &GV); 597 598 // If the global has common linkage, it must have a zero initializer and 599 // cannot be constant. 600 if (GV.hasCommonLinkage()) { 601 Assert(GV.getInitializer()->isNullValue(), 602 "'common' global must have a zero initializer!", &GV); 603 Assert(!GV.isConstant(), "'common' global may not be marked constant!", 604 &GV); 605 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 606 } 607 } 608 609 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 610 GV.getName() == "llvm.global_dtors")) { 611 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 612 "invalid linkage for intrinsic global variable", &GV); 613 // Don't worry about emitting an error for it not being an array, 614 // visitGlobalValue will complain on appending non-array. 615 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 616 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 617 PointerType *FuncPtrTy = 618 FunctionType::get(Type::getVoidTy(Context), false)->getPointerTo(); 619 // FIXME: Reject the 2-field form in LLVM 4.0. 620 Assert(STy && 621 (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 622 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 623 STy->getTypeAtIndex(1) == FuncPtrTy, 624 "wrong type for intrinsic global variable", &GV); 625 if (STy->getNumElements() == 3) { 626 Type *ETy = STy->getTypeAtIndex(2); 627 Assert(ETy->isPointerTy() && 628 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 629 "wrong type for intrinsic global variable", &GV); 630 } 631 } 632 } 633 634 if (GV.hasName() && (GV.getName() == "llvm.used" || 635 GV.getName() == "llvm.compiler.used")) { 636 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 637 "invalid linkage for intrinsic global variable", &GV); 638 Type *GVType = GV.getValueType(); 639 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 640 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 641 Assert(PTy, "wrong type for intrinsic global variable", &GV); 642 if (GV.hasInitializer()) { 643 const Constant *Init = GV.getInitializer(); 644 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 645 Assert(InitArray, "wrong initalizer for intrinsic global variable", 646 Init); 647 for (Value *Op : InitArray->operands()) { 648 Value *V = Op->stripPointerCastsNoFollowAliases(); 649 Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 650 isa<GlobalAlias>(V), 651 "invalid llvm.used member", V); 652 Assert(V->hasName(), "members of llvm.used must be named", V); 653 } 654 } 655 } 656 } 657 658 Assert(!GV.hasDLLImportStorageClass() || 659 (GV.isDeclaration() && GV.hasExternalLinkage()) || 660 GV.hasAvailableExternallyLinkage(), 661 "Global is marked as dllimport, but not external", &GV); 662 663 if (!GV.hasInitializer()) { 664 visitGlobalValue(GV); 665 return; 666 } 667 668 // Walk any aggregate initializers looking for bitcasts between address spaces 669 visitConstantExprsRecursively(GV.getInitializer()); 670 671 visitGlobalValue(GV); 672 } 673 674 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 675 SmallPtrSet<const GlobalAlias*, 4> Visited; 676 Visited.insert(&GA); 677 visitAliaseeSubExpr(Visited, GA, C); 678 } 679 680 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 681 const GlobalAlias &GA, const Constant &C) { 682 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 683 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 684 &GA); 685 686 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 687 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 688 689 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias", 690 &GA); 691 } else { 692 // Only continue verifying subexpressions of GlobalAliases. 693 // Do not recurse into global initializers. 694 return; 695 } 696 } 697 698 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 699 visitConstantExprsRecursively(CE); 700 701 for (const Use &U : C.operands()) { 702 Value *V = &*U; 703 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 704 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 705 else if (const auto *C2 = dyn_cast<Constant>(V)) 706 visitAliaseeSubExpr(Visited, GA, *C2); 707 } 708 } 709 710 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 711 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 712 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 713 "weak_odr, or external linkage!", 714 &GA); 715 const Constant *Aliasee = GA.getAliasee(); 716 Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 717 Assert(GA.getType() == Aliasee->getType(), 718 "Alias and aliasee types should match!", &GA); 719 720 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 721 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 722 723 visitAliaseeSubExpr(GA, *Aliasee); 724 725 visitGlobalValue(GA); 726 } 727 728 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 729 // There used to be various other llvm.dbg.* nodes, but we don't support 730 // upgrading them and we want to reserve the namespace for future uses. 731 if (NMD.getName().startswith("llvm.dbg.")) 732 AssertDI(NMD.getName() == "llvm.dbg.cu", 733 "unrecognized named metadata node in the llvm.dbg namespace", 734 &NMD); 735 for (const MDNode *MD : NMD.operands()) { 736 if (NMD.getName() == "llvm.dbg.cu") 737 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 738 739 if (!MD) 740 continue; 741 742 visitMDNode(*MD); 743 } 744 } 745 746 void Verifier::visitMDNode(const MDNode &MD) { 747 // Only visit each node once. Metadata can be mutually recursive, so this 748 // avoids infinite recursion here, as well as being an optimization. 749 if (!MDNodes.insert(&MD).second) 750 return; 751 752 switch (MD.getMetadataID()) { 753 default: 754 llvm_unreachable("Invalid MDNode subclass"); 755 case Metadata::MDTupleKind: 756 break; 757 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 758 case Metadata::CLASS##Kind: \ 759 visit##CLASS(cast<CLASS>(MD)); \ 760 break; 761 #include "llvm/IR/Metadata.def" 762 } 763 764 for (const Metadata *Op : MD.operands()) { 765 if (!Op) 766 continue; 767 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 768 &MD, Op); 769 if (auto *N = dyn_cast<MDNode>(Op)) { 770 visitMDNode(*N); 771 continue; 772 } 773 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 774 visitValueAsMetadata(*V, nullptr); 775 continue; 776 } 777 } 778 779 // Check these last, so we diagnose problems in operands first. 780 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 781 Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 782 } 783 784 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 785 Assert(MD.getValue(), "Expected valid value", &MD); 786 Assert(!MD.getValue()->getType()->isMetadataTy(), 787 "Unexpected metadata round-trip through values", &MD, MD.getValue()); 788 789 auto *L = dyn_cast<LocalAsMetadata>(&MD); 790 if (!L) 791 return; 792 793 Assert(F, "function-local metadata used outside a function", L); 794 795 // If this was an instruction, bb, or argument, verify that it is in the 796 // function that we expect. 797 Function *ActualF = nullptr; 798 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 799 Assert(I->getParent(), "function-local metadata not in basic block", L, I); 800 ActualF = I->getParent()->getParent(); 801 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 802 ActualF = BB->getParent(); 803 else if (Argument *A = dyn_cast<Argument>(L->getValue())) 804 ActualF = A->getParent(); 805 assert(ActualF && "Unimplemented function local metadata case!"); 806 807 Assert(ActualF == F, "function-local metadata used in wrong function", L); 808 } 809 810 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 811 Metadata *MD = MDV.getMetadata(); 812 if (auto *N = dyn_cast<MDNode>(MD)) { 813 visitMDNode(*N); 814 return; 815 } 816 817 // Only visit each node once. Metadata can be mutually recursive, so this 818 // avoids infinite recursion here, as well as being an optimization. 819 if (!MDNodes.insert(MD).second) 820 return; 821 822 if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 823 visitValueAsMetadata(*V, F); 824 } 825 826 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); } 827 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); } 828 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); } 829 830 template <class Ty> 831 static bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) { 832 for (Metadata *MD : N.operands()) { 833 if (MD) { 834 if (!isa<Ty>(MD)) 835 return false; 836 } else { 837 if (!AllowNull) 838 return false; 839 } 840 } 841 return true; 842 } 843 844 template <class Ty> static bool isValidMetadataArray(const MDTuple &N) { 845 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false); 846 } 847 848 template <class Ty> static bool isValidMetadataNullArray(const MDTuple &N) { 849 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true); 850 } 851 852 void Verifier::visitDILocation(const DILocation &N) { 853 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 854 "location requires a valid scope", &N, N.getRawScope()); 855 if (auto *IA = N.getRawInlinedAt()) 856 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 857 } 858 859 void Verifier::visitGenericDINode(const GenericDINode &N) { 860 AssertDI(N.getTag(), "invalid tag", &N); 861 } 862 863 void Verifier::visitDIScope(const DIScope &N) { 864 if (auto *F = N.getRawFile()) 865 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 866 } 867 868 void Verifier::visitDISubrange(const DISubrange &N) { 869 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 870 AssertDI(N.getCount() >= -1, "invalid subrange count", &N); 871 } 872 873 void Verifier::visitDIEnumerator(const DIEnumerator &N) { 874 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 875 } 876 877 void Verifier::visitDIBasicType(const DIBasicType &N) { 878 AssertDI(N.getTag() == dwarf::DW_TAG_base_type || 879 N.getTag() == dwarf::DW_TAG_unspecified_type, 880 "invalid tag", &N); 881 } 882 883 void Verifier::visitDIDerivedType(const DIDerivedType &N) { 884 // Common scope checks. 885 visitDIScope(N); 886 887 AssertDI(N.getTag() == dwarf::DW_TAG_typedef || 888 N.getTag() == dwarf::DW_TAG_pointer_type || 889 N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 890 N.getTag() == dwarf::DW_TAG_reference_type || 891 N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 892 N.getTag() == dwarf::DW_TAG_const_type || 893 N.getTag() == dwarf::DW_TAG_volatile_type || 894 N.getTag() == dwarf::DW_TAG_restrict_type || 895 N.getTag() == dwarf::DW_TAG_atomic_type || 896 N.getTag() == dwarf::DW_TAG_member || 897 N.getTag() == dwarf::DW_TAG_inheritance || 898 N.getTag() == dwarf::DW_TAG_friend, 899 "invalid tag", &N); 900 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 901 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N, 902 N.getRawExtraData()); 903 } 904 905 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 906 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 907 N.getRawBaseType()); 908 } 909 910 static bool hasConflictingReferenceFlags(unsigned Flags) { 911 return (Flags & DINode::FlagLValueReference) && 912 (Flags & DINode::FlagRValueReference); 913 } 914 915 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 916 auto *Params = dyn_cast<MDTuple>(&RawParams); 917 AssertDI(Params, "invalid template params", &N, &RawParams); 918 for (Metadata *Op : Params->operands()) { 919 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter", 920 &N, Params, Op); 921 } 922 } 923 924 void Verifier::visitDICompositeType(const DICompositeType &N) { 925 // Common scope checks. 926 visitDIScope(N); 927 928 AssertDI(N.getTag() == dwarf::DW_TAG_array_type || 929 N.getTag() == dwarf::DW_TAG_structure_type || 930 N.getTag() == dwarf::DW_TAG_union_type || 931 N.getTag() == dwarf::DW_TAG_enumeration_type || 932 N.getTag() == dwarf::DW_TAG_class_type, 933 "invalid tag", &N); 934 935 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 936 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 937 N.getRawBaseType()); 938 939 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 940 "invalid composite elements", &N, N.getRawElements()); 941 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N, 942 N.getRawVTableHolder()); 943 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 944 "invalid reference flags", &N); 945 if (auto *Params = N.getRawTemplateParams()) 946 visitTemplateParams(N, *Params); 947 948 if (N.getTag() == dwarf::DW_TAG_class_type || 949 N.getTag() == dwarf::DW_TAG_union_type) { 950 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(), 951 "class/union requires a filename", &N, N.getFile()); 952 } 953 } 954 955 void Verifier::visitDISubroutineType(const DISubroutineType &N) { 956 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 957 if (auto *Types = N.getRawTypeArray()) { 958 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 959 for (Metadata *Ty : N.getTypeArray()->operands()) { 960 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty); 961 } 962 } 963 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 964 "invalid reference flags", &N); 965 } 966 967 void Verifier::visitDIFile(const DIFile &N) { 968 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 969 } 970 971 void Verifier::visitDICompileUnit(const DICompileUnit &N) { 972 AssertDI(N.isDistinct(), "compile units must be distinct", &N); 973 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 974 975 // Don't bother verifying the compilation directory or producer string 976 // as those could be empty. 977 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 978 N.getRawFile()); 979 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N, 980 N.getFile()); 981 982 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind), 983 "invalid emission kind", &N); 984 985 if (auto *Array = N.getRawEnumTypes()) { 986 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array); 987 for (Metadata *Op : N.getEnumTypes()->operands()) { 988 auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 989 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 990 "invalid enum type", &N, N.getEnumTypes(), Op); 991 } 992 } 993 if (auto *Array = N.getRawRetainedTypes()) { 994 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 995 for (Metadata *Op : N.getRetainedTypes()->operands()) { 996 AssertDI(Op && (isa<DIType>(Op) || 997 (isa<DISubprogram>(Op) && 998 !cast<DISubprogram>(Op)->isDefinition())), 999 "invalid retained type", &N, Op); 1000 } 1001 } 1002 if (auto *Array = N.getRawGlobalVariables()) { 1003 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 1004 for (Metadata *Op : N.getGlobalVariables()->operands()) { 1005 AssertDI(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", 1006 &N, Op); 1007 } 1008 } 1009 if (auto *Array = N.getRawImportedEntities()) { 1010 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 1011 for (Metadata *Op : N.getImportedEntities()->operands()) { 1012 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", 1013 &N, Op); 1014 } 1015 } 1016 if (auto *Array = N.getRawMacros()) { 1017 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1018 for (Metadata *Op : N.getMacros()->operands()) { 1019 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1020 } 1021 } 1022 CUVisited.insert(&N); 1023 } 1024 1025 void Verifier::visitDISubprogram(const DISubprogram &N) { 1026 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 1027 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1028 if (auto *F = N.getRawFile()) 1029 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1030 if (auto *T = N.getRawType()) 1031 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 1032 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N, 1033 N.getRawContainingType()); 1034 if (auto *Params = N.getRawTemplateParams()) 1035 visitTemplateParams(N, *Params); 1036 if (auto *S = N.getRawDeclaration()) 1037 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 1038 "invalid subprogram declaration", &N, S); 1039 if (auto *RawVars = N.getRawVariables()) { 1040 auto *Vars = dyn_cast<MDTuple>(RawVars); 1041 AssertDI(Vars, "invalid variable list", &N, RawVars); 1042 for (Metadata *Op : Vars->operands()) { 1043 AssertDI(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, 1044 Vars, Op); 1045 } 1046 } 1047 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1048 "invalid reference flags", &N); 1049 1050 auto *Unit = N.getRawUnit(); 1051 if (N.isDefinition()) { 1052 // Subprogram definitions (not part of the type hierarchy). 1053 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N); 1054 AssertDI(Unit, "subprogram definitions must have a compile unit", &N); 1055 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit); 1056 } else { 1057 // Subprogram declarations (part of the type hierarchy). 1058 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N); 1059 } 1060 } 1061 1062 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 1063 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 1064 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1065 "invalid local scope", &N, N.getRawScope()); 1066 } 1067 1068 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 1069 visitDILexicalBlockBase(N); 1070 1071 AssertDI(N.getLine() || !N.getColumn(), 1072 "cannot have column info without line info", &N); 1073 } 1074 1075 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 1076 visitDILexicalBlockBase(N); 1077 } 1078 1079 void Verifier::visitDINamespace(const DINamespace &N) { 1080 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 1081 if (auto *S = N.getRawScope()) 1082 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1083 } 1084 1085 void Verifier::visitDIMacro(const DIMacro &N) { 1086 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define || 1087 N.getMacinfoType() == dwarf::DW_MACINFO_undef, 1088 "invalid macinfo type", &N); 1089 AssertDI(!N.getName().empty(), "anonymous macro", &N); 1090 if (!N.getValue().empty()) { 1091 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1092 } 1093 } 1094 1095 void Verifier::visitDIMacroFile(const DIMacroFile &N) { 1096 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1097 "invalid macinfo type", &N); 1098 if (auto *F = N.getRawFile()) 1099 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1100 1101 if (auto *Array = N.getRawElements()) { 1102 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1103 for (Metadata *Op : N.getElements()->operands()) { 1104 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1105 } 1106 } 1107 } 1108 1109 void Verifier::visitDIModule(const DIModule &N) { 1110 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1111 AssertDI(!N.getName().empty(), "anonymous module", &N); 1112 } 1113 1114 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1115 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1116 } 1117 1118 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1119 visitDITemplateParameter(N); 1120 1121 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1122 &N); 1123 } 1124 1125 void Verifier::visitDITemplateValueParameter( 1126 const DITemplateValueParameter &N) { 1127 visitDITemplateParameter(N); 1128 1129 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1130 N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1131 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1132 "invalid tag", &N); 1133 } 1134 1135 void Verifier::visitDIVariable(const DIVariable &N) { 1136 if (auto *S = N.getRawScope()) 1137 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1138 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1139 if (auto *F = N.getRawFile()) 1140 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1141 } 1142 1143 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1144 // Checks common to all variables. 1145 visitDIVariable(N); 1146 1147 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1148 AssertDI(!N.getName().empty(), "missing global variable name", &N); 1149 if (auto *V = N.getRawExpr()) 1150 AssertDI(isa<DIExpression>(V), "invalid expression location", &N, V); 1151 if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1152 AssertDI(isa<DIDerivedType>(Member), 1153 "invalid static data member declaration", &N, Member); 1154 } 1155 } 1156 1157 void Verifier::visitDILocalVariable(const DILocalVariable &N) { 1158 // Checks common to all variables. 1159 visitDIVariable(N); 1160 1161 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1162 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1163 "local variable requires a valid scope", &N, N.getRawScope()); 1164 } 1165 1166 void Verifier::visitDIExpression(const DIExpression &N) { 1167 AssertDI(N.isValid(), "invalid expression", &N); 1168 } 1169 1170 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1171 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1172 if (auto *T = N.getRawType()) 1173 AssertDI(isType(T), "invalid type ref", &N, T); 1174 if (auto *F = N.getRawFile()) 1175 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1176 } 1177 1178 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1179 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module || 1180 N.getTag() == dwarf::DW_TAG_imported_declaration, 1181 "invalid tag", &N); 1182 if (auto *S = N.getRawScope()) 1183 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1184 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N, 1185 N.getRawEntity()); 1186 } 1187 1188 void Verifier::visitComdat(const Comdat &C) { 1189 // The Module is invalid if the GlobalValue has private linkage. Entities 1190 // with private linkage don't have entries in the symbol table. 1191 if (const GlobalValue *GV = M.getNamedValue(C.getName())) 1192 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage", 1193 GV); 1194 } 1195 1196 void Verifier::visitModuleIdents(const Module &M) { 1197 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1198 if (!Idents) 1199 return; 1200 1201 // llvm.ident takes a list of metadata entry. Each entry has only one string. 1202 // Scan each llvm.ident entry and make sure that this requirement is met. 1203 for (const MDNode *N : Idents->operands()) { 1204 Assert(N->getNumOperands() == 1, 1205 "incorrect number of operands in llvm.ident metadata", N); 1206 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1207 ("invalid value for llvm.ident metadata entry operand" 1208 "(the operand should be a string)"), 1209 N->getOperand(0)); 1210 } 1211 } 1212 1213 void Verifier::visitModuleFlags(const Module &M) { 1214 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1215 if (!Flags) return; 1216 1217 // Scan each flag, and track the flags and requirements. 1218 DenseMap<const MDString*, const MDNode*> SeenIDs; 1219 SmallVector<const MDNode*, 16> Requirements; 1220 for (const MDNode *MDN : Flags->operands()) 1221 visitModuleFlag(MDN, SeenIDs, Requirements); 1222 1223 // Validate that the requirements in the module are valid. 1224 for (const MDNode *Requirement : Requirements) { 1225 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1226 const Metadata *ReqValue = Requirement->getOperand(1); 1227 1228 const MDNode *Op = SeenIDs.lookup(Flag); 1229 if (!Op) { 1230 CheckFailed("invalid requirement on flag, flag is not present in module", 1231 Flag); 1232 continue; 1233 } 1234 1235 if (Op->getOperand(2) != ReqValue) { 1236 CheckFailed(("invalid requirement on flag, " 1237 "flag does not have the required value"), 1238 Flag); 1239 continue; 1240 } 1241 } 1242 } 1243 1244 void 1245 Verifier::visitModuleFlag(const MDNode *Op, 1246 DenseMap<const MDString *, const MDNode *> &SeenIDs, 1247 SmallVectorImpl<const MDNode *> &Requirements) { 1248 // Each module flag should have three arguments, the merge behavior (a 1249 // constant int), the flag ID (an MDString), and the value. 1250 Assert(Op->getNumOperands() == 3, 1251 "incorrect number of operands in module flag", Op); 1252 Module::ModFlagBehavior MFB; 1253 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1254 Assert( 1255 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1256 "invalid behavior operand in module flag (expected constant integer)", 1257 Op->getOperand(0)); 1258 Assert(false, 1259 "invalid behavior operand in module flag (unexpected constant)", 1260 Op->getOperand(0)); 1261 } 1262 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1263 Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1264 Op->getOperand(1)); 1265 1266 // Sanity check the values for behaviors with additional requirements. 1267 switch (MFB) { 1268 case Module::Error: 1269 case Module::Warning: 1270 case Module::Override: 1271 // These behavior types accept any value. 1272 break; 1273 1274 case Module::Require: { 1275 // The value should itself be an MDNode with two operands, a flag ID (an 1276 // MDString), and a value. 1277 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1278 Assert(Value && Value->getNumOperands() == 2, 1279 "invalid value for 'require' module flag (expected metadata pair)", 1280 Op->getOperand(2)); 1281 Assert(isa<MDString>(Value->getOperand(0)), 1282 ("invalid value for 'require' module flag " 1283 "(first value operand should be a string)"), 1284 Value->getOperand(0)); 1285 1286 // Append it to the list of requirements, to check once all module flags are 1287 // scanned. 1288 Requirements.push_back(Value); 1289 break; 1290 } 1291 1292 case Module::Append: 1293 case Module::AppendUnique: { 1294 // These behavior types require the operand be an MDNode. 1295 Assert(isa<MDNode>(Op->getOperand(2)), 1296 "invalid value for 'append'-type module flag " 1297 "(expected a metadata node)", 1298 Op->getOperand(2)); 1299 break; 1300 } 1301 } 1302 1303 // Unless this is a "requires" flag, check the ID is unique. 1304 if (MFB != Module::Require) { 1305 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1306 Assert(Inserted, 1307 "module flag identifiers must be unique (or of 'require' type)", ID); 1308 } 1309 } 1310 1311 void Verifier::verifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 1312 bool isFunction, const Value *V) { 1313 unsigned Slot = ~0U; 1314 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I) 1315 if (Attrs.getSlotIndex(I) == Idx) { 1316 Slot = I; 1317 break; 1318 } 1319 1320 assert(Slot != ~0U && "Attribute set inconsistency!"); 1321 1322 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot); 1323 I != E; ++I) { 1324 if (I->isStringAttribute()) 1325 continue; 1326 1327 if (I->getKindAsEnum() == Attribute::NoReturn || 1328 I->getKindAsEnum() == Attribute::NoUnwind || 1329 I->getKindAsEnum() == Attribute::NoInline || 1330 I->getKindAsEnum() == Attribute::AlwaysInline || 1331 I->getKindAsEnum() == Attribute::OptimizeForSize || 1332 I->getKindAsEnum() == Attribute::StackProtect || 1333 I->getKindAsEnum() == Attribute::StackProtectReq || 1334 I->getKindAsEnum() == Attribute::StackProtectStrong || 1335 I->getKindAsEnum() == Attribute::SafeStack || 1336 I->getKindAsEnum() == Attribute::NoRedZone || 1337 I->getKindAsEnum() == Attribute::NoImplicitFloat || 1338 I->getKindAsEnum() == Attribute::Naked || 1339 I->getKindAsEnum() == Attribute::InlineHint || 1340 I->getKindAsEnum() == Attribute::StackAlignment || 1341 I->getKindAsEnum() == Attribute::UWTable || 1342 I->getKindAsEnum() == Attribute::NonLazyBind || 1343 I->getKindAsEnum() == Attribute::ReturnsTwice || 1344 I->getKindAsEnum() == Attribute::SanitizeAddress || 1345 I->getKindAsEnum() == Attribute::SanitizeThread || 1346 I->getKindAsEnum() == Attribute::SanitizeMemory || 1347 I->getKindAsEnum() == Attribute::MinSize || 1348 I->getKindAsEnum() == Attribute::NoDuplicate || 1349 I->getKindAsEnum() == Attribute::Builtin || 1350 I->getKindAsEnum() == Attribute::NoBuiltin || 1351 I->getKindAsEnum() == Attribute::Cold || 1352 I->getKindAsEnum() == Attribute::OptimizeNone || 1353 I->getKindAsEnum() == Attribute::JumpTable || 1354 I->getKindAsEnum() == Attribute::Convergent || 1355 I->getKindAsEnum() == Attribute::ArgMemOnly || 1356 I->getKindAsEnum() == Attribute::NoRecurse || 1357 I->getKindAsEnum() == Attribute::InaccessibleMemOnly || 1358 I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly || 1359 I->getKindAsEnum() == Attribute::AllocSize) { 1360 if (!isFunction) { 1361 CheckFailed("Attribute '" + I->getAsString() + 1362 "' only applies to functions!", V); 1363 return; 1364 } 1365 } else if (I->getKindAsEnum() == Attribute::ReadOnly || 1366 I->getKindAsEnum() == Attribute::WriteOnly || 1367 I->getKindAsEnum() == Attribute::ReadNone) { 1368 if (Idx == 0) { 1369 CheckFailed("Attribute '" + I->getAsString() + 1370 "' does not apply to function returns"); 1371 return; 1372 } 1373 } else if (isFunction) { 1374 CheckFailed("Attribute '" + I->getAsString() + 1375 "' does not apply to functions!", V); 1376 return; 1377 } 1378 } 1379 } 1380 1381 // VerifyParameterAttrs - Check the given attributes for an argument or return 1382 // value of the specified type. The value V is printed in error messages. 1383 void Verifier::verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 1384 bool isReturnValue, const Value *V) { 1385 if (!Attrs.hasAttributes(Idx)) 1386 return; 1387 1388 verifyAttributeTypes(Attrs, Idx, false, V); 1389 1390 if (isReturnValue) 1391 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1392 !Attrs.hasAttribute(Idx, Attribute::Nest) && 1393 !Attrs.hasAttribute(Idx, Attribute::StructRet) && 1394 !Attrs.hasAttribute(Idx, Attribute::NoCapture) && 1395 !Attrs.hasAttribute(Idx, Attribute::Returned) && 1396 !Attrs.hasAttribute(Idx, Attribute::InAlloca) && 1397 !Attrs.hasAttribute(Idx, Attribute::SwiftSelf) && 1398 !Attrs.hasAttribute(Idx, Attribute::SwiftError), 1399 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', " 1400 "'returned', 'swiftself', and 'swifterror' do not apply to return " 1401 "values!", 1402 V); 1403 1404 // Check for mutually incompatible attributes. Only inreg is compatible with 1405 // sret. 1406 unsigned AttrCount = 0; 1407 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal); 1408 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca); 1409 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) || 1410 Attrs.hasAttribute(Idx, Attribute::InReg); 1411 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest); 1412 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', " 1413 "and 'sret' are incompatible!", 1414 V); 1415 1416 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) && 1417 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1418 "Attributes " 1419 "'inalloca and readonly' are incompatible!", 1420 V); 1421 1422 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) && 1423 Attrs.hasAttribute(Idx, Attribute::Returned)), 1424 "Attributes " 1425 "'sret and returned' are incompatible!", 1426 V); 1427 1428 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) && 1429 Attrs.hasAttribute(Idx, Attribute::SExt)), 1430 "Attributes " 1431 "'zeroext and signext' are incompatible!", 1432 V); 1433 1434 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 1435 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1436 "Attributes " 1437 "'readnone and readonly' are incompatible!", 1438 V); 1439 1440 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 1441 Attrs.hasAttribute(Idx, Attribute::WriteOnly)), 1442 "Attributes " 1443 "'readnone and writeonly' are incompatible!", 1444 V); 1445 1446 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadOnly) && 1447 Attrs.hasAttribute(Idx, Attribute::WriteOnly)), 1448 "Attributes " 1449 "'readonly and writeonly' are incompatible!", 1450 V); 1451 1452 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) && 1453 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), 1454 "Attributes " 1455 "'noinline and alwaysinline' are incompatible!", 1456 V); 1457 1458 Assert( 1459 !AttrBuilder(Attrs, Idx).overlaps(AttributeFuncs::typeIncompatible(Ty)), 1460 "Wrong types for attribute: " + 1461 AttributeSet::get(Context, Idx, AttributeFuncs::typeIncompatible(Ty)) 1462 .getAsString(Idx), 1463 V); 1464 1465 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1466 SmallPtrSet<Type*, 4> Visited; 1467 if (!PTy->getElementType()->isSized(&Visited)) { 1468 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1469 !Attrs.hasAttribute(Idx, Attribute::InAlloca), 1470 "Attributes 'byval' and 'inalloca' do not support unsized types!", 1471 V); 1472 } 1473 if (!isa<PointerType>(PTy->getElementType())) 1474 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError), 1475 "Attribute 'swifterror' only applies to parameters " 1476 "with pointer to pointer type!", 1477 V); 1478 } else { 1479 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal), 1480 "Attribute 'byval' only applies to parameters with pointer type!", 1481 V); 1482 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError), 1483 "Attribute 'swifterror' only applies to parameters " 1484 "with pointer type!", 1485 V); 1486 } 1487 } 1488 1489 // Check parameter attributes against a function type. 1490 // The value V is printed in error messages. 1491 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 1492 const Value *V) { 1493 if (Attrs.isEmpty()) 1494 return; 1495 1496 bool SawNest = false; 1497 bool SawReturned = false; 1498 bool SawSRet = false; 1499 bool SawSwiftSelf = false; 1500 bool SawSwiftError = false; 1501 1502 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 1503 unsigned Idx = Attrs.getSlotIndex(i); 1504 1505 Type *Ty; 1506 if (Idx == 0) 1507 Ty = FT->getReturnType(); 1508 else if (Idx-1 < FT->getNumParams()) 1509 Ty = FT->getParamType(Idx-1); 1510 else 1511 break; // VarArgs attributes, verified elsewhere. 1512 1513 verifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V); 1514 1515 if (Idx == 0) 1516 continue; 1517 1518 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 1519 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1520 SawNest = true; 1521 } 1522 1523 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 1524 Assert(!SawReturned, "More than one parameter has attribute returned!", 1525 V); 1526 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1527 "Incompatible " 1528 "argument and return types for 'returned' attribute", 1529 V); 1530 SawReturned = true; 1531 } 1532 1533 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) { 1534 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1535 Assert(Idx == 1 || Idx == 2, 1536 "Attribute 'sret' is not on first or second parameter!", V); 1537 SawSRet = true; 1538 } 1539 1540 if (Attrs.hasAttribute(Idx, Attribute::SwiftSelf)) { 1541 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 1542 SawSwiftSelf = true; 1543 } 1544 1545 if (Attrs.hasAttribute(Idx, Attribute::SwiftError)) { 1546 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 1547 V); 1548 SawSwiftError = true; 1549 } 1550 1551 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) { 1552 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!", 1553 V); 1554 } 1555 } 1556 1557 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex)) 1558 return; 1559 1560 verifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V); 1561 1562 Assert( 1563 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1564 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)), 1565 "Attributes 'readnone and readonly' are incompatible!", V); 1566 1567 Assert( 1568 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1569 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::WriteOnly)), 1570 "Attributes 'readnone and writeonly' are incompatible!", V); 1571 1572 Assert( 1573 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly) && 1574 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::WriteOnly)), 1575 "Attributes 'readonly and writeonly' are incompatible!", V); 1576 1577 Assert( 1578 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1579 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1580 Attribute::InaccessibleMemOrArgMemOnly)), 1581 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V); 1582 1583 Assert( 1584 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1585 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1586 Attribute::InaccessibleMemOnly)), 1587 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 1588 1589 Assert( 1590 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) && 1591 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1592 Attribute::AlwaysInline)), 1593 "Attributes 'noinline and alwaysinline' are incompatible!", V); 1594 1595 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1596 Attribute::OptimizeNone)) { 1597 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline), 1598 "Attribute 'optnone' requires 'noinline'!", V); 1599 1600 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 1601 Attribute::OptimizeForSize), 1602 "Attributes 'optsize and optnone' are incompatible!", V); 1603 1604 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize), 1605 "Attributes 'minsize and optnone' are incompatible!", V); 1606 } 1607 1608 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1609 Attribute::JumpTable)) { 1610 const GlobalValue *GV = cast<GlobalValue>(V); 1611 Assert(GV->hasGlobalUnnamedAddr(), 1612 "Attribute 'jumptable' requires 'unnamed_addr'", V); 1613 } 1614 1615 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::AllocSize)) { 1616 std::pair<unsigned, Optional<unsigned>> Args = 1617 Attrs.getAllocSizeArgs(AttributeSet::FunctionIndex); 1618 1619 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 1620 if (ParamNo >= FT->getNumParams()) { 1621 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 1622 return false; 1623 } 1624 1625 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 1626 CheckFailed("'allocsize' " + Name + 1627 " argument must refer to an integer parameter", 1628 V); 1629 return false; 1630 } 1631 1632 return true; 1633 }; 1634 1635 if (!CheckParam("element size", Args.first)) 1636 return; 1637 1638 if (Args.second && !CheckParam("number of elements", *Args.second)) 1639 return; 1640 } 1641 } 1642 1643 void Verifier::verifyFunctionMetadata( 1644 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 1645 for (const auto &Pair : MDs) { 1646 if (Pair.first == LLVMContext::MD_prof) { 1647 MDNode *MD = Pair.second; 1648 Assert(MD->getNumOperands() == 2, 1649 "!prof annotations should have exactly 2 operands", MD); 1650 1651 // Check first operand. 1652 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 1653 MD); 1654 Assert(isa<MDString>(MD->getOperand(0)), 1655 "expected string with name of the !prof annotation", MD); 1656 MDString *MDS = cast<MDString>(MD->getOperand(0)); 1657 StringRef ProfName = MDS->getString(); 1658 Assert(ProfName.equals("function_entry_count"), 1659 "first operand should be 'function_entry_count'", MD); 1660 1661 // Check second operand. 1662 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 1663 MD); 1664 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 1665 "expected integer argument to function_entry_count", MD); 1666 } 1667 } 1668 } 1669 1670 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 1671 if (!ConstantExprVisited.insert(EntryC).second) 1672 return; 1673 1674 SmallVector<const Constant *, 16> Stack; 1675 Stack.push_back(EntryC); 1676 1677 while (!Stack.empty()) { 1678 const Constant *C = Stack.pop_back_val(); 1679 1680 // Check this constant expression. 1681 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 1682 visitConstantExpr(CE); 1683 1684 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 1685 // Global Values get visited separately, but we do need to make sure 1686 // that the global value is in the correct module 1687 Assert(GV->getParent() == &M, "Referencing global in another module!", 1688 EntryC, &M, GV, GV->getParent()); 1689 continue; 1690 } 1691 1692 // Visit all sub-expressions. 1693 for (const Use &U : C->operands()) { 1694 const auto *OpC = dyn_cast<Constant>(U); 1695 if (!OpC) 1696 continue; 1697 if (!ConstantExprVisited.insert(OpC).second) 1698 continue; 1699 Stack.push_back(OpC); 1700 } 1701 } 1702 } 1703 1704 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 1705 if (CE->getOpcode() == Instruction::BitCast) 1706 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 1707 CE->getType()), 1708 "Invalid bitcast", CE); 1709 1710 if (CE->getOpcode() == Instruction::IntToPtr || 1711 CE->getOpcode() == Instruction::PtrToInt) { 1712 auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr 1713 ? CE->getType() 1714 : CE->getOperand(0)->getType(); 1715 StringRef Msg = CE->getOpcode() == Instruction::IntToPtr 1716 ? "inttoptr not supported for non-integral pointers" 1717 : "ptrtoint not supported for non-integral pointers"; 1718 Assert( 1719 !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())), 1720 Msg); 1721 } 1722 } 1723 1724 bool Verifier::verifyAttributeCount(AttributeSet Attrs, unsigned Params) { 1725 if (Attrs.getNumSlots() == 0) 1726 return true; 1727 1728 unsigned LastSlot = Attrs.getNumSlots() - 1; 1729 unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 1730 if (LastIndex <= Params 1731 || (LastIndex == AttributeSet::FunctionIndex 1732 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 1733 return true; 1734 1735 return false; 1736 } 1737 1738 /// Verify that statepoint intrinsic is well formed. 1739 void Verifier::verifyStatepoint(ImmutableCallSite CS) { 1740 assert(CS.getCalledFunction() && 1741 CS.getCalledFunction()->getIntrinsicID() == 1742 Intrinsic::experimental_gc_statepoint); 1743 1744 const Instruction &CI = *CS.getInstruction(); 1745 1746 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() && 1747 !CS.onlyAccessesArgMemory(), 1748 "gc.statepoint must read and write all memory to preserve " 1749 "reordering restrictions required by safepoint semantics", 1750 &CI); 1751 1752 const Value *IDV = CS.getArgument(0); 1753 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer", 1754 &CI); 1755 1756 const Value *NumPatchBytesV = CS.getArgument(1); 1757 Assert(isa<ConstantInt>(NumPatchBytesV), 1758 "gc.statepoint number of patchable bytes must be a constant integer", 1759 &CI); 1760 const int64_t NumPatchBytes = 1761 cast<ConstantInt>(NumPatchBytesV)->getSExtValue(); 1762 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 1763 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be " 1764 "positive", 1765 &CI); 1766 1767 const Value *Target = CS.getArgument(2); 1768 auto *PT = dyn_cast<PointerType>(Target->getType()); 1769 Assert(PT && PT->getElementType()->isFunctionTy(), 1770 "gc.statepoint callee must be of function pointer type", &CI, Target); 1771 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 1772 1773 const Value *NumCallArgsV = CS.getArgument(3); 1774 Assert(isa<ConstantInt>(NumCallArgsV), 1775 "gc.statepoint number of arguments to underlying call " 1776 "must be constant integer", 1777 &CI); 1778 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue(); 1779 Assert(NumCallArgs >= 0, 1780 "gc.statepoint number of arguments to underlying call " 1781 "must be positive", 1782 &CI); 1783 const int NumParams = (int)TargetFuncType->getNumParams(); 1784 if (TargetFuncType->isVarArg()) { 1785 Assert(NumCallArgs >= NumParams, 1786 "gc.statepoint mismatch in number of vararg call args", &CI); 1787 1788 // TODO: Remove this limitation 1789 Assert(TargetFuncType->getReturnType()->isVoidTy(), 1790 "gc.statepoint doesn't support wrapping non-void " 1791 "vararg functions yet", 1792 &CI); 1793 } else 1794 Assert(NumCallArgs == NumParams, 1795 "gc.statepoint mismatch in number of call args", &CI); 1796 1797 const Value *FlagsV = CS.getArgument(4); 1798 Assert(isa<ConstantInt>(FlagsV), 1799 "gc.statepoint flags must be constant integer", &CI); 1800 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue(); 1801 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 1802 "unknown flag used in gc.statepoint flags argument", &CI); 1803 1804 // Verify that the types of the call parameter arguments match 1805 // the type of the wrapped callee. 1806 for (int i = 0; i < NumParams; i++) { 1807 Type *ParamType = TargetFuncType->getParamType(i); 1808 Type *ArgType = CS.getArgument(5 + i)->getType(); 1809 Assert(ArgType == ParamType, 1810 "gc.statepoint call argument does not match wrapped " 1811 "function type", 1812 &CI); 1813 } 1814 1815 const int EndCallArgsInx = 4 + NumCallArgs; 1816 1817 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1); 1818 Assert(isa<ConstantInt>(NumTransitionArgsV), 1819 "gc.statepoint number of transition arguments " 1820 "must be constant integer", 1821 &CI); 1822 const int NumTransitionArgs = 1823 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 1824 Assert(NumTransitionArgs >= 0, 1825 "gc.statepoint number of transition arguments must be positive", &CI); 1826 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 1827 1828 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1); 1829 Assert(isa<ConstantInt>(NumDeoptArgsV), 1830 "gc.statepoint number of deoptimization arguments " 1831 "must be constant integer", 1832 &CI); 1833 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 1834 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments " 1835 "must be positive", 1836 &CI); 1837 1838 const int ExpectedNumArgs = 1839 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs; 1840 Assert(ExpectedNumArgs <= (int)CS.arg_size(), 1841 "gc.statepoint too few arguments according to length fields", &CI); 1842 1843 // Check that the only uses of this gc.statepoint are gc.result or 1844 // gc.relocate calls which are tied to this statepoint and thus part 1845 // of the same statepoint sequence 1846 for (const User *U : CI.users()) { 1847 const CallInst *Call = dyn_cast<const CallInst>(U); 1848 Assert(Call, "illegal use of statepoint token", &CI, U); 1849 if (!Call) continue; 1850 Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call), 1851 "gc.result or gc.relocate are the only value uses " 1852 "of a gc.statepoint", 1853 &CI, U); 1854 if (isa<GCResultInst>(Call)) { 1855 Assert(Call->getArgOperand(0) == &CI, 1856 "gc.result connected to wrong gc.statepoint", &CI, Call); 1857 } else if (isa<GCRelocateInst>(Call)) { 1858 Assert(Call->getArgOperand(0) == &CI, 1859 "gc.relocate connected to wrong gc.statepoint", &CI, Call); 1860 } 1861 } 1862 1863 // Note: It is legal for a single derived pointer to be listed multiple 1864 // times. It's non-optimal, but it is legal. It can also happen after 1865 // insertion if we strip a bitcast away. 1866 // Note: It is really tempting to check that each base is relocated and 1867 // that a derived pointer is never reused as a base pointer. This turns 1868 // out to be problematic since optimizations run after safepoint insertion 1869 // can recognize equality properties that the insertion logic doesn't know 1870 // about. See example statepoint.ll in the verifier subdirectory 1871 } 1872 1873 void Verifier::verifyFrameRecoverIndices() { 1874 for (auto &Counts : FrameEscapeInfo) { 1875 Function *F = Counts.first; 1876 unsigned EscapedObjectCount = Counts.second.first; 1877 unsigned MaxRecoveredIndex = Counts.second.second; 1878 Assert(MaxRecoveredIndex <= EscapedObjectCount, 1879 "all indices passed to llvm.localrecover must be less than the " 1880 "number of arguments passed ot llvm.localescape in the parent " 1881 "function", 1882 F); 1883 } 1884 } 1885 1886 static Instruction *getSuccPad(TerminatorInst *Terminator) { 1887 BasicBlock *UnwindDest; 1888 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 1889 UnwindDest = II->getUnwindDest(); 1890 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 1891 UnwindDest = CSI->getUnwindDest(); 1892 else 1893 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 1894 return UnwindDest->getFirstNonPHI(); 1895 } 1896 1897 void Verifier::verifySiblingFuncletUnwinds() { 1898 SmallPtrSet<Instruction *, 8> Visited; 1899 SmallPtrSet<Instruction *, 8> Active; 1900 for (const auto &Pair : SiblingFuncletInfo) { 1901 Instruction *PredPad = Pair.first; 1902 if (Visited.count(PredPad)) 1903 continue; 1904 Active.insert(PredPad); 1905 TerminatorInst *Terminator = Pair.second; 1906 do { 1907 Instruction *SuccPad = getSuccPad(Terminator); 1908 if (Active.count(SuccPad)) { 1909 // Found a cycle; report error 1910 Instruction *CyclePad = SuccPad; 1911 SmallVector<Instruction *, 8> CycleNodes; 1912 do { 1913 CycleNodes.push_back(CyclePad); 1914 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad]; 1915 if (CycleTerminator != CyclePad) 1916 CycleNodes.push_back(CycleTerminator); 1917 CyclePad = getSuccPad(CycleTerminator); 1918 } while (CyclePad != SuccPad); 1919 Assert(false, "EH pads can't handle each other's exceptions", 1920 ArrayRef<Instruction *>(CycleNodes)); 1921 } 1922 // Don't re-walk a node we've already checked 1923 if (!Visited.insert(SuccPad).second) 1924 break; 1925 // Walk to this successor if it has a map entry. 1926 PredPad = SuccPad; 1927 auto TermI = SiblingFuncletInfo.find(PredPad); 1928 if (TermI == SiblingFuncletInfo.end()) 1929 break; 1930 Terminator = TermI->second; 1931 Active.insert(PredPad); 1932 } while (true); 1933 // Each node only has one successor, so we've walked all the active 1934 // nodes' successors. 1935 Active.clear(); 1936 } 1937 } 1938 1939 // visitFunction - Verify that a function is ok. 1940 // 1941 void Verifier::visitFunction(const Function &F) { 1942 visitGlobalValue(F); 1943 1944 // Check function arguments. 1945 FunctionType *FT = F.getFunctionType(); 1946 unsigned NumArgs = F.arg_size(); 1947 1948 Assert(&Context == &F.getContext(), 1949 "Function context does not match Module context!", &F); 1950 1951 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 1952 Assert(FT->getNumParams() == NumArgs, 1953 "# formal arguments must match # of arguments for function type!", &F, 1954 FT); 1955 Assert(F.getReturnType()->isFirstClassType() || 1956 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 1957 "Functions cannot return aggregate values!", &F); 1958 1959 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 1960 "Invalid struct return type!", &F); 1961 1962 AttributeSet Attrs = F.getAttributes(); 1963 1964 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 1965 "Attribute after last parameter!", &F); 1966 1967 // Check function attributes. 1968 verifyFunctionAttrs(FT, Attrs, &F); 1969 1970 // On function declarations/definitions, we do not support the builtin 1971 // attribute. We do not check this in VerifyFunctionAttrs since that is 1972 // checking for Attributes that can/can not ever be on functions. 1973 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin), 1974 "Attribute 'builtin' can only be applied to a callsite.", &F); 1975 1976 // Check that this function meets the restrictions on this calling convention. 1977 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 1978 // restrictions can be lifted. 1979 switch (F.getCallingConv()) { 1980 default: 1981 case CallingConv::C: 1982 break; 1983 case CallingConv::Fast: 1984 case CallingConv::Cold: 1985 case CallingConv::Intel_OCL_BI: 1986 case CallingConv::PTX_Kernel: 1987 case CallingConv::PTX_Device: 1988 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 1989 "perfect forwarding!", 1990 &F); 1991 break; 1992 } 1993 1994 bool isLLVMdotName = F.getName().size() >= 5 && 1995 F.getName().substr(0, 5) == "llvm."; 1996 1997 // Check that the argument values match the function type for this function... 1998 unsigned i = 0; 1999 for (const Argument &Arg : F.args()) { 2000 Assert(Arg.getType() == FT->getParamType(i), 2001 "Argument value does not match function argument type!", &Arg, 2002 FT->getParamType(i)); 2003 Assert(Arg.getType()->isFirstClassType(), 2004 "Function arguments must have first-class types!", &Arg); 2005 if (!isLLVMdotName) { 2006 Assert(!Arg.getType()->isMetadataTy(), 2007 "Function takes metadata but isn't an intrinsic", &Arg, &F); 2008 Assert(!Arg.getType()->isTokenTy(), 2009 "Function takes token but isn't an intrinsic", &Arg, &F); 2010 } 2011 2012 // Check that swifterror argument is only used by loads and stores. 2013 if (Attrs.hasAttribute(i+1, Attribute::SwiftError)) { 2014 verifySwiftErrorValue(&Arg); 2015 } 2016 ++i; 2017 } 2018 2019 if (!isLLVMdotName) 2020 Assert(!F.getReturnType()->isTokenTy(), 2021 "Functions returns a token but isn't an intrinsic", &F); 2022 2023 // Get the function metadata attachments. 2024 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2025 F.getAllMetadata(MDs); 2026 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 2027 verifyFunctionMetadata(MDs); 2028 2029 // Check validity of the personality function 2030 if (F.hasPersonalityFn()) { 2031 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 2032 if (Per) 2033 Assert(Per->getParent() == F.getParent(), 2034 "Referencing personality function in another module!", 2035 &F, F.getParent(), Per, Per->getParent()); 2036 } 2037 2038 if (F.isMaterializable()) { 2039 // Function has a body somewhere we can't see. 2040 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 2041 MDs.empty() ? nullptr : MDs.front().second); 2042 } else if (F.isDeclaration()) { 2043 for (const auto &I : MDs) { 2044 AssertDI(I.first != LLVMContext::MD_dbg, 2045 "function declaration may not have a !dbg attachment", &F); 2046 Assert(I.first != LLVMContext::MD_prof, 2047 "function declaration may not have a !prof attachment", &F); 2048 2049 // Verify the metadata itself. 2050 visitMDNode(*I.second); 2051 } 2052 Assert(!F.hasPersonalityFn(), 2053 "Function declaration shouldn't have a personality routine", &F); 2054 } else { 2055 // Verify that this function (which has a body) is not named "llvm.*". It 2056 // is not legal to define intrinsics. 2057 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 2058 2059 // Check the entry node 2060 const BasicBlock *Entry = &F.getEntryBlock(); 2061 Assert(pred_empty(Entry), 2062 "Entry block to function must not have predecessors!", Entry); 2063 2064 // The address of the entry block cannot be taken, unless it is dead. 2065 if (Entry->hasAddressTaken()) { 2066 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 2067 "blockaddress may not be used with the entry block!", Entry); 2068 } 2069 2070 unsigned NumDebugAttachments = 0, NumProfAttachments = 0; 2071 // Visit metadata attachments. 2072 for (const auto &I : MDs) { 2073 // Verify that the attachment is legal. 2074 switch (I.first) { 2075 default: 2076 break; 2077 case LLVMContext::MD_dbg: 2078 ++NumDebugAttachments; 2079 AssertDI(NumDebugAttachments == 1, 2080 "function must have a single !dbg attachment", &F, I.second); 2081 AssertDI(isa<DISubprogram>(I.second), 2082 "function !dbg attachment must be a subprogram", &F, I.second); 2083 break; 2084 case LLVMContext::MD_prof: 2085 ++NumProfAttachments; 2086 Assert(NumProfAttachments == 1, 2087 "function must have a single !prof attachment", &F, I.second); 2088 break; 2089 } 2090 2091 // Verify the metadata itself. 2092 visitMDNode(*I.second); 2093 } 2094 } 2095 2096 // If this function is actually an intrinsic, verify that it is only used in 2097 // direct call/invokes, never having its "address taken". 2098 // Only do this if the module is materialized, otherwise we don't have all the 2099 // uses. 2100 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2101 const User *U; 2102 if (F.hasAddressTaken(&U)) 2103 Assert(false, "Invalid user of intrinsic instruction!", U); 2104 } 2105 2106 Assert(!F.hasDLLImportStorageClass() || 2107 (F.isDeclaration() && F.hasExternalLinkage()) || 2108 F.hasAvailableExternallyLinkage(), 2109 "Function is marked as dllimport, but not external.", &F); 2110 2111 auto *N = F.getSubprogram(); 2112 if (!N) 2113 return; 2114 2115 visitDISubprogram(*N); 2116 2117 // Check that all !dbg attachments lead to back to N (or, at least, another 2118 // subprogram that describes the same function). 2119 // 2120 // FIXME: Check this incrementally while visiting !dbg attachments. 2121 // FIXME: Only check when N is the canonical subprogram for F. 2122 SmallPtrSet<const MDNode *, 32> Seen; 2123 for (auto &BB : F) 2124 for (auto &I : BB) { 2125 // Be careful about using DILocation here since we might be dealing with 2126 // broken code (this is the Verifier after all). 2127 DILocation *DL = 2128 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode()); 2129 if (!DL) 2130 continue; 2131 if (!Seen.insert(DL).second) 2132 continue; 2133 2134 DILocalScope *Scope = DL->getInlinedAtScope(); 2135 if (Scope && !Seen.insert(Scope).second) 2136 continue; 2137 2138 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr; 2139 2140 // Scope and SP could be the same MDNode and we don't want to skip 2141 // validation in that case 2142 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2143 continue; 2144 2145 // FIXME: Once N is canonical, check "SP == &N". 2146 AssertDI(SP->describes(&F), 2147 "!dbg attachment points at wrong subprogram for function", N, &F, 2148 &I, DL, Scope, SP); 2149 } 2150 } 2151 2152 // verifyBasicBlock - Verify that a basic block is well formed... 2153 // 2154 void Verifier::visitBasicBlock(BasicBlock &BB) { 2155 InstsInThisBlock.clear(); 2156 2157 // Ensure that basic blocks have terminators! 2158 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2159 2160 // Check constraints that this basic block imposes on all of the PHI nodes in 2161 // it. 2162 if (isa<PHINode>(BB.front())) { 2163 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 2164 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2165 std::sort(Preds.begin(), Preds.end()); 2166 PHINode *PN; 2167 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 2168 // Ensure that PHI nodes have at least one entry! 2169 Assert(PN->getNumIncomingValues() != 0, 2170 "PHI nodes must have at least one entry. If the block is dead, " 2171 "the PHI should be removed!", 2172 PN); 2173 Assert(PN->getNumIncomingValues() == Preds.size(), 2174 "PHINode should have one entry for each predecessor of its " 2175 "parent basic block!", 2176 PN); 2177 2178 // Get and sort all incoming values in the PHI node... 2179 Values.clear(); 2180 Values.reserve(PN->getNumIncomingValues()); 2181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2182 Values.push_back(std::make_pair(PN->getIncomingBlock(i), 2183 PN->getIncomingValue(i))); 2184 std::sort(Values.begin(), Values.end()); 2185 2186 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2187 // Check to make sure that if there is more than one entry for a 2188 // particular basic block in this PHI node, that the incoming values are 2189 // all identical. 2190 // 2191 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2192 Values[i].second == Values[i - 1].second, 2193 "PHI node has multiple entries for the same basic block with " 2194 "different incoming values!", 2195 PN, Values[i].first, Values[i].second, Values[i - 1].second); 2196 2197 // Check to make sure that the predecessors and PHI node entries are 2198 // matched up. 2199 Assert(Values[i].first == Preds[i], 2200 "PHI node entries do not match predecessors!", PN, 2201 Values[i].first, Preds[i]); 2202 } 2203 } 2204 } 2205 2206 // Check that all instructions have their parent pointers set up correctly. 2207 for (auto &I : BB) 2208 { 2209 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2210 } 2211 } 2212 2213 void Verifier::visitTerminatorInst(TerminatorInst &I) { 2214 // Ensure that terminators only exist at the end of the basic block. 2215 Assert(&I == I.getParent()->getTerminator(), 2216 "Terminator found in the middle of a basic block!", I.getParent()); 2217 visitInstruction(I); 2218 } 2219 2220 void Verifier::visitBranchInst(BranchInst &BI) { 2221 if (BI.isConditional()) { 2222 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2223 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2224 } 2225 visitTerminatorInst(BI); 2226 } 2227 2228 void Verifier::visitReturnInst(ReturnInst &RI) { 2229 Function *F = RI.getParent()->getParent(); 2230 unsigned N = RI.getNumOperands(); 2231 if (F->getReturnType()->isVoidTy()) 2232 Assert(N == 0, 2233 "Found return instr that returns non-void in Function of void " 2234 "return type!", 2235 &RI, F->getReturnType()); 2236 else 2237 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2238 "Function return type does not match operand " 2239 "type of return inst!", 2240 &RI, F->getReturnType()); 2241 2242 // Check to make sure that the return value has necessary properties for 2243 // terminators... 2244 visitTerminatorInst(RI); 2245 } 2246 2247 void Verifier::visitSwitchInst(SwitchInst &SI) { 2248 // Check to make sure that all of the constants in the switch instruction 2249 // have the same type as the switched-on value. 2250 Type *SwitchTy = SI.getCondition()->getType(); 2251 SmallPtrSet<ConstantInt*, 32> Constants; 2252 for (auto &Case : SI.cases()) { 2253 Assert(Case.getCaseValue()->getType() == SwitchTy, 2254 "Switch constants must all be same type as switch value!", &SI); 2255 Assert(Constants.insert(Case.getCaseValue()).second, 2256 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2257 } 2258 2259 visitTerminatorInst(SI); 2260 } 2261 2262 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2263 Assert(BI.getAddress()->getType()->isPointerTy(), 2264 "Indirectbr operand must have pointer type!", &BI); 2265 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2266 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2267 "Indirectbr destinations must all have pointer type!", &BI); 2268 2269 visitTerminatorInst(BI); 2270 } 2271 2272 void Verifier::visitSelectInst(SelectInst &SI) { 2273 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2274 SI.getOperand(2)), 2275 "Invalid operands for select instruction!", &SI); 2276 2277 Assert(SI.getTrueValue()->getType() == SI.getType(), 2278 "Select values must have same type as select instruction!", &SI); 2279 visitInstruction(SI); 2280 } 2281 2282 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2283 /// a pass, if any exist, it's an error. 2284 /// 2285 void Verifier::visitUserOp1(Instruction &I) { 2286 Assert(false, "User-defined operators should not live outside of a pass!", &I); 2287 } 2288 2289 void Verifier::visitTruncInst(TruncInst &I) { 2290 // Get the source and destination types 2291 Type *SrcTy = I.getOperand(0)->getType(); 2292 Type *DestTy = I.getType(); 2293 2294 // Get the size of the types in bits, we'll need this later 2295 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2296 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2297 2298 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2299 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2300 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2301 "trunc source and destination must both be a vector or neither", &I); 2302 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2303 2304 visitInstruction(I); 2305 } 2306 2307 void Verifier::visitZExtInst(ZExtInst &I) { 2308 // Get the source and destination types 2309 Type *SrcTy = I.getOperand(0)->getType(); 2310 Type *DestTy = I.getType(); 2311 2312 // Get the size of the types in bits, we'll need this later 2313 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2314 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2315 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2316 "zext source and destination must both be a vector or neither", &I); 2317 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2318 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2319 2320 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2321 2322 visitInstruction(I); 2323 } 2324 2325 void Verifier::visitSExtInst(SExtInst &I) { 2326 // Get the source and destination types 2327 Type *SrcTy = I.getOperand(0)->getType(); 2328 Type *DestTy = I.getType(); 2329 2330 // Get the size of the types in bits, we'll need this later 2331 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2332 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2333 2334 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2335 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2336 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2337 "sext source and destination must both be a vector or neither", &I); 2338 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2339 2340 visitInstruction(I); 2341 } 2342 2343 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2344 // Get the source and destination types 2345 Type *SrcTy = I.getOperand(0)->getType(); 2346 Type *DestTy = I.getType(); 2347 // Get the size of the types in bits, we'll need this later 2348 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2349 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2350 2351 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2352 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2353 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2354 "fptrunc source and destination must both be a vector or neither", &I); 2355 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2356 2357 visitInstruction(I); 2358 } 2359 2360 void Verifier::visitFPExtInst(FPExtInst &I) { 2361 // Get the source and destination types 2362 Type *SrcTy = I.getOperand(0)->getType(); 2363 Type *DestTy = I.getType(); 2364 2365 // Get the size of the types in bits, we'll need this later 2366 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2367 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2368 2369 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2370 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2371 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2372 "fpext source and destination must both be a vector or neither", &I); 2373 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2374 2375 visitInstruction(I); 2376 } 2377 2378 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2379 // Get the source and destination types 2380 Type *SrcTy = I.getOperand(0)->getType(); 2381 Type *DestTy = I.getType(); 2382 2383 bool SrcVec = SrcTy->isVectorTy(); 2384 bool DstVec = DestTy->isVectorTy(); 2385 2386 Assert(SrcVec == DstVec, 2387 "UIToFP source and dest must both be vector or scalar", &I); 2388 Assert(SrcTy->isIntOrIntVectorTy(), 2389 "UIToFP source must be integer or integer vector", &I); 2390 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2391 &I); 2392 2393 if (SrcVec && DstVec) 2394 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2395 cast<VectorType>(DestTy)->getNumElements(), 2396 "UIToFP source and dest vector length mismatch", &I); 2397 2398 visitInstruction(I); 2399 } 2400 2401 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2402 // Get the source and destination types 2403 Type *SrcTy = I.getOperand(0)->getType(); 2404 Type *DestTy = I.getType(); 2405 2406 bool SrcVec = SrcTy->isVectorTy(); 2407 bool DstVec = DestTy->isVectorTy(); 2408 2409 Assert(SrcVec == DstVec, 2410 "SIToFP source and dest must both be vector or scalar", &I); 2411 Assert(SrcTy->isIntOrIntVectorTy(), 2412 "SIToFP source must be integer or integer vector", &I); 2413 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2414 &I); 2415 2416 if (SrcVec && DstVec) 2417 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2418 cast<VectorType>(DestTy)->getNumElements(), 2419 "SIToFP source and dest vector length mismatch", &I); 2420 2421 visitInstruction(I); 2422 } 2423 2424 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2425 // Get the source and destination types 2426 Type *SrcTy = I.getOperand(0)->getType(); 2427 Type *DestTy = I.getType(); 2428 2429 bool SrcVec = SrcTy->isVectorTy(); 2430 bool DstVec = DestTy->isVectorTy(); 2431 2432 Assert(SrcVec == DstVec, 2433 "FPToUI source and dest must both be vector or scalar", &I); 2434 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2435 &I); 2436 Assert(DestTy->isIntOrIntVectorTy(), 2437 "FPToUI result must be integer or integer vector", &I); 2438 2439 if (SrcVec && DstVec) 2440 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2441 cast<VectorType>(DestTy)->getNumElements(), 2442 "FPToUI source and dest vector length mismatch", &I); 2443 2444 visitInstruction(I); 2445 } 2446 2447 void Verifier::visitFPToSIInst(FPToSIInst &I) { 2448 // Get the source and destination types 2449 Type *SrcTy = I.getOperand(0)->getType(); 2450 Type *DestTy = I.getType(); 2451 2452 bool SrcVec = SrcTy->isVectorTy(); 2453 bool DstVec = DestTy->isVectorTy(); 2454 2455 Assert(SrcVec == DstVec, 2456 "FPToSI source and dest must both be vector or scalar", &I); 2457 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 2458 &I); 2459 Assert(DestTy->isIntOrIntVectorTy(), 2460 "FPToSI result must be integer or integer vector", &I); 2461 2462 if (SrcVec && DstVec) 2463 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2464 cast<VectorType>(DestTy)->getNumElements(), 2465 "FPToSI source and dest vector length mismatch", &I); 2466 2467 visitInstruction(I); 2468 } 2469 2470 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 2471 // Get the source and destination types 2472 Type *SrcTy = I.getOperand(0)->getType(); 2473 Type *DestTy = I.getType(); 2474 2475 Assert(SrcTy->getScalarType()->isPointerTy(), 2476 "PtrToInt source must be pointer", &I); 2477 2478 if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType())) 2479 Assert(!DL.isNonIntegralPointerType(PTy), 2480 "ptrtoint not supported for non-integral pointers"); 2481 2482 Assert(DestTy->getScalarType()->isIntegerTy(), 2483 "PtrToInt result must be integral", &I); 2484 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 2485 &I); 2486 2487 if (SrcTy->isVectorTy()) { 2488 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2489 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2490 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2491 "PtrToInt Vector width mismatch", &I); 2492 } 2493 2494 visitInstruction(I); 2495 } 2496 2497 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 2498 // Get the source and destination types 2499 Type *SrcTy = I.getOperand(0)->getType(); 2500 Type *DestTy = I.getType(); 2501 2502 Assert(SrcTy->getScalarType()->isIntegerTy(), 2503 "IntToPtr source must be an integral", &I); 2504 Assert(DestTy->getScalarType()->isPointerTy(), 2505 "IntToPtr result must be a pointer", &I); 2506 2507 if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType())) 2508 Assert(!DL.isNonIntegralPointerType(PTy), 2509 "inttoptr not supported for non-integral pointers"); 2510 2511 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 2512 &I); 2513 if (SrcTy->isVectorTy()) { 2514 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2515 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2516 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2517 "IntToPtr Vector width mismatch", &I); 2518 } 2519 visitInstruction(I); 2520 } 2521 2522 void Verifier::visitBitCastInst(BitCastInst &I) { 2523 Assert( 2524 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 2525 "Invalid bitcast", &I); 2526 visitInstruction(I); 2527 } 2528 2529 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 2530 Type *SrcTy = I.getOperand(0)->getType(); 2531 Type *DestTy = I.getType(); 2532 2533 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 2534 &I); 2535 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 2536 &I); 2537 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 2538 "AddrSpaceCast must be between different address spaces", &I); 2539 if (SrcTy->isVectorTy()) 2540 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 2541 "AddrSpaceCast vector pointer number of elements mismatch", &I); 2542 visitInstruction(I); 2543 } 2544 2545 /// visitPHINode - Ensure that a PHI node is well formed. 2546 /// 2547 void Verifier::visitPHINode(PHINode &PN) { 2548 // Ensure that the PHI nodes are all grouped together at the top of the block. 2549 // This can be tested by checking whether the instruction before this is 2550 // either nonexistent (because this is begin()) or is a PHI node. If not, 2551 // then there is some other instruction before a PHI. 2552 Assert(&PN == &PN.getParent()->front() || 2553 isa<PHINode>(--BasicBlock::iterator(&PN)), 2554 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 2555 2556 // Check that a PHI doesn't yield a Token. 2557 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 2558 2559 // Check that all of the values of the PHI node have the same type as the 2560 // result, and that the incoming blocks are really basic blocks. 2561 for (Value *IncValue : PN.incoming_values()) { 2562 Assert(PN.getType() == IncValue->getType(), 2563 "PHI node operands are not the same type as the result!", &PN); 2564 } 2565 2566 // All other PHI node constraints are checked in the visitBasicBlock method. 2567 2568 visitInstruction(PN); 2569 } 2570 2571 void Verifier::verifyCallSite(CallSite CS) { 2572 Instruction *I = CS.getInstruction(); 2573 2574 Assert(CS.getCalledValue()->getType()->isPointerTy(), 2575 "Called function must be a pointer!", I); 2576 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 2577 2578 Assert(FPTy->getElementType()->isFunctionTy(), 2579 "Called function is not pointer to function type!", I); 2580 2581 Assert(FPTy->getElementType() == CS.getFunctionType(), 2582 "Called function is not the same type as the call!", I); 2583 2584 FunctionType *FTy = CS.getFunctionType(); 2585 2586 // Verify that the correct number of arguments are being passed 2587 if (FTy->isVarArg()) 2588 Assert(CS.arg_size() >= FTy->getNumParams(), 2589 "Called function requires more parameters than were provided!", I); 2590 else 2591 Assert(CS.arg_size() == FTy->getNumParams(), 2592 "Incorrect number of arguments passed to called function!", I); 2593 2594 // Verify that all arguments to the call match the function type. 2595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2596 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i), 2597 "Call parameter type does not match function signature!", 2598 CS.getArgument(i), FTy->getParamType(i), I); 2599 2600 AttributeSet Attrs = CS.getAttributes(); 2601 2602 Assert(verifyAttributeCount(Attrs, CS.arg_size()), 2603 "Attribute after last parameter!", I); 2604 2605 // Verify call attributes. 2606 verifyFunctionAttrs(FTy, Attrs, I); 2607 2608 // Conservatively check the inalloca argument. 2609 // We have a bug if we can find that there is an underlying alloca without 2610 // inalloca. 2611 if (CS.hasInAllocaArgument()) { 2612 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1); 2613 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 2614 Assert(AI->isUsedWithInAlloca(), 2615 "inalloca argument for call has mismatched alloca", AI, I); 2616 } 2617 2618 // For each argument of the callsite, if it has the swifterror argument, 2619 // make sure the underlying alloca/parameter it comes from has a swifterror as 2620 // well. 2621 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2622 if (CS.paramHasAttr(i+1, Attribute::SwiftError)) { 2623 Value *SwiftErrorArg = CS.getArgument(i); 2624 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) { 2625 Assert(AI->isSwiftError(), 2626 "swifterror argument for call has mismatched alloca", AI, I); 2627 continue; 2628 } 2629 auto ArgI = dyn_cast<Argument>(SwiftErrorArg); 2630 Assert(ArgI, "swifterror argument should come from an alloca or parameter", SwiftErrorArg, I); 2631 Assert(ArgI->hasSwiftErrorAttr(), 2632 "swifterror argument for call has mismatched parameter", ArgI, I); 2633 } 2634 2635 if (FTy->isVarArg()) { 2636 // FIXME? is 'nest' even legal here? 2637 bool SawNest = false; 2638 bool SawReturned = false; 2639 2640 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) { 2641 if (Attrs.hasAttribute(Idx, Attribute::Nest)) 2642 SawNest = true; 2643 if (Attrs.hasAttribute(Idx, Attribute::Returned)) 2644 SawReturned = true; 2645 } 2646 2647 // Check attributes on the varargs part. 2648 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 2649 Type *Ty = CS.getArgument(Idx-1)->getType(); 2650 verifyParameterAttrs(Attrs, Idx, Ty, false, I); 2651 2652 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 2653 Assert(!SawNest, "More than one parameter has attribute nest!", I); 2654 SawNest = true; 2655 } 2656 2657 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 2658 Assert(!SawReturned, "More than one parameter has attribute returned!", 2659 I); 2660 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 2661 "Incompatible argument and return types for 'returned' " 2662 "attribute", 2663 I); 2664 SawReturned = true; 2665 } 2666 2667 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet), 2668 "Attribute 'sret' cannot be used for vararg call arguments!", I); 2669 2670 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) 2671 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I); 2672 } 2673 } 2674 2675 // Verify that there's no metadata unless it's a direct call to an intrinsic. 2676 if (CS.getCalledFunction() == nullptr || 2677 !CS.getCalledFunction()->getName().startswith("llvm.")) { 2678 for (Type *ParamTy : FTy->params()) { 2679 Assert(!ParamTy->isMetadataTy(), 2680 "Function has metadata parameter but isn't an intrinsic", I); 2681 Assert(!ParamTy->isTokenTy(), 2682 "Function has token parameter but isn't an intrinsic", I); 2683 } 2684 } 2685 2686 // Verify that indirect calls don't return tokens. 2687 if (CS.getCalledFunction() == nullptr) 2688 Assert(!FTy->getReturnType()->isTokenTy(), 2689 "Return type cannot be token for indirect call!"); 2690 2691 if (Function *F = CS.getCalledFunction()) 2692 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 2693 visitIntrinsicCallSite(ID, CS); 2694 2695 // Verify that a callsite has at most one "deopt", at most one "funclet" and 2696 // at most one "gc-transition" operand bundle. 2697 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 2698 FoundGCTransitionBundle = false; 2699 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) { 2700 OperandBundleUse BU = CS.getOperandBundleAt(i); 2701 uint32_t Tag = BU.getTagID(); 2702 if (Tag == LLVMContext::OB_deopt) { 2703 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I); 2704 FoundDeoptBundle = true; 2705 } else if (Tag == LLVMContext::OB_gc_transition) { 2706 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 2707 I); 2708 FoundGCTransitionBundle = true; 2709 } else if (Tag == LLVMContext::OB_funclet) { 2710 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I); 2711 FoundFuncletBundle = true; 2712 Assert(BU.Inputs.size() == 1, 2713 "Expected exactly one funclet bundle operand", I); 2714 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 2715 "Funclet bundle operands should correspond to a FuncletPadInst", 2716 I); 2717 } 2718 } 2719 2720 // Verify that each inlinable callsite of a debug-info-bearing function in a 2721 // debug-info-bearing function has a debug location attached to it. Failure to 2722 // do so causes assertion failures when the inliner sets up inline scope info. 2723 if (I->getFunction()->getSubprogram() && CS.getCalledFunction() && 2724 CS.getCalledFunction()->getSubprogram()) 2725 Assert(I->getDebugLoc(), "inlinable function call in a function with debug " 2726 "info must have a !dbg location", 2727 I); 2728 2729 visitInstruction(*I); 2730 } 2731 2732 /// Two types are "congruent" if they are identical, or if they are both pointer 2733 /// types with different pointee types and the same address space. 2734 static bool isTypeCongruent(Type *L, Type *R) { 2735 if (L == R) 2736 return true; 2737 PointerType *PL = dyn_cast<PointerType>(L); 2738 PointerType *PR = dyn_cast<PointerType>(R); 2739 if (!PL || !PR) 2740 return false; 2741 return PL->getAddressSpace() == PR->getAddressSpace(); 2742 } 2743 2744 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) { 2745 static const Attribute::AttrKind ABIAttrs[] = { 2746 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 2747 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf, 2748 Attribute::SwiftError}; 2749 AttrBuilder Copy; 2750 for (auto AK : ABIAttrs) { 2751 if (Attrs.hasAttribute(I + 1, AK)) 2752 Copy.addAttribute(AK); 2753 } 2754 if (Attrs.hasAttribute(I + 1, Attribute::Alignment)) 2755 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1)); 2756 return Copy; 2757 } 2758 2759 void Verifier::verifyMustTailCall(CallInst &CI) { 2760 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 2761 2762 // - The caller and callee prototypes must match. Pointer types of 2763 // parameters or return types may differ in pointee type, but not 2764 // address space. 2765 Function *F = CI.getParent()->getParent(); 2766 FunctionType *CallerTy = F->getFunctionType(); 2767 FunctionType *CalleeTy = CI.getFunctionType(); 2768 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 2769 "cannot guarantee tail call due to mismatched parameter counts", &CI); 2770 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 2771 "cannot guarantee tail call due to mismatched varargs", &CI); 2772 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 2773 "cannot guarantee tail call due to mismatched return types", &CI); 2774 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2775 Assert( 2776 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 2777 "cannot guarantee tail call due to mismatched parameter types", &CI); 2778 } 2779 2780 // - The calling conventions of the caller and callee must match. 2781 Assert(F->getCallingConv() == CI.getCallingConv(), 2782 "cannot guarantee tail call due to mismatched calling conv", &CI); 2783 2784 // - All ABI-impacting function attributes, such as sret, byval, inreg, 2785 // returned, and inalloca, must match. 2786 AttributeSet CallerAttrs = F->getAttributes(); 2787 AttributeSet CalleeAttrs = CI.getAttributes(); 2788 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2789 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 2790 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 2791 Assert(CallerABIAttrs == CalleeABIAttrs, 2792 "cannot guarantee tail call due to mismatched ABI impacting " 2793 "function attributes", 2794 &CI, CI.getOperand(I)); 2795 } 2796 2797 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 2798 // or a pointer bitcast followed by a ret instruction. 2799 // - The ret instruction must return the (possibly bitcasted) value 2800 // produced by the call or void. 2801 Value *RetVal = &CI; 2802 Instruction *Next = CI.getNextNode(); 2803 2804 // Handle the optional bitcast. 2805 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 2806 Assert(BI->getOperand(0) == RetVal, 2807 "bitcast following musttail call must use the call", BI); 2808 RetVal = BI; 2809 Next = BI->getNextNode(); 2810 } 2811 2812 // Check the return. 2813 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 2814 Assert(Ret, "musttail call must be precede a ret with an optional bitcast", 2815 &CI); 2816 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 2817 "musttail call result must be returned", Ret); 2818 } 2819 2820 void Verifier::visitCallInst(CallInst &CI) { 2821 verifyCallSite(&CI); 2822 2823 if (CI.isMustTailCall()) 2824 verifyMustTailCall(CI); 2825 } 2826 2827 void Verifier::visitInvokeInst(InvokeInst &II) { 2828 verifyCallSite(&II); 2829 2830 // Verify that the first non-PHI instruction of the unwind destination is an 2831 // exception handling instruction. 2832 Assert( 2833 II.getUnwindDest()->isEHPad(), 2834 "The unwind destination does not have an exception handling instruction!", 2835 &II); 2836 2837 visitTerminatorInst(II); 2838 } 2839 2840 /// visitBinaryOperator - Check that both arguments to the binary operator are 2841 /// of the same type! 2842 /// 2843 void Verifier::visitBinaryOperator(BinaryOperator &B) { 2844 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 2845 "Both operands to a binary operator are not of the same type!", &B); 2846 2847 switch (B.getOpcode()) { 2848 // Check that integer arithmetic operators are only used with 2849 // integral operands. 2850 case Instruction::Add: 2851 case Instruction::Sub: 2852 case Instruction::Mul: 2853 case Instruction::SDiv: 2854 case Instruction::UDiv: 2855 case Instruction::SRem: 2856 case Instruction::URem: 2857 Assert(B.getType()->isIntOrIntVectorTy(), 2858 "Integer arithmetic operators only work with integral types!", &B); 2859 Assert(B.getType() == B.getOperand(0)->getType(), 2860 "Integer arithmetic operators must have same type " 2861 "for operands and result!", 2862 &B); 2863 break; 2864 // Check that floating-point arithmetic operators are only used with 2865 // floating-point operands. 2866 case Instruction::FAdd: 2867 case Instruction::FSub: 2868 case Instruction::FMul: 2869 case Instruction::FDiv: 2870 case Instruction::FRem: 2871 Assert(B.getType()->isFPOrFPVectorTy(), 2872 "Floating-point arithmetic operators only work with " 2873 "floating-point types!", 2874 &B); 2875 Assert(B.getType() == B.getOperand(0)->getType(), 2876 "Floating-point arithmetic operators must have same type " 2877 "for operands and result!", 2878 &B); 2879 break; 2880 // Check that logical operators are only used with integral operands. 2881 case Instruction::And: 2882 case Instruction::Or: 2883 case Instruction::Xor: 2884 Assert(B.getType()->isIntOrIntVectorTy(), 2885 "Logical operators only work with integral types!", &B); 2886 Assert(B.getType() == B.getOperand(0)->getType(), 2887 "Logical operators must have same type for operands and result!", 2888 &B); 2889 break; 2890 case Instruction::Shl: 2891 case Instruction::LShr: 2892 case Instruction::AShr: 2893 Assert(B.getType()->isIntOrIntVectorTy(), 2894 "Shifts only work with integral types!", &B); 2895 Assert(B.getType() == B.getOperand(0)->getType(), 2896 "Shift return type must be same as operands!", &B); 2897 break; 2898 default: 2899 llvm_unreachable("Unknown BinaryOperator opcode!"); 2900 } 2901 2902 visitInstruction(B); 2903 } 2904 2905 void Verifier::visitICmpInst(ICmpInst &IC) { 2906 // Check that the operands are the same type 2907 Type *Op0Ty = IC.getOperand(0)->getType(); 2908 Type *Op1Ty = IC.getOperand(1)->getType(); 2909 Assert(Op0Ty == Op1Ty, 2910 "Both operands to ICmp instruction are not of the same type!", &IC); 2911 // Check that the operands are the right type 2912 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 2913 "Invalid operand types for ICmp instruction", &IC); 2914 // Check that the predicate is valid. 2915 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 2916 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 2917 "Invalid predicate in ICmp instruction!", &IC); 2918 2919 visitInstruction(IC); 2920 } 2921 2922 void Verifier::visitFCmpInst(FCmpInst &FC) { 2923 // Check that the operands are the same type 2924 Type *Op0Ty = FC.getOperand(0)->getType(); 2925 Type *Op1Ty = FC.getOperand(1)->getType(); 2926 Assert(Op0Ty == Op1Ty, 2927 "Both operands to FCmp instruction are not of the same type!", &FC); 2928 // Check that the operands are the right type 2929 Assert(Op0Ty->isFPOrFPVectorTy(), 2930 "Invalid operand types for FCmp instruction", &FC); 2931 // Check that the predicate is valid. 2932 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 2933 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 2934 "Invalid predicate in FCmp instruction!", &FC); 2935 2936 visitInstruction(FC); 2937 } 2938 2939 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 2940 Assert( 2941 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 2942 "Invalid extractelement operands!", &EI); 2943 visitInstruction(EI); 2944 } 2945 2946 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 2947 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 2948 IE.getOperand(2)), 2949 "Invalid insertelement operands!", &IE); 2950 visitInstruction(IE); 2951 } 2952 2953 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 2954 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 2955 SV.getOperand(2)), 2956 "Invalid shufflevector operands!", &SV); 2957 visitInstruction(SV); 2958 } 2959 2960 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 2961 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 2962 2963 Assert(isa<PointerType>(TargetTy), 2964 "GEP base pointer is not a vector or a vector of pointers", &GEP); 2965 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 2966 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 2967 Type *ElTy = 2968 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 2969 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 2970 2971 Assert(GEP.getType()->getScalarType()->isPointerTy() && 2972 GEP.getResultElementType() == ElTy, 2973 "GEP is not of right type for indices!", &GEP, ElTy); 2974 2975 if (GEP.getType()->isVectorTy()) { 2976 // Additional checks for vector GEPs. 2977 unsigned GEPWidth = GEP.getType()->getVectorNumElements(); 2978 if (GEP.getPointerOperandType()->isVectorTy()) 2979 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(), 2980 "Vector GEP result width doesn't match operand's", &GEP); 2981 for (Value *Idx : Idxs) { 2982 Type *IndexTy = Idx->getType(); 2983 if (IndexTy->isVectorTy()) { 2984 unsigned IndexWidth = IndexTy->getVectorNumElements(); 2985 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 2986 } 2987 Assert(IndexTy->getScalarType()->isIntegerTy(), 2988 "All GEP indices should be of integer type"); 2989 } 2990 } 2991 visitInstruction(GEP); 2992 } 2993 2994 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 2995 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 2996 } 2997 2998 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) { 2999 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) && 3000 "precondition violation"); 3001 3002 unsigned NumOperands = Range->getNumOperands(); 3003 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 3004 unsigned NumRanges = NumOperands / 2; 3005 Assert(NumRanges >= 1, "It should have at least one range!", Range); 3006 3007 ConstantRange LastRange(1); // Dummy initial value 3008 for (unsigned i = 0; i < NumRanges; ++i) { 3009 ConstantInt *Low = 3010 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 3011 Assert(Low, "The lower limit must be an integer!", Low); 3012 ConstantInt *High = 3013 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 3014 Assert(High, "The upper limit must be an integer!", High); 3015 Assert(High->getType() == Low->getType() && High->getType() == Ty, 3016 "Range types must match instruction type!", &I); 3017 3018 APInt HighV = High->getValue(); 3019 APInt LowV = Low->getValue(); 3020 ConstantRange CurRange(LowV, HighV); 3021 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 3022 "Range must not be empty!", Range); 3023 if (i != 0) { 3024 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 3025 "Intervals are overlapping", Range); 3026 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 3027 Range); 3028 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 3029 Range); 3030 } 3031 LastRange = ConstantRange(LowV, HighV); 3032 } 3033 if (NumRanges > 2) { 3034 APInt FirstLow = 3035 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 3036 APInt FirstHigh = 3037 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 3038 ConstantRange FirstRange(FirstLow, FirstHigh); 3039 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 3040 "Intervals are overlapping", Range); 3041 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 3042 Range); 3043 } 3044 } 3045 3046 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) { 3047 unsigned Size = DL.getTypeSizeInBits(Ty); 3048 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 3049 Assert(!(Size & (Size - 1)), 3050 "atomic memory access' operand must have a power-of-two size", Ty, I); 3051 } 3052 3053 void Verifier::visitLoadInst(LoadInst &LI) { 3054 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 3055 Assert(PTy, "Load operand must be a pointer.", &LI); 3056 Type *ElTy = LI.getType(); 3057 Assert(LI.getAlignment() <= Value::MaximumAlignment, 3058 "huge alignment values are unsupported", &LI); 3059 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 3060 if (LI.isAtomic()) { 3061 Assert(LI.getOrdering() != AtomicOrdering::Release && 3062 LI.getOrdering() != AtomicOrdering::AcquireRelease, 3063 "Load cannot have Release ordering", &LI); 3064 Assert(LI.getAlignment() != 0, 3065 "Atomic load must specify explicit alignment", &LI); 3066 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 3067 ElTy->isFloatingPointTy(), 3068 "atomic load operand must have integer, pointer, or floating point " 3069 "type!", 3070 ElTy, &LI); 3071 checkAtomicMemAccessSize(ElTy, &LI); 3072 } else { 3073 Assert(LI.getSynchScope() == CrossThread, 3074 "Non-atomic load cannot have SynchronizationScope specified", &LI); 3075 } 3076 3077 visitInstruction(LI); 3078 } 3079 3080 void Verifier::visitStoreInst(StoreInst &SI) { 3081 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 3082 Assert(PTy, "Store operand must be a pointer.", &SI); 3083 Type *ElTy = PTy->getElementType(); 3084 Assert(ElTy == SI.getOperand(0)->getType(), 3085 "Stored value type does not match pointer operand type!", &SI, ElTy); 3086 Assert(SI.getAlignment() <= Value::MaximumAlignment, 3087 "huge alignment values are unsupported", &SI); 3088 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 3089 if (SI.isAtomic()) { 3090 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 3091 SI.getOrdering() != AtomicOrdering::AcquireRelease, 3092 "Store cannot have Acquire ordering", &SI); 3093 Assert(SI.getAlignment() != 0, 3094 "Atomic store must specify explicit alignment", &SI); 3095 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 3096 ElTy->isFloatingPointTy(), 3097 "atomic store operand must have integer, pointer, or floating point " 3098 "type!", 3099 ElTy, &SI); 3100 checkAtomicMemAccessSize(ElTy, &SI); 3101 } else { 3102 Assert(SI.getSynchScope() == CrossThread, 3103 "Non-atomic store cannot have SynchronizationScope specified", &SI); 3104 } 3105 visitInstruction(SI); 3106 } 3107 3108 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3109 void Verifier::verifySwiftErrorCallSite(CallSite CS, 3110 const Value *SwiftErrorVal) { 3111 unsigned Idx = 0; 3112 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 3113 I != E; ++I, ++Idx) { 3114 if (*I == SwiftErrorVal) { 3115 Assert(CS.paramHasAttr(Idx+1, Attribute::SwiftError), 3116 "swifterror value when used in a callsite should be marked " 3117 "with swifterror attribute", 3118 SwiftErrorVal, CS); 3119 } 3120 } 3121 } 3122 3123 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3124 // Check that swifterror value is only used by loads, stores, or as 3125 // a swifterror argument. 3126 for (const User *U : SwiftErrorVal->users()) { 3127 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3128 isa<InvokeInst>(U), 3129 "swifterror value can only be loaded and stored from, or " 3130 "as a swifterror argument!", 3131 SwiftErrorVal, U); 3132 // If it is used by a store, check it is the second operand. 3133 if (auto StoreI = dyn_cast<StoreInst>(U)) 3134 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3135 "swifterror value should be the second operand when used " 3136 "by stores", SwiftErrorVal, U); 3137 if (auto CallI = dyn_cast<CallInst>(U)) 3138 verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal); 3139 if (auto II = dyn_cast<InvokeInst>(U)) 3140 verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal); 3141 } 3142 } 3143 3144 void Verifier::visitAllocaInst(AllocaInst &AI) { 3145 SmallPtrSet<Type*, 4> Visited; 3146 PointerType *PTy = AI.getType(); 3147 Assert(PTy->getAddressSpace() == 0, 3148 "Allocation instruction pointer not in the generic address space!", 3149 &AI); 3150 Assert(AI.getAllocatedType()->isSized(&Visited), 3151 "Cannot allocate unsized type", &AI); 3152 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3153 "Alloca array size must have integer type", &AI); 3154 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3155 "huge alignment values are unsupported", &AI); 3156 3157 if (AI.isSwiftError()) { 3158 verifySwiftErrorValue(&AI); 3159 } 3160 3161 visitInstruction(AI); 3162 } 3163 3164 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3165 3166 // FIXME: more conditions??? 3167 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic, 3168 "cmpxchg instructions must be atomic.", &CXI); 3169 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic, 3170 "cmpxchg instructions must be atomic.", &CXI); 3171 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered, 3172 "cmpxchg instructions cannot be unordered.", &CXI); 3173 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered, 3174 "cmpxchg instructions cannot be unordered.", &CXI); 3175 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()), 3176 "cmpxchg instructions failure argument shall be no stronger than the " 3177 "success argument", 3178 &CXI); 3179 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release && 3180 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease, 3181 "cmpxchg failure ordering cannot include release semantics", &CXI); 3182 3183 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 3184 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI); 3185 Type *ElTy = PTy->getElementType(); 3186 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy(), 3187 "cmpxchg operand must have integer or pointer type", 3188 ElTy, &CXI); 3189 checkAtomicMemAccessSize(ElTy, &CXI); 3190 Assert(ElTy == CXI.getOperand(1)->getType(), 3191 "Expected value type does not match pointer operand type!", &CXI, 3192 ElTy); 3193 Assert(ElTy == CXI.getOperand(2)->getType(), 3194 "Stored value type does not match pointer operand type!", &CXI, ElTy); 3195 visitInstruction(CXI); 3196 } 3197 3198 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3199 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic, 3200 "atomicrmw instructions must be atomic.", &RMWI); 3201 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3202 "atomicrmw instructions cannot be unordered.", &RMWI); 3203 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 3204 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 3205 Type *ElTy = PTy->getElementType(); 3206 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!", 3207 &RMWI, ElTy); 3208 checkAtomicMemAccessSize(ElTy, &RMWI); 3209 Assert(ElTy == RMWI.getOperand(1)->getType(), 3210 "Argument value type does not match pointer operand type!", &RMWI, 3211 ElTy); 3212 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 3213 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 3214 "Invalid binary operation!", &RMWI); 3215 visitInstruction(RMWI); 3216 } 3217 3218 void Verifier::visitFenceInst(FenceInst &FI) { 3219 const AtomicOrdering Ordering = FI.getOrdering(); 3220 Assert(Ordering == AtomicOrdering::Acquire || 3221 Ordering == AtomicOrdering::Release || 3222 Ordering == AtomicOrdering::AcquireRelease || 3223 Ordering == AtomicOrdering::SequentiallyConsistent, 3224 "fence instructions may only have acquire, release, acq_rel, or " 3225 "seq_cst ordering.", 3226 &FI); 3227 visitInstruction(FI); 3228 } 3229 3230 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3231 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3232 EVI.getIndices()) == EVI.getType(), 3233 "Invalid ExtractValueInst operands!", &EVI); 3234 3235 visitInstruction(EVI); 3236 } 3237 3238 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3239 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3240 IVI.getIndices()) == 3241 IVI.getOperand(1)->getType(), 3242 "Invalid InsertValueInst operands!", &IVI); 3243 3244 visitInstruction(IVI); 3245 } 3246 3247 static Value *getParentPad(Value *EHPad) { 3248 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3249 return FPI->getParentPad(); 3250 3251 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3252 } 3253 3254 void Verifier::visitEHPadPredecessors(Instruction &I) { 3255 assert(I.isEHPad()); 3256 3257 BasicBlock *BB = I.getParent(); 3258 Function *F = BB->getParent(); 3259 3260 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3261 3262 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3263 // The landingpad instruction defines its parent as a landing pad block. The 3264 // landing pad block may be branched to only by the unwind edge of an 3265 // invoke. 3266 for (BasicBlock *PredBB : predecessors(BB)) { 3267 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3268 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3269 "Block containing LandingPadInst must be jumped to " 3270 "only by the unwind edge of an invoke.", 3271 LPI); 3272 } 3273 return; 3274 } 3275 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3276 if (!pred_empty(BB)) 3277 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3278 "Block containg CatchPadInst must be jumped to " 3279 "only by its catchswitch.", 3280 CPI); 3281 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3282 "Catchswitch cannot unwind to one of its catchpads", 3283 CPI->getCatchSwitch(), CPI); 3284 return; 3285 } 3286 3287 // Verify that each pred has a legal terminator with a legal to/from EH 3288 // pad relationship. 3289 Instruction *ToPad = &I; 3290 Value *ToPadParent = getParentPad(ToPad); 3291 for (BasicBlock *PredBB : predecessors(BB)) { 3292 TerminatorInst *TI = PredBB->getTerminator(); 3293 Value *FromPad; 3294 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3295 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3296 "EH pad must be jumped to via an unwind edge", ToPad, II); 3297 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3298 FromPad = Bundle->Inputs[0]; 3299 else 3300 FromPad = ConstantTokenNone::get(II->getContext()); 3301 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3302 FromPad = CRI->getOperand(0); 3303 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3304 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 3305 FromPad = CSI; 3306 } else { 3307 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 3308 } 3309 3310 // The edge may exit from zero or more nested pads. 3311 SmallSet<Value *, 8> Seen; 3312 for (;; FromPad = getParentPad(FromPad)) { 3313 Assert(FromPad != ToPad, 3314 "EH pad cannot handle exceptions raised within it", FromPad, TI); 3315 if (FromPad == ToPadParent) { 3316 // This is a legal unwind edge. 3317 break; 3318 } 3319 Assert(!isa<ConstantTokenNone>(FromPad), 3320 "A single unwind edge may only enter one EH pad", TI); 3321 Assert(Seen.insert(FromPad).second, 3322 "EH pad jumps through a cycle of pads", FromPad); 3323 } 3324 } 3325 } 3326 3327 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 3328 // The landingpad instruction is ill-formed if it doesn't have any clauses and 3329 // isn't a cleanup. 3330 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 3331 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 3332 3333 visitEHPadPredecessors(LPI); 3334 3335 if (!LandingPadResultTy) 3336 LandingPadResultTy = LPI.getType(); 3337 else 3338 Assert(LandingPadResultTy == LPI.getType(), 3339 "The landingpad instruction should have a consistent result type " 3340 "inside a function.", 3341 &LPI); 3342 3343 Function *F = LPI.getParent()->getParent(); 3344 Assert(F->hasPersonalityFn(), 3345 "LandingPadInst needs to be in a function with a personality.", &LPI); 3346 3347 // The landingpad instruction must be the first non-PHI instruction in the 3348 // block. 3349 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 3350 "LandingPadInst not the first non-PHI instruction in the block.", 3351 &LPI); 3352 3353 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 3354 Constant *Clause = LPI.getClause(i); 3355 if (LPI.isCatch(i)) { 3356 Assert(isa<PointerType>(Clause->getType()), 3357 "Catch operand does not have pointer type!", &LPI); 3358 } else { 3359 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 3360 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 3361 "Filter operand is not an array of constants!", &LPI); 3362 } 3363 } 3364 3365 visitInstruction(LPI); 3366 } 3367 3368 void Verifier::visitResumeInst(ResumeInst &RI) { 3369 Assert(RI.getFunction()->hasPersonalityFn(), 3370 "ResumeInst needs to be in a function with a personality.", &RI); 3371 3372 if (!LandingPadResultTy) 3373 LandingPadResultTy = RI.getValue()->getType(); 3374 else 3375 Assert(LandingPadResultTy == RI.getValue()->getType(), 3376 "The resume instruction should have a consistent result type " 3377 "inside a function.", 3378 &RI); 3379 3380 visitTerminatorInst(RI); 3381 } 3382 3383 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 3384 BasicBlock *BB = CPI.getParent(); 3385 3386 Function *F = BB->getParent(); 3387 Assert(F->hasPersonalityFn(), 3388 "CatchPadInst needs to be in a function with a personality.", &CPI); 3389 3390 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 3391 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 3392 CPI.getParentPad()); 3393 3394 // The catchpad instruction must be the first non-PHI instruction in the 3395 // block. 3396 Assert(BB->getFirstNonPHI() == &CPI, 3397 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 3398 3399 visitEHPadPredecessors(CPI); 3400 visitFuncletPadInst(CPI); 3401 } 3402 3403 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 3404 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 3405 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 3406 CatchReturn.getOperand(0)); 3407 3408 visitTerminatorInst(CatchReturn); 3409 } 3410 3411 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 3412 BasicBlock *BB = CPI.getParent(); 3413 3414 Function *F = BB->getParent(); 3415 Assert(F->hasPersonalityFn(), 3416 "CleanupPadInst needs to be in a function with a personality.", &CPI); 3417 3418 // The cleanuppad instruction must be the first non-PHI instruction in the 3419 // block. 3420 Assert(BB->getFirstNonPHI() == &CPI, 3421 "CleanupPadInst not the first non-PHI instruction in the block.", 3422 &CPI); 3423 3424 auto *ParentPad = CPI.getParentPad(); 3425 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3426 "CleanupPadInst has an invalid parent.", &CPI); 3427 3428 visitEHPadPredecessors(CPI); 3429 visitFuncletPadInst(CPI); 3430 } 3431 3432 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 3433 User *FirstUser = nullptr; 3434 Value *FirstUnwindPad = nullptr; 3435 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 3436 SmallSet<FuncletPadInst *, 8> Seen; 3437 3438 while (!Worklist.empty()) { 3439 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 3440 Assert(Seen.insert(CurrentPad).second, 3441 "FuncletPadInst must not be nested within itself", CurrentPad); 3442 Value *UnresolvedAncestorPad = nullptr; 3443 for (User *U : CurrentPad->users()) { 3444 BasicBlock *UnwindDest; 3445 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 3446 UnwindDest = CRI->getUnwindDest(); 3447 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 3448 // We allow catchswitch unwind to caller to nest 3449 // within an outer pad that unwinds somewhere else, 3450 // because catchswitch doesn't have a nounwind variant. 3451 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 3452 if (CSI->unwindsToCaller()) 3453 continue; 3454 UnwindDest = CSI->getUnwindDest(); 3455 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 3456 UnwindDest = II->getUnwindDest(); 3457 } else if (isa<CallInst>(U)) { 3458 // Calls which don't unwind may be found inside funclet 3459 // pads that unwind somewhere else. We don't *require* 3460 // such calls to be annotated nounwind. 3461 continue; 3462 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 3463 // The unwind dest for a cleanup can only be found by 3464 // recursive search. Add it to the worklist, and we'll 3465 // search for its first use that determines where it unwinds. 3466 Worklist.push_back(CPI); 3467 continue; 3468 } else { 3469 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 3470 continue; 3471 } 3472 3473 Value *UnwindPad; 3474 bool ExitsFPI; 3475 if (UnwindDest) { 3476 UnwindPad = UnwindDest->getFirstNonPHI(); 3477 if (!cast<Instruction>(UnwindPad)->isEHPad()) 3478 continue; 3479 Value *UnwindParent = getParentPad(UnwindPad); 3480 // Ignore unwind edges that don't exit CurrentPad. 3481 if (UnwindParent == CurrentPad) 3482 continue; 3483 // Determine whether the original funclet pad is exited, 3484 // and if we are scanning nested pads determine how many 3485 // of them are exited so we can stop searching their 3486 // children. 3487 Value *ExitedPad = CurrentPad; 3488 ExitsFPI = false; 3489 do { 3490 if (ExitedPad == &FPI) { 3491 ExitsFPI = true; 3492 // Now we can resolve any ancestors of CurrentPad up to 3493 // FPI, but not including FPI since we need to make sure 3494 // to check all direct users of FPI for consistency. 3495 UnresolvedAncestorPad = &FPI; 3496 break; 3497 } 3498 Value *ExitedParent = getParentPad(ExitedPad); 3499 if (ExitedParent == UnwindParent) { 3500 // ExitedPad is the ancestor-most pad which this unwind 3501 // edge exits, so we can resolve up to it, meaning that 3502 // ExitedParent is the first ancestor still unresolved. 3503 UnresolvedAncestorPad = ExitedParent; 3504 break; 3505 } 3506 ExitedPad = ExitedParent; 3507 } while (!isa<ConstantTokenNone>(ExitedPad)); 3508 } else { 3509 // Unwinding to caller exits all pads. 3510 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 3511 ExitsFPI = true; 3512 UnresolvedAncestorPad = &FPI; 3513 } 3514 3515 if (ExitsFPI) { 3516 // This unwind edge exits FPI. Make sure it agrees with other 3517 // such edges. 3518 if (FirstUser) { 3519 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 3520 "pad must have the same unwind " 3521 "dest", 3522 &FPI, U, FirstUser); 3523 } else { 3524 FirstUser = U; 3525 FirstUnwindPad = UnwindPad; 3526 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 3527 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 3528 getParentPad(UnwindPad) == getParentPad(&FPI)) 3529 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U); 3530 } 3531 } 3532 // Make sure we visit all uses of FPI, but for nested pads stop as 3533 // soon as we know where they unwind to. 3534 if (CurrentPad != &FPI) 3535 break; 3536 } 3537 if (UnresolvedAncestorPad) { 3538 if (CurrentPad == UnresolvedAncestorPad) { 3539 // When CurrentPad is FPI itself, we don't mark it as resolved even if 3540 // we've found an unwind edge that exits it, because we need to verify 3541 // all direct uses of FPI. 3542 assert(CurrentPad == &FPI); 3543 continue; 3544 } 3545 // Pop off the worklist any nested pads that we've found an unwind 3546 // destination for. The pads on the worklist are the uncles, 3547 // great-uncles, etc. of CurrentPad. We've found an unwind destination 3548 // for all ancestors of CurrentPad up to but not including 3549 // UnresolvedAncestorPad. 3550 Value *ResolvedPad = CurrentPad; 3551 while (!Worklist.empty()) { 3552 Value *UnclePad = Worklist.back(); 3553 Value *AncestorPad = getParentPad(UnclePad); 3554 // Walk ResolvedPad up the ancestor list until we either find the 3555 // uncle's parent or the last resolved ancestor. 3556 while (ResolvedPad != AncestorPad) { 3557 Value *ResolvedParent = getParentPad(ResolvedPad); 3558 if (ResolvedParent == UnresolvedAncestorPad) { 3559 break; 3560 } 3561 ResolvedPad = ResolvedParent; 3562 } 3563 // If the resolved ancestor search didn't find the uncle's parent, 3564 // then the uncle is not yet resolved. 3565 if (ResolvedPad != AncestorPad) 3566 break; 3567 // This uncle is resolved, so pop it from the worklist. 3568 Worklist.pop_back(); 3569 } 3570 } 3571 } 3572 3573 if (FirstUnwindPad) { 3574 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 3575 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 3576 Value *SwitchUnwindPad; 3577 if (SwitchUnwindDest) 3578 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 3579 else 3580 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 3581 Assert(SwitchUnwindPad == FirstUnwindPad, 3582 "Unwind edges out of a catch must have the same unwind dest as " 3583 "the parent catchswitch", 3584 &FPI, FirstUser, CatchSwitch); 3585 } 3586 } 3587 3588 visitInstruction(FPI); 3589 } 3590 3591 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 3592 BasicBlock *BB = CatchSwitch.getParent(); 3593 3594 Function *F = BB->getParent(); 3595 Assert(F->hasPersonalityFn(), 3596 "CatchSwitchInst needs to be in a function with a personality.", 3597 &CatchSwitch); 3598 3599 // The catchswitch instruction must be the first non-PHI instruction in the 3600 // block. 3601 Assert(BB->getFirstNonPHI() == &CatchSwitch, 3602 "CatchSwitchInst not the first non-PHI instruction in the block.", 3603 &CatchSwitch); 3604 3605 auto *ParentPad = CatchSwitch.getParentPad(); 3606 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3607 "CatchSwitchInst has an invalid parent.", ParentPad); 3608 3609 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 3610 Instruction *I = UnwindDest->getFirstNonPHI(); 3611 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3612 "CatchSwitchInst must unwind to an EH block which is not a " 3613 "landingpad.", 3614 &CatchSwitch); 3615 3616 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 3617 if (getParentPad(I) == ParentPad) 3618 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 3619 } 3620 3621 Assert(CatchSwitch.getNumHandlers() != 0, 3622 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 3623 3624 for (BasicBlock *Handler : CatchSwitch.handlers()) { 3625 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 3626 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 3627 } 3628 3629 visitEHPadPredecessors(CatchSwitch); 3630 visitTerminatorInst(CatchSwitch); 3631 } 3632 3633 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 3634 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 3635 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 3636 CRI.getOperand(0)); 3637 3638 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 3639 Instruction *I = UnwindDest->getFirstNonPHI(); 3640 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3641 "CleanupReturnInst must unwind to an EH block which is not a " 3642 "landingpad.", 3643 &CRI); 3644 } 3645 3646 visitTerminatorInst(CRI); 3647 } 3648 3649 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 3650 Instruction *Op = cast<Instruction>(I.getOperand(i)); 3651 // If the we have an invalid invoke, don't try to compute the dominance. 3652 // We already reject it in the invoke specific checks and the dominance 3653 // computation doesn't handle multiple edges. 3654 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 3655 if (II->getNormalDest() == II->getUnwindDest()) 3656 return; 3657 } 3658 3659 // Quick check whether the def has already been encountered in the same block. 3660 // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI 3661 // uses are defined to happen on the incoming edge, not at the instruction. 3662 // 3663 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 3664 // wrapping an SSA value, assert that we've already encountered it. See 3665 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 3666 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 3667 return; 3668 3669 const Use &U = I.getOperandUse(i); 3670 Assert(DT.dominates(Op, U), 3671 "Instruction does not dominate all uses!", Op, &I); 3672 } 3673 3674 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 3675 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 3676 "apply only to pointer types", &I); 3677 Assert(isa<LoadInst>(I), 3678 "dereferenceable, dereferenceable_or_null apply only to load" 3679 " instructions, use attributes for calls or invokes", &I); 3680 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 3681 "take one operand!", &I); 3682 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 3683 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 3684 "dereferenceable_or_null metadata value must be an i64!", &I); 3685 } 3686 3687 /// Verify that \p BaseNode can be used as the "base type" in the struct-path 3688 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a 3689 /// struct-type node describing an aggregate data structure (like a struct). 3690 Verifier::TBAABaseNodeSummary Verifier::verifyTBAABaseNode(Instruction &I, 3691 MDNode *BaseNode) { 3692 if (BaseNode->getNumOperands() < 2) { 3693 CheckFailed("Base nodes must have at least two operands", &I, BaseNode); 3694 return {true, ~0u}; 3695 } 3696 3697 auto Itr = TBAABaseNodes.find(BaseNode); 3698 if (Itr != TBAABaseNodes.end()) 3699 return Itr->second; 3700 3701 auto Result = verifyTBAABaseNodeImpl(I, BaseNode); 3702 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result}); 3703 (void)InsertResult; 3704 assert(InsertResult.second && "We just checked!"); 3705 return Result; 3706 } 3707 3708 Verifier::TBAABaseNodeSummary 3709 Verifier::verifyTBAABaseNodeImpl(Instruction &I, MDNode *BaseNode) { 3710 const Verifier::TBAABaseNodeSummary InvalidNode = {true, ~0u}; 3711 3712 if (BaseNode->getNumOperands() == 2) { 3713 // This is a scalar base node. 3714 if (!BaseNode->getOperand(0) || !BaseNode->getOperand(1)) { 3715 CheckFailed("Null operands in scalar type nodes!", &I, BaseNode); 3716 return InvalidNode; 3717 } 3718 if (!isa<MDNode>(BaseNode->getOperand(1))) { 3719 CheckFailed("Invalid parent operand in scalar TBAA node", &I, BaseNode); 3720 return InvalidNode; 3721 } 3722 if (!isa<MDString>(BaseNode->getOperand(0))) { 3723 CheckFailed("Invalid name operand in scalar TBAA node", &I, BaseNode); 3724 return InvalidNode; 3725 } 3726 3727 // Scalar nodes can only be accessed at offset 0. 3728 return {false, 0}; 3729 } 3730 3731 if (BaseNode->getNumOperands() % 2 != 1) { 3732 CheckFailed("Struct tag nodes must have an odd number of operands!", 3733 BaseNode); 3734 return InvalidNode; 3735 } 3736 3737 bool Failed = false; 3738 3739 Optional<APInt> PrevOffset; 3740 unsigned BitWidth = ~0u; 3741 3742 // We've already checked that BaseNode is not a degenerate root node with one 3743 // operand in \c verifyTBAABaseNode, so this loop should run at least once. 3744 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) { 3745 const MDOperand &FieldTy = BaseNode->getOperand(Idx); 3746 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1); 3747 if (!isa<MDNode>(FieldTy)) { 3748 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode); 3749 Failed = true; 3750 continue; 3751 } 3752 3753 auto *OffsetEntryCI = 3754 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset); 3755 if (!OffsetEntryCI) { 3756 CheckFailed("Offset entries must be constants!", &I, BaseNode); 3757 Failed = true; 3758 continue; 3759 } 3760 3761 if (BitWidth == ~0u) 3762 BitWidth = OffsetEntryCI->getBitWidth(); 3763 3764 if (OffsetEntryCI->getBitWidth() != BitWidth) { 3765 CheckFailed( 3766 "Bitwidth between the offsets and struct type entries must match", &I, 3767 BaseNode); 3768 Failed = true; 3769 continue; 3770 } 3771 3772 // NB! As far as I can tell, we generate a non-strictly increasing offset 3773 // sequence only from structs that have zero size bit fields. When 3774 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we 3775 // pick the field lexically the latest in struct type metadata node. This 3776 // mirrors the actual behavior of the alias analysis implementation. 3777 bool IsAscending = 3778 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue()); 3779 3780 if (!IsAscending) { 3781 CheckFailed("Offsets must be increasing!", &I, BaseNode); 3782 Failed = true; 3783 } 3784 3785 PrevOffset = OffsetEntryCI->getValue(); 3786 } 3787 3788 return Failed ? InvalidNode : Verifier::TBAABaseNodeSummary(false, BitWidth); 3789 } 3790 3791 static bool IsRootTBAANode(const MDNode *MD) { 3792 return MD->getNumOperands() < 2; 3793 } 3794 3795 static bool IsScalarTBAANodeImpl(const MDNode *MD, 3796 SmallPtrSetImpl<const MDNode *> &Visited) { 3797 if (MD->getNumOperands() == 2) 3798 return true; 3799 3800 if (MD->getNumOperands() != 3) 3801 return false; 3802 3803 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 3804 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0)))) 3805 return false; 3806 3807 auto *Parent = dyn_cast<MDNode>(MD->getOperand(1)); 3808 return Visited.insert(Parent).second && 3809 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited)); 3810 } 3811 3812 static bool IsScalarTBAANode(const MDNode *MD) { 3813 SmallPtrSet<const MDNode *, 4> Visited; 3814 return IsScalarTBAANodeImpl(MD, Visited); 3815 } 3816 3817 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p 3818 /// Offset in place to be the offset within the field node returned. 3819 /// 3820 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode. 3821 MDNode *Verifier::getFieldNodeFromTBAABaseNode(Instruction &I, MDNode *BaseNode, 3822 APInt &Offset) { 3823 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!"); 3824 3825 // Scalar nodes have only one possible "field" -- their parent in the access 3826 // hierarchy. Offset must be zero at this point, but our caller is supposed 3827 // to Assert that. 3828 if (BaseNode->getNumOperands() == 2) 3829 return cast<MDNode>(BaseNode->getOperand(1)); 3830 3831 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) { 3832 auto *OffsetEntryCI = 3833 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1)); 3834 if (OffsetEntryCI->getValue().ugt(Offset)) { 3835 if (Idx == 1) { 3836 CheckFailed("Could not find TBAA parent in struct type node", &I, 3837 BaseNode, &Offset); 3838 return nullptr; 3839 } 3840 3841 auto *PrevOffsetEntryCI = 3842 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx - 1)); 3843 Offset -= PrevOffsetEntryCI->getValue(); 3844 return cast<MDNode>(BaseNode->getOperand(Idx - 2)); 3845 } 3846 } 3847 3848 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>( 3849 BaseNode->getOperand(BaseNode->getNumOperands() - 1)); 3850 3851 Offset -= LastOffsetEntryCI->getValue(); 3852 return cast<MDNode>(BaseNode->getOperand(BaseNode->getNumOperands() - 2)); 3853 } 3854 3855 void Verifier::visitTBAAMetadata(Instruction &I, MDNode *MD) { 3856 bool IsStructPathTBAA = 3857 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 3858 3859 Assert(IsStructPathTBAA, 3860 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", 3861 &I); 3862 3863 Assert(MD->getNumOperands() < 5, 3864 "Struct tag metadata must have either 3 or 4 operands", &I, MD); 3865 3866 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0)); 3867 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 3868 3869 if (MD->getNumOperands() == 4) { 3870 auto *IsImmutableCI = 3871 mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(3)); 3872 Assert(IsImmutableCI, 3873 "Immutability tag on struct tag metadata must be a constant", &I, 3874 MD); 3875 Assert(IsImmutableCI->isZero() || IsImmutableCI->isOne(), 3876 "Immutability part of the struct tag metadata must be either 0 or 1", 3877 &I, MD); 3878 } 3879 3880 Assert(BaseNode && AccessType, 3881 "Malformed struct tag metadata: base and access-type " 3882 "should be non-null and point to Metadata nodes", 3883 &I, MD, BaseNode, AccessType); 3884 3885 Assert(IsScalarTBAANode(AccessType), "Access type node must be scalar", &I, 3886 MD, AccessType); 3887 3888 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2)); 3889 Assert(OffsetCI, "Offset must be constant integer", &I, MD); 3890 3891 APInt Offset = OffsetCI->getValue(); 3892 bool SeenAccessTypeInPath = false; 3893 3894 SmallPtrSet<MDNode *, 4> StructPath; 3895 3896 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode); 3897 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset)) { 3898 if (!StructPath.insert(BaseNode).second) { 3899 CheckFailed("Cycle detected in struct path", &I, MD); 3900 return; 3901 } 3902 3903 bool Invalid; 3904 unsigned BaseNodeBitWidth; 3905 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode); 3906 3907 // If the base node is invalid in itself, then we've already printed all the 3908 // errors we wanted to print. 3909 if (Invalid) 3910 return; 3911 3912 SeenAccessTypeInPath |= BaseNode == AccessType; 3913 3914 if (IsScalarTBAANode(BaseNode) || BaseNode == AccessType) 3915 Assert(Offset == 0, "Offset not zero at the point of scalar access", &I, 3916 MD, &Offset); 3917 3918 Assert(BaseNodeBitWidth == Offset.getBitWidth() || 3919 (BaseNodeBitWidth == 0 && Offset == 0), 3920 "Access bit-width not the same as description bit-width", &I, MD, 3921 BaseNodeBitWidth, Offset.getBitWidth()); 3922 } 3923 3924 Assert(SeenAccessTypeInPath, "Did not see access type in access path!", &I, 3925 MD); 3926 } 3927 3928 /// verifyInstruction - Verify that an instruction is well formed. 3929 /// 3930 void Verifier::visitInstruction(Instruction &I) { 3931 BasicBlock *BB = I.getParent(); 3932 Assert(BB, "Instruction not embedded in basic block!", &I); 3933 3934 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 3935 for (User *U : I.users()) { 3936 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 3937 "Only PHI nodes may reference their own value!", &I); 3938 } 3939 } 3940 3941 // Check that void typed values don't have names 3942 Assert(!I.getType()->isVoidTy() || !I.hasName(), 3943 "Instruction has a name, but provides a void value!", &I); 3944 3945 // Check that the return value of the instruction is either void or a legal 3946 // value type. 3947 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 3948 "Instruction returns a non-scalar type!", &I); 3949 3950 // Check that the instruction doesn't produce metadata. Calls are already 3951 // checked against the callee type. 3952 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 3953 "Invalid use of metadata!", &I); 3954 3955 // Check that all uses of the instruction, if they are instructions 3956 // themselves, actually have parent basic blocks. If the use is not an 3957 // instruction, it is an error! 3958 for (Use &U : I.uses()) { 3959 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 3960 Assert(Used->getParent() != nullptr, 3961 "Instruction referencing" 3962 " instruction not embedded in a basic block!", 3963 &I, Used); 3964 else { 3965 CheckFailed("Use of instruction is not an instruction!", U); 3966 return; 3967 } 3968 } 3969 3970 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 3971 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 3972 3973 // Check to make sure that only first-class-values are operands to 3974 // instructions. 3975 if (!I.getOperand(i)->getType()->isFirstClassType()) { 3976 Assert(false, "Instruction operands must be first-class values!", &I); 3977 } 3978 3979 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 3980 // Check to make sure that the "address of" an intrinsic function is never 3981 // taken. 3982 Assert( 3983 !F->isIntrinsic() || 3984 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0), 3985 "Cannot take the address of an intrinsic!", &I); 3986 Assert( 3987 !F->isIntrinsic() || isa<CallInst>(I) || 3988 F->getIntrinsicID() == Intrinsic::donothing || 3989 F->getIntrinsicID() == Intrinsic::coro_resume || 3990 F->getIntrinsicID() == Intrinsic::coro_destroy || 3991 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 3992 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 3993 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint, 3994 "Cannot invoke an intrinsic other than donothing, patchpoint, " 3995 "statepoint, coro_resume or coro_destroy", 3996 &I); 3997 Assert(F->getParent() == &M, "Referencing function in another module!", 3998 &I, &M, F, F->getParent()); 3999 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 4000 Assert(OpBB->getParent() == BB->getParent(), 4001 "Referring to a basic block in another function!", &I); 4002 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 4003 Assert(OpArg->getParent() == BB->getParent(), 4004 "Referring to an argument in another function!", &I); 4005 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 4006 Assert(GV->getParent() == &M, "Referencing global in another module!", &I, 4007 &M, GV, GV->getParent()); 4008 } else if (isa<Instruction>(I.getOperand(i))) { 4009 verifyDominatesUse(I, i); 4010 } else if (isa<InlineAsm>(I.getOperand(i))) { 4011 Assert((i + 1 == e && isa<CallInst>(I)) || 4012 (i + 3 == e && isa<InvokeInst>(I)), 4013 "Cannot take the address of an inline asm!", &I); 4014 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 4015 if (CE->getType()->isPtrOrPtrVectorTy() || 4016 !DL.getNonIntegralAddressSpaces().empty()) { 4017 // If we have a ConstantExpr pointer, we need to see if it came from an 4018 // illegal bitcast. If the datalayout string specifies non-integral 4019 // address spaces then we also need to check for illegal ptrtoint and 4020 // inttoptr expressions. 4021 visitConstantExprsRecursively(CE); 4022 } 4023 } 4024 } 4025 4026 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 4027 Assert(I.getType()->isFPOrFPVectorTy(), 4028 "fpmath requires a floating point result!", &I); 4029 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 4030 if (ConstantFP *CFP0 = 4031 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 4032 const APFloat &Accuracy = CFP0->getValueAPF(); 4033 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle, 4034 "fpmath accuracy must have float type", &I); 4035 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 4036 "fpmath accuracy not a positive number!", &I); 4037 } else { 4038 Assert(false, "invalid fpmath accuracy!", &I); 4039 } 4040 } 4041 4042 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 4043 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 4044 "Ranges are only for loads, calls and invokes!", &I); 4045 visitRangeMetadata(I, Range, I.getType()); 4046 } 4047 4048 if (I.getMetadata(LLVMContext::MD_nonnull)) { 4049 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 4050 &I); 4051 Assert(isa<LoadInst>(I), 4052 "nonnull applies only to load instructions, use attributes" 4053 " for calls or invokes", 4054 &I); 4055 } 4056 4057 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 4058 visitDereferenceableMetadata(I, MD); 4059 4060 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 4061 visitDereferenceableMetadata(I, MD); 4062 4063 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) { 4064 Assert(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 4065 isa<VAArgInst>(I), 4066 "TBAA is only for loads, stores and calls!", &I); 4067 visitTBAAMetadata(I, TBAA); 4068 } 4069 4070 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 4071 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 4072 &I); 4073 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 4074 "use attributes for calls or invokes", &I); 4075 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 4076 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 4077 Assert(CI && CI->getType()->isIntegerTy(64), 4078 "align metadata value must be an i64!", &I); 4079 uint64_t Align = CI->getZExtValue(); 4080 Assert(isPowerOf2_64(Align), 4081 "align metadata value must be a power of 2!", &I); 4082 Assert(Align <= Value::MaximumAlignment, 4083 "alignment is larger that implementation defined limit", &I); 4084 } 4085 4086 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 4087 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 4088 visitMDNode(*N); 4089 } 4090 4091 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) 4092 verifyFragmentExpression(*DII); 4093 4094 InstsInThisBlock.insert(&I); 4095 } 4096 4097 /// Allow intrinsics to be verified in different ways. 4098 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) { 4099 Function *IF = CS.getCalledFunction(); 4100 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 4101 IF); 4102 4103 // Verify that the intrinsic prototype lines up with what the .td files 4104 // describe. 4105 FunctionType *IFTy = IF->getFunctionType(); 4106 bool IsVarArg = IFTy->isVarArg(); 4107 4108 SmallVector<Intrinsic::IITDescriptor, 8> Table; 4109 getIntrinsicInfoTableEntries(ID, Table); 4110 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 4111 4112 SmallVector<Type *, 4> ArgTys; 4113 Assert(!Intrinsic::matchIntrinsicType(IFTy->getReturnType(), 4114 TableRef, ArgTys), 4115 "Intrinsic has incorrect return type!", IF); 4116 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 4117 Assert(!Intrinsic::matchIntrinsicType(IFTy->getParamType(i), 4118 TableRef, ArgTys), 4119 "Intrinsic has incorrect argument type!", IF); 4120 4121 // Verify if the intrinsic call matches the vararg property. 4122 if (IsVarArg) 4123 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4124 "Intrinsic was not defined with variable arguments!", IF); 4125 else 4126 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4127 "Callsite was not defined with variable arguments!", IF); 4128 4129 // All descriptors should be absorbed by now. 4130 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 4131 4132 // Now that we have the intrinsic ID and the actual argument types (and we 4133 // know they are legal for the intrinsic!) get the intrinsic name through the 4134 // usual means. This allows us to verify the mangling of argument types into 4135 // the name. 4136 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 4137 Assert(ExpectedName == IF->getName(), 4138 "Intrinsic name not mangled correctly for type arguments! " 4139 "Should be: " + 4140 ExpectedName, 4141 IF); 4142 4143 // If the intrinsic takes MDNode arguments, verify that they are either global 4144 // or are local to *this* function. 4145 for (Value *V : CS.args()) 4146 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 4147 visitMetadataAsValue(*MD, CS.getCaller()); 4148 4149 switch (ID) { 4150 default: 4151 break; 4152 case Intrinsic::coro_id: { 4153 auto *InfoArg = CS.getArgOperand(3)->stripPointerCasts(); 4154 if (isa<ConstantPointerNull>(InfoArg)) 4155 break; 4156 auto *GV = dyn_cast<GlobalVariable>(InfoArg); 4157 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(), 4158 "info argument of llvm.coro.begin must refer to an initialized " 4159 "constant"); 4160 Constant *Init = GV->getInitializer(); 4161 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init), 4162 "info argument of llvm.coro.begin must refer to either a struct or " 4163 "an array"); 4164 break; 4165 } 4166 case Intrinsic::ctlz: // llvm.ctlz 4167 case Intrinsic::cttz: // llvm.cttz 4168 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 4169 "is_zero_undef argument of bit counting intrinsics must be a " 4170 "constant int", 4171 CS); 4172 break; 4173 case Intrinsic::dbg_declare: // llvm.dbg.declare 4174 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)), 4175 "invalid llvm.dbg.declare intrinsic call 1", CS); 4176 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction())); 4177 break; 4178 case Intrinsic::dbg_value: // llvm.dbg.value 4179 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction())); 4180 break; 4181 case Intrinsic::memcpy: 4182 case Intrinsic::memmove: 4183 case Intrinsic::memset: { 4184 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3)); 4185 Assert(AlignCI, 4186 "alignment argument of memory intrinsics must be a constant int", 4187 CS); 4188 const APInt &AlignVal = AlignCI->getValue(); 4189 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(), 4190 "alignment argument of memory intrinsics must be a power of 2", CS); 4191 Assert(isa<ConstantInt>(CS.getArgOperand(4)), 4192 "isvolatile argument of memory intrinsics must be a constant int", 4193 CS); 4194 break; 4195 } 4196 case Intrinsic::gcroot: 4197 case Intrinsic::gcwrite: 4198 case Intrinsic::gcread: 4199 if (ID == Intrinsic::gcroot) { 4200 AllocaInst *AI = 4201 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts()); 4202 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS); 4203 Assert(isa<Constant>(CS.getArgOperand(1)), 4204 "llvm.gcroot parameter #2 must be a constant.", CS); 4205 if (!AI->getAllocatedType()->isPointerTy()) { 4206 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)), 4207 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4208 "or argument #2 must be a non-null constant.", 4209 CS); 4210 } 4211 } 4212 4213 Assert(CS.getParent()->getParent()->hasGC(), 4214 "Enclosing function does not use GC.", CS); 4215 break; 4216 case Intrinsic::init_trampoline: 4217 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()), 4218 "llvm.init_trampoline parameter #2 must resolve to a function.", 4219 CS); 4220 break; 4221 case Intrinsic::prefetch: 4222 Assert(isa<ConstantInt>(CS.getArgOperand(1)) && 4223 isa<ConstantInt>(CS.getArgOperand(2)) && 4224 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 && 4225 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4, 4226 "invalid arguments to llvm.prefetch", CS); 4227 break; 4228 case Intrinsic::stackprotector: 4229 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()), 4230 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS); 4231 break; 4232 case Intrinsic::lifetime_start: 4233 case Intrinsic::lifetime_end: 4234 case Intrinsic::invariant_start: 4235 Assert(isa<ConstantInt>(CS.getArgOperand(0)), 4236 "size argument of memory use markers must be a constant integer", 4237 CS); 4238 break; 4239 case Intrinsic::invariant_end: 4240 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 4241 "llvm.invariant.end parameter #2 must be a constant integer", CS); 4242 break; 4243 4244 case Intrinsic::localescape: { 4245 BasicBlock *BB = CS.getParent(); 4246 Assert(BB == &BB->getParent()->front(), 4247 "llvm.localescape used outside of entry block", CS); 4248 Assert(!SawFrameEscape, 4249 "multiple calls to llvm.localescape in one function", CS); 4250 for (Value *Arg : CS.args()) { 4251 if (isa<ConstantPointerNull>(Arg)) 4252 continue; // Null values are allowed as placeholders. 4253 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4254 Assert(AI && AI->isStaticAlloca(), 4255 "llvm.localescape only accepts static allocas", CS); 4256 } 4257 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands(); 4258 SawFrameEscape = true; 4259 break; 4260 } 4261 case Intrinsic::localrecover: { 4262 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts(); 4263 Function *Fn = dyn_cast<Function>(FnArg); 4264 Assert(Fn && !Fn->isDeclaration(), 4265 "llvm.localrecover first " 4266 "argument must be function defined in this module", 4267 CS); 4268 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2)); 4269 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int", 4270 CS); 4271 auto &Entry = FrameEscapeInfo[Fn]; 4272 Entry.second = unsigned( 4273 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4274 break; 4275 } 4276 4277 case Intrinsic::experimental_gc_statepoint: 4278 Assert(!CS.isInlineAsm(), 4279 "gc.statepoint support for inline assembly unimplemented", CS); 4280 Assert(CS.getParent()->getParent()->hasGC(), 4281 "Enclosing function does not use GC.", CS); 4282 4283 verifyStatepoint(CS); 4284 break; 4285 case Intrinsic::experimental_gc_result: { 4286 Assert(CS.getParent()->getParent()->hasGC(), 4287 "Enclosing function does not use GC.", CS); 4288 // Are we tied to a statepoint properly? 4289 CallSite StatepointCS(CS.getArgOperand(0)); 4290 const Function *StatepointFn = 4291 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr; 4292 Assert(StatepointFn && StatepointFn->isDeclaration() && 4293 StatepointFn->getIntrinsicID() == 4294 Intrinsic::experimental_gc_statepoint, 4295 "gc.result operand #1 must be from a statepoint", CS, 4296 CS.getArgOperand(0)); 4297 4298 // Assert that result type matches wrapped callee. 4299 const Value *Target = StatepointCS.getArgument(2); 4300 auto *PT = cast<PointerType>(Target->getType()); 4301 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4302 Assert(CS.getType() == TargetFuncType->getReturnType(), 4303 "gc.result result type does not match wrapped callee", CS); 4304 break; 4305 } 4306 case Intrinsic::experimental_gc_relocate: { 4307 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS); 4308 4309 Assert(isa<PointerType>(CS.getType()->getScalarType()), 4310 "gc.relocate must return a pointer or a vector of pointers", CS); 4311 4312 // Check that this relocate is correctly tied to the statepoint 4313 4314 // This is case for relocate on the unwinding path of an invoke statepoint 4315 if (LandingPadInst *LandingPad = 4316 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) { 4317 4318 const BasicBlock *InvokeBB = 4319 LandingPad->getParent()->getUniquePredecessor(); 4320 4321 // Landingpad relocates should have only one predecessor with invoke 4322 // statepoint terminator 4323 Assert(InvokeBB, "safepoints should have unique landingpads", 4324 LandingPad->getParent()); 4325 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4326 InvokeBB); 4327 Assert(isStatepoint(InvokeBB->getTerminator()), 4328 "gc relocate should be linked to a statepoint", InvokeBB); 4329 } 4330 else { 4331 // In all other cases relocate should be tied to the statepoint directly. 4332 // This covers relocates on a normal return path of invoke statepoint and 4333 // relocates of a call statepoint. 4334 auto Token = CS.getArgOperand(0); 4335 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)), 4336 "gc relocate is incorrectly tied to the statepoint", CS, Token); 4337 } 4338 4339 // Verify rest of the relocate arguments. 4340 4341 ImmutableCallSite StatepointCS( 4342 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint()); 4343 4344 // Both the base and derived must be piped through the safepoint. 4345 Value* Base = CS.getArgOperand(1); 4346 Assert(isa<ConstantInt>(Base), 4347 "gc.relocate operand #2 must be integer offset", CS); 4348 4349 Value* Derived = CS.getArgOperand(2); 4350 Assert(isa<ConstantInt>(Derived), 4351 "gc.relocate operand #3 must be integer offset", CS); 4352 4353 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 4354 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 4355 // Check the bounds 4356 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(), 4357 "gc.relocate: statepoint base index out of bounds", CS); 4358 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(), 4359 "gc.relocate: statepoint derived index out of bounds", CS); 4360 4361 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters' 4362 // section of the statepoint's argument. 4363 Assert(StatepointCS.arg_size() > 0, 4364 "gc.statepoint: insufficient arguments"); 4365 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)), 4366 "gc.statement: number of call arguments must be constant integer"); 4367 const unsigned NumCallArgs = 4368 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue(); 4369 Assert(StatepointCS.arg_size() > NumCallArgs + 5, 4370 "gc.statepoint: mismatch in number of call arguments"); 4371 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)), 4372 "gc.statepoint: number of transition arguments must be " 4373 "a constant integer"); 4374 const int NumTransitionArgs = 4375 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)) 4376 ->getZExtValue(); 4377 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1; 4378 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)), 4379 "gc.statepoint: number of deoptimization arguments must be " 4380 "a constant integer"); 4381 const int NumDeoptArgs = 4382 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)) 4383 ->getZExtValue(); 4384 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs; 4385 const int GCParamArgsEnd = StatepointCS.arg_size(); 4386 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd, 4387 "gc.relocate: statepoint base index doesn't fall within the " 4388 "'gc parameters' section of the statepoint call", 4389 CS); 4390 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd, 4391 "gc.relocate: statepoint derived index doesn't fall within the " 4392 "'gc parameters' section of the statepoint call", 4393 CS); 4394 4395 // Relocated value must be either a pointer type or vector-of-pointer type, 4396 // but gc_relocate does not need to return the same pointer type as the 4397 // relocated pointer. It can be casted to the correct type later if it's 4398 // desired. However, they must have the same address space and 'vectorness' 4399 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction()); 4400 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(), 4401 "gc.relocate: relocated value must be a gc pointer", CS); 4402 4403 auto ResultType = CS.getType(); 4404 auto DerivedType = Relocate.getDerivedPtr()->getType(); 4405 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 4406 "gc.relocate: vector relocates to vector and pointer to pointer", 4407 CS); 4408 Assert( 4409 ResultType->getPointerAddressSpace() == 4410 DerivedType->getPointerAddressSpace(), 4411 "gc.relocate: relocating a pointer shouldn't change its address space", 4412 CS); 4413 break; 4414 } 4415 case Intrinsic::eh_exceptioncode: 4416 case Intrinsic::eh_exceptionpointer: { 4417 Assert(isa<CatchPadInst>(CS.getArgOperand(0)), 4418 "eh.exceptionpointer argument must be a catchpad", CS); 4419 break; 4420 } 4421 case Intrinsic::masked_load: { 4422 Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS); 4423 4424 Value *Ptr = CS.getArgOperand(0); 4425 //Value *Alignment = CS.getArgOperand(1); 4426 Value *Mask = CS.getArgOperand(2); 4427 Value *PassThru = CS.getArgOperand(3); 4428 Assert(Mask->getType()->isVectorTy(), 4429 "masked_load: mask must be vector", CS); 4430 4431 // DataTy is the overloaded type 4432 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4433 Assert(DataTy == CS.getType(), 4434 "masked_load: return must match pointer type", CS); 4435 Assert(PassThru->getType() == DataTy, 4436 "masked_load: pass through and data type must match", CS); 4437 Assert(Mask->getType()->getVectorNumElements() == 4438 DataTy->getVectorNumElements(), 4439 "masked_load: vector mask must be same length as data", CS); 4440 break; 4441 } 4442 case Intrinsic::masked_store: { 4443 Value *Val = CS.getArgOperand(0); 4444 Value *Ptr = CS.getArgOperand(1); 4445 //Value *Alignment = CS.getArgOperand(2); 4446 Value *Mask = CS.getArgOperand(3); 4447 Assert(Mask->getType()->isVectorTy(), 4448 "masked_store: mask must be vector", CS); 4449 4450 // DataTy is the overloaded type 4451 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4452 Assert(DataTy == Val->getType(), 4453 "masked_store: storee must match pointer type", CS); 4454 Assert(Mask->getType()->getVectorNumElements() == 4455 DataTy->getVectorNumElements(), 4456 "masked_store: vector mask must be same length as data", CS); 4457 break; 4458 } 4459 4460 case Intrinsic::experimental_guard: { 4461 Assert(CS.isCall(), "experimental_guard cannot be invoked", CS); 4462 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4463 "experimental_guard must have exactly one " 4464 "\"deopt\" operand bundle"); 4465 break; 4466 } 4467 4468 case Intrinsic::experimental_deoptimize: { 4469 Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS); 4470 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4471 "experimental_deoptimize must have exactly one " 4472 "\"deopt\" operand bundle"); 4473 Assert(CS.getType() == CS.getInstruction()->getFunction()->getReturnType(), 4474 "experimental_deoptimize return type must match caller return type"); 4475 4476 if (CS.isCall()) { 4477 auto *DeoptCI = CS.getInstruction(); 4478 auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode()); 4479 Assert(RI, 4480 "calls to experimental_deoptimize must be followed by a return"); 4481 4482 if (!CS.getType()->isVoidTy() && RI) 4483 Assert(RI->getReturnValue() == DeoptCI, 4484 "calls to experimental_deoptimize must be followed by a return " 4485 "of the value computed by experimental_deoptimize"); 4486 } 4487 4488 break; 4489 } 4490 }; 4491 } 4492 4493 /// \brief Carefully grab the subprogram from a local scope. 4494 /// 4495 /// This carefully grabs the subprogram from a local scope, avoiding the 4496 /// built-in assertions that would typically fire. 4497 static DISubprogram *getSubprogram(Metadata *LocalScope) { 4498 if (!LocalScope) 4499 return nullptr; 4500 4501 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 4502 return SP; 4503 4504 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 4505 return getSubprogram(LB->getRawScope()); 4506 4507 // Just return null; broken scope chains are checked elsewhere. 4508 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 4509 return nullptr; 4510 } 4511 4512 template <class DbgIntrinsicTy> 4513 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) { 4514 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata(); 4515 AssertDI(isa<ValueAsMetadata>(MD) || 4516 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 4517 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 4518 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 4519 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 4520 DII.getRawVariable()); 4521 AssertDI(isa<DIExpression>(DII.getRawExpression()), 4522 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 4523 DII.getRawExpression()); 4524 4525 // Ignore broken !dbg attachments; they're checked elsewhere. 4526 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 4527 if (!isa<DILocation>(N)) 4528 return; 4529 4530 BasicBlock *BB = DII.getParent(); 4531 Function *F = BB ? BB->getParent() : nullptr; 4532 4533 // The scopes for variables and !dbg attachments must agree. 4534 DILocalVariable *Var = DII.getVariable(); 4535 DILocation *Loc = DII.getDebugLoc(); 4536 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 4537 &DII, BB, F); 4538 4539 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 4540 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 4541 if (!VarSP || !LocSP) 4542 return; // Broken scope chains are checked elsewhere. 4543 4544 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 4545 " variable and !dbg attachment", 4546 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 4547 Loc->getScope()->getSubprogram()); 4548 } 4549 4550 static uint64_t getVariableSize(const DILocalVariable &V) { 4551 // Be careful of broken types (checked elsewhere). 4552 const Metadata *RawType = V.getRawType(); 4553 while (RawType) { 4554 // Try to get the size directly. 4555 if (auto *T = dyn_cast<DIType>(RawType)) 4556 if (uint64_t Size = T->getSizeInBits()) 4557 return Size; 4558 4559 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 4560 // Look at the base type. 4561 RawType = DT->getRawBaseType(); 4562 continue; 4563 } 4564 4565 // Missing type or size. 4566 break; 4567 } 4568 4569 // Fail gracefully. 4570 return 0; 4571 } 4572 4573 void Verifier::verifyFragmentExpression(const DbgInfoIntrinsic &I) { 4574 DILocalVariable *V; 4575 DIExpression *E; 4576 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) { 4577 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable()); 4578 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression()); 4579 } else { 4580 auto *DDI = cast<DbgDeclareInst>(&I); 4581 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable()); 4582 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression()); 4583 } 4584 4585 // We don't know whether this intrinsic verified correctly. 4586 if (!V || !E || !E->isValid()) 4587 return; 4588 4589 // Nothing to do if this isn't a bit piece expression. 4590 if (!E->isFragment()) 4591 return; 4592 4593 // The frontend helps out GDB by emitting the members of local anonymous 4594 // unions as artificial local variables with shared storage. When SROA splits 4595 // the storage for artificial local variables that are smaller than the entire 4596 // union, the overhang piece will be outside of the allotted space for the 4597 // variable and this check fails. 4598 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 4599 if (V->isArtificial()) 4600 return; 4601 4602 // If there's no size, the type is broken, but that should be checked 4603 // elsewhere. 4604 uint64_t VarSize = getVariableSize(*V); 4605 if (!VarSize) 4606 return; 4607 4608 unsigned FragSize = E->getFragmentSizeInBits(); 4609 unsigned FragOffset = E->getFragmentOffsetInBits(); 4610 AssertDI(FragSize + FragOffset <= VarSize, 4611 "fragment is larger than or outside of variable", &I, V, E); 4612 AssertDI(FragSize != VarSize, "fragment covers entire variable", &I, V, E); 4613 } 4614 4615 void Verifier::verifyCompileUnits() { 4616 auto *CUs = M.getNamedMetadata("llvm.dbg.cu"); 4617 SmallPtrSet<const Metadata *, 2> Listed; 4618 if (CUs) 4619 Listed.insert(CUs->op_begin(), CUs->op_end()); 4620 AssertDI( 4621 all_of(CUVisited, 4622 [&Listed](const Metadata *CU) { return Listed.count(CU); }), 4623 "All DICompileUnits must be listed in llvm.dbg.cu"); 4624 CUVisited.clear(); 4625 } 4626 4627 void Verifier::verifyDeoptimizeCallingConvs() { 4628 if (DeoptimizeDeclarations.empty()) 4629 return; 4630 4631 const Function *First = DeoptimizeDeclarations[0]; 4632 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 4633 Assert(First->getCallingConv() == F->getCallingConv(), 4634 "All llvm.experimental.deoptimize declarations must have the same " 4635 "calling convention", 4636 First, F); 4637 } 4638 } 4639 4640 //===----------------------------------------------------------------------===// 4641 // Implement the public interfaces to this file... 4642 //===----------------------------------------------------------------------===// 4643 4644 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 4645 Function &F = const_cast<Function &>(f); 4646 4647 // Don't use a raw_null_ostream. Printing IR is expensive. 4648 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent()); 4649 4650 // Note that this function's return value is inverted from what you would 4651 // expect of a function called "verify". 4652 return !V.verify(F); 4653 } 4654 4655 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 4656 bool *BrokenDebugInfo) { 4657 // Don't use a raw_null_ostream. Printing IR is expensive. 4658 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M); 4659 4660 bool Broken = false; 4661 for (const Function &F : M) 4662 Broken |= !V.verify(F); 4663 4664 Broken |= !V.verify(); 4665 if (BrokenDebugInfo) 4666 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 4667 // Note that this function's return value is inverted from what you would 4668 // expect of a function called "verify". 4669 return Broken; 4670 } 4671 4672 namespace { 4673 4674 struct VerifierLegacyPass : public FunctionPass { 4675 static char ID; 4676 4677 std::unique_ptr<Verifier> V; 4678 bool FatalErrors = true; 4679 4680 VerifierLegacyPass() : FunctionPass(ID) { 4681 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4682 } 4683 explicit VerifierLegacyPass(bool FatalErrors) 4684 : FunctionPass(ID), 4685 FatalErrors(FatalErrors) { 4686 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4687 } 4688 4689 bool doInitialization(Module &M) override { 4690 V = llvm::make_unique<Verifier>( 4691 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M); 4692 return false; 4693 } 4694 4695 bool runOnFunction(Function &F) override { 4696 if (!V->verify(F) && FatalErrors) 4697 report_fatal_error("Broken function found, compilation aborted!"); 4698 4699 return false; 4700 } 4701 4702 bool doFinalization(Module &M) override { 4703 bool HasErrors = false; 4704 for (Function &F : M) 4705 if (F.isDeclaration()) 4706 HasErrors |= !V->verify(F); 4707 4708 HasErrors |= !V->verify(); 4709 if (FatalErrors) { 4710 if (HasErrors) 4711 report_fatal_error("Broken module found, compilation aborted!"); 4712 assert(!V->hasBrokenDebugInfo() && "Module contains invalid debug info"); 4713 } 4714 4715 // Strip broken debug info. 4716 if (V->hasBrokenDebugInfo()) { 4717 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4718 M.getContext().diagnose(DiagInvalid); 4719 if (!StripDebugInfo(M)) 4720 report_fatal_error("Failed to strip malformed debug info"); 4721 } 4722 return false; 4723 } 4724 4725 void getAnalysisUsage(AnalysisUsage &AU) const override { 4726 AU.setPreservesAll(); 4727 } 4728 }; 4729 4730 } // end anonymous namespace 4731 4732 char VerifierLegacyPass::ID = 0; 4733 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 4734 4735 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 4736 return new VerifierLegacyPass(FatalErrors); 4737 } 4738 4739 AnalysisKey VerifierAnalysis::Key; 4740 VerifierAnalysis::Result VerifierAnalysis::run(Module &M, 4741 ModuleAnalysisManager &) { 4742 Result Res; 4743 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 4744 return Res; 4745 } 4746 4747 VerifierAnalysis::Result VerifierAnalysis::run(Function &F, 4748 FunctionAnalysisManager &) { 4749 return { llvm::verifyFunction(F, &dbgs()), false }; 4750 } 4751 4752 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 4753 auto Res = AM.getResult<VerifierAnalysis>(M); 4754 if (FatalErrors) { 4755 if (Res.IRBroken) 4756 report_fatal_error("Broken module found, compilation aborted!"); 4757 assert(!Res.DebugInfoBroken && "Module contains invalid debug info"); 4758 } 4759 4760 // Strip broken debug info. 4761 if (Res.DebugInfoBroken) { 4762 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4763 M.getContext().diagnose(DiagInvalid); 4764 if (!StripDebugInfo(M)) 4765 report_fatal_error("Failed to strip malformed debug info"); 4766 } 4767 return PreservedAnalyses::all(); 4768 } 4769 4770 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 4771 auto res = AM.getResult<VerifierAnalysis>(F); 4772 if (res.IRBroken && FatalErrors) 4773 report_fatal_error("Broken function found, compilation aborted!"); 4774 4775 return PreservedAnalyses::all(); 4776 } 4777