1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the function verifier interface, that can be used for some 10 // sanity checking of input to the system. 11 // 12 // Note that this does not provide full `Java style' security and verifications, 13 // instead it just tries to ensure that code is well-formed. 14 // 15 // * Both of a binary operator's parameters are of the same type 16 // * Verify that the indices of mem access instructions match other operands 17 // * Verify that arithmetic and other things are only performed on first-class 18 // types. Verify that shifts & logicals only happen on integrals f.e. 19 // * All of the constants in a switch statement are of the correct type 20 // * The code is in valid SSA form 21 // * It should be illegal to put a label into any other type (like a structure) 22 // or to return one. [except constant arrays!] 23 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 24 // * PHI nodes must have an entry for each predecessor, with no extras. 25 // * PHI nodes must be the first thing in a basic block, all grouped together 26 // * PHI nodes must have at least one entry 27 // * All basic blocks should only end with terminator insts, not contain them 28 // * The entry node to a function must not have predecessors 29 // * All Instructions must be embedded into a basic block 30 // * Functions cannot take a void-typed parameter 31 // * Verify that a function's argument list agrees with it's declared type. 32 // * It is illegal to specify a name for a void value. 33 // * It is illegal to have a internal global value with no initializer 34 // * It is illegal to have a ret instruction that returns a value that does not 35 // agree with the function return value type. 36 // * Function call argument types match the function prototype 37 // * A landing pad is defined by a landingpad instruction, and can be jumped to 38 // only by the unwind edge of an invoke instruction. 39 // * A landingpad instruction must be the first non-PHI instruction in the 40 // block. 41 // * Landingpad instructions must be in a function with a personality function. 42 // * All other things that are tested by asserts spread about the code... 43 // 44 //===----------------------------------------------------------------------===// 45 46 #include "llvm/IR/Verifier.h" 47 #include "llvm/ADT/APFloat.h" 48 #include "llvm/ADT/APInt.h" 49 #include "llvm/ADT/ArrayRef.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/MapVector.h" 52 #include "llvm/ADT/Optional.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/SmallPtrSet.h" 55 #include "llvm/ADT/SmallSet.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringExtras.h" 58 #include "llvm/ADT/StringMap.h" 59 #include "llvm/ADT/StringRef.h" 60 #include "llvm/ADT/Twine.h" 61 #include "llvm/ADT/ilist.h" 62 #include "llvm/BinaryFormat/Dwarf.h" 63 #include "llvm/IR/Argument.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/CFG.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/Dominators.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GlobalAlias.h" 80 #include "llvm/IR/GlobalValue.h" 81 #include "llvm/IR/GlobalVariable.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstVisitor.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsWebAssembly.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/InitializePasses.h" 101 #include "llvm/Pass.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/Casting.h" 104 #include "llvm/Support/CommandLine.h" 105 #include "llvm/Support/Debug.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> VerifyNoAliasScopeDomination( 119 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), 120 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " 121 "scopes are not dominating")); 122 123 namespace llvm { 124 125 struct VerifierSupport { 126 raw_ostream *OS; 127 const Module &M; 128 ModuleSlotTracker MST; 129 Triple TT; 130 const DataLayout &DL; 131 LLVMContext &Context; 132 133 /// Track the brokenness of the module while recursively visiting. 134 bool Broken = false; 135 /// Broken debug info can be "recovered" from by stripping the debug info. 136 bool BrokenDebugInfo = false; 137 /// Whether to treat broken debug info as an error. 138 bool TreatBrokenDebugInfoAsError = true; 139 140 explicit VerifierSupport(raw_ostream *OS, const Module &M) 141 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()), 142 Context(M.getContext()) {} 143 144 private: 145 void Write(const Module *M) { 146 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 147 } 148 149 void Write(const Value *V) { 150 if (V) 151 Write(*V); 152 } 153 154 void Write(const Value &V) { 155 if (isa<Instruction>(V)) { 156 V.print(*OS, MST); 157 *OS << '\n'; 158 } else { 159 V.printAsOperand(*OS, true, MST); 160 *OS << '\n'; 161 } 162 } 163 164 void Write(const Metadata *MD) { 165 if (!MD) 166 return; 167 MD->print(*OS, MST, &M); 168 *OS << '\n'; 169 } 170 171 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 172 Write(MD.get()); 173 } 174 175 void Write(const NamedMDNode *NMD) { 176 if (!NMD) 177 return; 178 NMD->print(*OS, MST); 179 *OS << '\n'; 180 } 181 182 void Write(Type *T) { 183 if (!T) 184 return; 185 *OS << ' ' << *T; 186 } 187 188 void Write(const Comdat *C) { 189 if (!C) 190 return; 191 *OS << *C; 192 } 193 194 void Write(const APInt *AI) { 195 if (!AI) 196 return; 197 *OS << *AI << '\n'; 198 } 199 200 void Write(const unsigned i) { *OS << i << '\n'; } 201 202 template <typename T> void Write(ArrayRef<T> Vs) { 203 for (const T &V : Vs) 204 Write(V); 205 } 206 207 template <typename T1, typename... Ts> 208 void WriteTs(const T1 &V1, const Ts &... Vs) { 209 Write(V1); 210 WriteTs(Vs...); 211 } 212 213 template <typename... Ts> void WriteTs() {} 214 215 public: 216 /// A check failed, so printout out the condition and the message. 217 /// 218 /// This provides a nice place to put a breakpoint if you want to see why 219 /// something is not correct. 220 void CheckFailed(const Twine &Message) { 221 if (OS) 222 *OS << Message << '\n'; 223 Broken = true; 224 } 225 226 /// A check failed (with values to print). 227 /// 228 /// This calls the Message-only version so that the above is easier to set a 229 /// breakpoint on. 230 template <typename T1, typename... Ts> 231 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 232 CheckFailed(Message); 233 if (OS) 234 WriteTs(V1, Vs...); 235 } 236 237 /// A debug info check failed. 238 void DebugInfoCheckFailed(const Twine &Message) { 239 if (OS) 240 *OS << Message << '\n'; 241 Broken |= TreatBrokenDebugInfoAsError; 242 BrokenDebugInfo = true; 243 } 244 245 /// A debug info check failed (with values to print). 246 template <typename T1, typename... Ts> 247 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, 248 const Ts &... Vs) { 249 DebugInfoCheckFailed(Message); 250 if (OS) 251 WriteTs(V1, Vs...); 252 } 253 }; 254 255 } // namespace llvm 256 257 namespace { 258 259 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 260 friend class InstVisitor<Verifier>; 261 262 DominatorTree DT; 263 264 /// When verifying a basic block, keep track of all of the 265 /// instructions we have seen so far. 266 /// 267 /// This allows us to do efficient dominance checks for the case when an 268 /// instruction has an operand that is an instruction in the same block. 269 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 270 271 /// Keep track of the metadata nodes that have been checked already. 272 SmallPtrSet<const Metadata *, 32> MDNodes; 273 274 /// Keep track which DISubprogram is attached to which function. 275 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments; 276 277 /// Track all DICompileUnits visited. 278 SmallPtrSet<const Metadata *, 2> CUVisited; 279 280 /// The result type for a landingpad. 281 Type *LandingPadResultTy; 282 283 /// Whether we've seen a call to @llvm.localescape in this function 284 /// already. 285 bool SawFrameEscape; 286 287 /// Whether the current function has a DISubprogram attached to it. 288 bool HasDebugInfo = false; 289 290 /// The current source language. 291 dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user; 292 293 /// Whether source was present on the first DIFile encountered in each CU. 294 DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo; 295 296 /// Stores the count of how many objects were passed to llvm.localescape for a 297 /// given function and the largest index passed to llvm.localrecover. 298 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 299 300 // Maps catchswitches and cleanuppads that unwind to siblings to the 301 // terminators that indicate the unwind, used to detect cycles therein. 302 MapVector<Instruction *, Instruction *> SiblingFuncletInfo; 303 304 /// Cache of constants visited in search of ConstantExprs. 305 SmallPtrSet<const Constant *, 32> ConstantExprVisited; 306 307 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic. 308 SmallVector<const Function *, 4> DeoptimizeDeclarations; 309 310 // Verify that this GlobalValue is only used in this module. 311 // This map is used to avoid visiting uses twice. We can arrive at a user 312 // twice, if they have multiple operands. In particular for very large 313 // constant expressions, we can arrive at a particular user many times. 314 SmallPtrSet<const Value *, 32> GlobalValueVisited; 315 316 // Keeps track of duplicate function argument debug info. 317 SmallVector<const DILocalVariable *, 16> DebugFnArgs; 318 319 TBAAVerifier TBAAVerifyHelper; 320 321 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls; 322 323 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I); 324 325 public: 326 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError, 327 const Module &M) 328 : VerifierSupport(OS, M), LandingPadResultTy(nullptr), 329 SawFrameEscape(false), TBAAVerifyHelper(this) { 330 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError; 331 } 332 333 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; } 334 335 bool verify(const Function &F) { 336 assert(F.getParent() == &M && 337 "An instance of this class only works with a specific module!"); 338 339 // First ensure the function is well-enough formed to compute dominance 340 // information, and directly compute a dominance tree. We don't rely on the 341 // pass manager to provide this as it isolates us from a potentially 342 // out-of-date dominator tree and makes it significantly more complex to run 343 // this code outside of a pass manager. 344 // FIXME: It's really gross that we have to cast away constness here. 345 if (!F.empty()) 346 DT.recalculate(const_cast<Function &>(F)); 347 348 for (const BasicBlock &BB : F) { 349 if (!BB.empty() && BB.back().isTerminator()) 350 continue; 351 352 if (OS) { 353 *OS << "Basic Block in function '" << F.getName() 354 << "' does not have terminator!\n"; 355 BB.printAsOperand(*OS, true, MST); 356 *OS << "\n"; 357 } 358 return false; 359 } 360 361 Broken = false; 362 // FIXME: We strip const here because the inst visitor strips const. 363 visit(const_cast<Function &>(F)); 364 verifySiblingFuncletUnwinds(); 365 InstsInThisBlock.clear(); 366 DebugFnArgs.clear(); 367 LandingPadResultTy = nullptr; 368 SawFrameEscape = false; 369 SiblingFuncletInfo.clear(); 370 verifyNoAliasScopeDecl(); 371 NoAliasScopeDecls.clear(); 372 373 return !Broken; 374 } 375 376 /// Verify the module that this instance of \c Verifier was initialized with. 377 bool verify() { 378 Broken = false; 379 380 // Collect all declarations of the llvm.experimental.deoptimize intrinsic. 381 for (const Function &F : M) 382 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize) 383 DeoptimizeDeclarations.push_back(&F); 384 385 // Now that we've visited every function, verify that we never asked to 386 // recover a frame index that wasn't escaped. 387 verifyFrameRecoverIndices(); 388 for (const GlobalVariable &GV : M.globals()) 389 visitGlobalVariable(GV); 390 391 for (const GlobalAlias &GA : M.aliases()) 392 visitGlobalAlias(GA); 393 394 for (const NamedMDNode &NMD : M.named_metadata()) 395 visitNamedMDNode(NMD); 396 397 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 398 visitComdat(SMEC.getValue()); 399 400 visitModuleFlags(M); 401 visitModuleIdents(M); 402 visitModuleCommandLines(M); 403 404 verifyCompileUnits(); 405 406 verifyDeoptimizeCallingConvs(); 407 DISubprogramAttachments.clear(); 408 return !Broken; 409 } 410 411 private: 412 /// Whether a metadata node is allowed to be, or contain, a DILocation. 413 enum class AreDebugLocsAllowed { No, Yes }; 414 415 // Verification methods... 416 void visitGlobalValue(const GlobalValue &GV); 417 void visitGlobalVariable(const GlobalVariable &GV); 418 void visitGlobalAlias(const GlobalAlias &GA); 419 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 420 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 421 const GlobalAlias &A, const Constant &C); 422 void visitNamedMDNode(const NamedMDNode &NMD); 423 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs); 424 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 425 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 426 void visitComdat(const Comdat &C); 427 void visitModuleIdents(const Module &M); 428 void visitModuleCommandLines(const Module &M); 429 void visitModuleFlags(const Module &M); 430 void visitModuleFlag(const MDNode *Op, 431 DenseMap<const MDString *, const MDNode *> &SeenIDs, 432 SmallVectorImpl<const MDNode *> &Requirements); 433 void visitModuleFlagCGProfileEntry(const MDOperand &MDO); 434 void visitFunction(const Function &F); 435 void visitBasicBlock(BasicBlock &BB); 436 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty); 437 void visitDereferenceableMetadata(Instruction &I, MDNode *MD); 438 void visitProfMetadata(Instruction &I, MDNode *MD); 439 void visitAnnotationMetadata(MDNode *Annotation); 440 441 template <class Ty> bool isValidMetadataArray(const MDTuple &N); 442 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 443 #include "llvm/IR/Metadata.def" 444 void visitDIScope(const DIScope &N); 445 void visitDIVariable(const DIVariable &N); 446 void visitDILexicalBlockBase(const DILexicalBlockBase &N); 447 void visitDITemplateParameter(const DITemplateParameter &N); 448 449 void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 450 451 // InstVisitor overrides... 452 using InstVisitor<Verifier>::visit; 453 void visit(Instruction &I); 454 455 void visitTruncInst(TruncInst &I); 456 void visitZExtInst(ZExtInst &I); 457 void visitSExtInst(SExtInst &I); 458 void visitFPTruncInst(FPTruncInst &I); 459 void visitFPExtInst(FPExtInst &I); 460 void visitFPToUIInst(FPToUIInst &I); 461 void visitFPToSIInst(FPToSIInst &I); 462 void visitUIToFPInst(UIToFPInst &I); 463 void visitSIToFPInst(SIToFPInst &I); 464 void visitIntToPtrInst(IntToPtrInst &I); 465 void visitPtrToIntInst(PtrToIntInst &I); 466 void visitBitCastInst(BitCastInst &I); 467 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 468 void visitPHINode(PHINode &PN); 469 void visitCallBase(CallBase &Call); 470 void visitUnaryOperator(UnaryOperator &U); 471 void visitBinaryOperator(BinaryOperator &B); 472 void visitICmpInst(ICmpInst &IC); 473 void visitFCmpInst(FCmpInst &FC); 474 void visitExtractElementInst(ExtractElementInst &EI); 475 void visitInsertElementInst(InsertElementInst &EI); 476 void visitShuffleVectorInst(ShuffleVectorInst &EI); 477 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 478 void visitCallInst(CallInst &CI); 479 void visitInvokeInst(InvokeInst &II); 480 void visitGetElementPtrInst(GetElementPtrInst &GEP); 481 void visitLoadInst(LoadInst &LI); 482 void visitStoreInst(StoreInst &SI); 483 void verifyDominatesUse(Instruction &I, unsigned i); 484 void visitInstruction(Instruction &I); 485 void visitTerminator(Instruction &I); 486 void visitBranchInst(BranchInst &BI); 487 void visitReturnInst(ReturnInst &RI); 488 void visitSwitchInst(SwitchInst &SI); 489 void visitIndirectBrInst(IndirectBrInst &BI); 490 void visitCallBrInst(CallBrInst &CBI); 491 void visitSelectInst(SelectInst &SI); 492 void visitUserOp1(Instruction &I); 493 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 494 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call); 495 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI); 496 void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII); 497 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI); 498 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 499 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 500 void visitFenceInst(FenceInst &FI); 501 void visitAllocaInst(AllocaInst &AI); 502 void visitExtractValueInst(ExtractValueInst &EVI); 503 void visitInsertValueInst(InsertValueInst &IVI); 504 void visitEHPadPredecessors(Instruction &I); 505 void visitLandingPadInst(LandingPadInst &LPI); 506 void visitResumeInst(ResumeInst &RI); 507 void visitCatchPadInst(CatchPadInst &CPI); 508 void visitCatchReturnInst(CatchReturnInst &CatchReturn); 509 void visitCleanupPadInst(CleanupPadInst &CPI); 510 void visitFuncletPadInst(FuncletPadInst &FPI); 511 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 512 void visitCleanupReturnInst(CleanupReturnInst &CRI); 513 514 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal); 515 void verifySwiftErrorValue(const Value *SwiftErrorVal); 516 void verifyMustTailCall(CallInst &CI); 517 bool verifyAttributeCount(AttributeList Attrs, unsigned Params); 518 void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 519 const Value *V); 520 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V); 521 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 522 const Value *V, bool IsIntrinsic); 523 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs); 524 525 void visitConstantExprsRecursively(const Constant *EntryC); 526 void visitConstantExpr(const ConstantExpr *CE); 527 void verifyStatepoint(const CallBase &Call); 528 void verifyFrameRecoverIndices(); 529 void verifySiblingFuncletUnwinds(); 530 531 void verifyFragmentExpression(const DbgVariableIntrinsic &I); 532 template <typename ValueOrMetadata> 533 void verifyFragmentExpression(const DIVariable &V, 534 DIExpression::FragmentInfo Fragment, 535 ValueOrMetadata *Desc); 536 void verifyFnArgs(const DbgVariableIntrinsic &I); 537 void verifyNotEntryValue(const DbgVariableIntrinsic &I); 538 539 /// Module-level debug info verification... 540 void verifyCompileUnits(); 541 542 /// Module-level verification that all @llvm.experimental.deoptimize 543 /// declarations share the same calling convention. 544 void verifyDeoptimizeCallingConvs(); 545 546 /// Verify all-or-nothing property of DIFile source attribute within a CU. 547 void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F); 548 549 /// Verify the llvm.experimental.noalias.scope.decl declarations 550 void verifyNoAliasScopeDecl(); 551 }; 552 553 } // end anonymous namespace 554 555 /// We know that cond should be true, if not print an error message. 556 #define Assert(C, ...) \ 557 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 558 559 /// We know that a debug info condition should be true, if not print 560 /// an error message. 561 #define AssertDI(C, ...) \ 562 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false) 563 564 void Verifier::visit(Instruction &I) { 565 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 566 Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 567 InstVisitor<Verifier>::visit(I); 568 } 569 570 // Helper to recursively iterate over indirect users. By 571 // returning false, the callback can ask to stop recursing 572 // further. 573 static void forEachUser(const Value *User, 574 SmallPtrSet<const Value *, 32> &Visited, 575 llvm::function_ref<bool(const Value *)> Callback) { 576 if (!Visited.insert(User).second) 577 return; 578 for (const Value *TheNextUser : User->materialized_users()) 579 if (Callback(TheNextUser)) 580 forEachUser(TheNextUser, Visited, Callback); 581 } 582 583 void Verifier::visitGlobalValue(const GlobalValue &GV) { 584 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(), 585 "Global is external, but doesn't have external or weak linkage!", &GV); 586 587 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) 588 Assert(GO->getAlignment() <= Value::MaximumAlignment, 589 "huge alignment values are unsupported", GO); 590 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 591 "Only global variables can have appending linkage!", &GV); 592 593 if (GV.hasAppendingLinkage()) { 594 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 595 Assert(GVar && GVar->getValueType()->isArrayTy(), 596 "Only global arrays can have appending linkage!", GVar); 597 } 598 599 if (GV.isDeclarationForLinker()) 600 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 601 602 if (GV.hasDLLImportStorageClass()) { 603 Assert(!GV.isDSOLocal(), 604 "GlobalValue with DLLImport Storage is dso_local!", &GV); 605 606 Assert((GV.isDeclaration() && 607 (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) || 608 GV.hasAvailableExternallyLinkage(), 609 "Global is marked as dllimport, but not external", &GV); 610 } 611 612 if (GV.isImplicitDSOLocal()) 613 Assert(GV.isDSOLocal(), 614 "GlobalValue with local linkage or non-default " 615 "visibility must be dso_local!", 616 &GV); 617 618 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool { 619 if (const Instruction *I = dyn_cast<Instruction>(V)) { 620 if (!I->getParent() || !I->getParent()->getParent()) 621 CheckFailed("Global is referenced by parentless instruction!", &GV, &M, 622 I); 623 else if (I->getParent()->getParent()->getParent() != &M) 624 CheckFailed("Global is referenced in a different module!", &GV, &M, I, 625 I->getParent()->getParent(), 626 I->getParent()->getParent()->getParent()); 627 return false; 628 } else if (const Function *F = dyn_cast<Function>(V)) { 629 if (F->getParent() != &M) 630 CheckFailed("Global is used by function in a different module", &GV, &M, 631 F, F->getParent()); 632 return false; 633 } 634 return true; 635 }); 636 } 637 638 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 639 if (GV.hasInitializer()) { 640 Assert(GV.getInitializer()->getType() == GV.getValueType(), 641 "Global variable initializer type does not match global " 642 "variable type!", 643 &GV); 644 // If the global has common linkage, it must have a zero initializer and 645 // cannot be constant. 646 if (GV.hasCommonLinkage()) { 647 Assert(GV.getInitializer()->isNullValue(), 648 "'common' global must have a zero initializer!", &GV); 649 Assert(!GV.isConstant(), "'common' global may not be marked constant!", 650 &GV); 651 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 652 } 653 } 654 655 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 656 GV.getName() == "llvm.global_dtors")) { 657 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 658 "invalid linkage for intrinsic global variable", &GV); 659 // Don't worry about emitting an error for it not being an array, 660 // visitGlobalValue will complain on appending non-array. 661 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 662 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 663 PointerType *FuncPtrTy = 664 FunctionType::get(Type::getVoidTy(Context), false)-> 665 getPointerTo(DL.getProgramAddressSpace()); 666 Assert(STy && 667 (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 668 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 669 STy->getTypeAtIndex(1) == FuncPtrTy, 670 "wrong type for intrinsic global variable", &GV); 671 Assert(STy->getNumElements() == 3, 672 "the third field of the element type is mandatory, " 673 "specify i8* null to migrate from the obsoleted 2-field form"); 674 Type *ETy = STy->getTypeAtIndex(2); 675 Assert(ETy->isPointerTy() && 676 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 677 "wrong type for intrinsic global variable", &GV); 678 } 679 } 680 681 if (GV.hasName() && (GV.getName() == "llvm.used" || 682 GV.getName() == "llvm.compiler.used")) { 683 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 684 "invalid linkage for intrinsic global variable", &GV); 685 Type *GVType = GV.getValueType(); 686 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 687 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 688 Assert(PTy, "wrong type for intrinsic global variable", &GV); 689 if (GV.hasInitializer()) { 690 const Constant *Init = GV.getInitializer(); 691 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 692 Assert(InitArray, "wrong initalizer for intrinsic global variable", 693 Init); 694 for (Value *Op : InitArray->operands()) { 695 Value *V = Op->stripPointerCasts(); 696 Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 697 isa<GlobalAlias>(V), 698 "invalid llvm.used member", V); 699 Assert(V->hasName(), "members of llvm.used must be named", V); 700 } 701 } 702 } 703 } 704 705 // Visit any debug info attachments. 706 SmallVector<MDNode *, 1> MDs; 707 GV.getMetadata(LLVMContext::MD_dbg, MDs); 708 for (auto *MD : MDs) { 709 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD)) 710 visitDIGlobalVariableExpression(*GVE); 711 else 712 AssertDI(false, "!dbg attachment of global variable must be a " 713 "DIGlobalVariableExpression"); 714 } 715 716 // Scalable vectors cannot be global variables, since we don't know 717 // the runtime size. If the global is an array containing scalable vectors, 718 // that will be caught by the isValidElementType methods in StructType or 719 // ArrayType instead. 720 Assert(!isa<ScalableVectorType>(GV.getValueType()), 721 "Globals cannot contain scalable vectors", &GV); 722 723 if (auto *STy = dyn_cast<StructType>(GV.getValueType())) 724 Assert(!STy->containsScalableVectorType(), 725 "Globals cannot contain scalable vectors", &GV); 726 727 if (!GV.hasInitializer()) { 728 visitGlobalValue(GV); 729 return; 730 } 731 732 // Walk any aggregate initializers looking for bitcasts between address spaces 733 visitConstantExprsRecursively(GV.getInitializer()); 734 735 visitGlobalValue(GV); 736 } 737 738 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 739 SmallPtrSet<const GlobalAlias*, 4> Visited; 740 Visited.insert(&GA); 741 visitAliaseeSubExpr(Visited, GA, C); 742 } 743 744 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 745 const GlobalAlias &GA, const Constant &C) { 746 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 747 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 748 &GA); 749 750 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 751 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 752 753 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias", 754 &GA); 755 } else { 756 // Only continue verifying subexpressions of GlobalAliases. 757 // Do not recurse into global initializers. 758 return; 759 } 760 } 761 762 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 763 visitConstantExprsRecursively(CE); 764 765 for (const Use &U : C.operands()) { 766 Value *V = &*U; 767 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 768 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 769 else if (const auto *C2 = dyn_cast<Constant>(V)) 770 visitAliaseeSubExpr(Visited, GA, *C2); 771 } 772 } 773 774 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 775 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 776 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 777 "weak_odr, or external linkage!", 778 &GA); 779 const Constant *Aliasee = GA.getAliasee(); 780 Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 781 Assert(GA.getType() == Aliasee->getType(), 782 "Alias and aliasee types should match!", &GA); 783 784 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 785 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 786 787 visitAliaseeSubExpr(GA, *Aliasee); 788 789 visitGlobalValue(GA); 790 } 791 792 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 793 // There used to be various other llvm.dbg.* nodes, but we don't support 794 // upgrading them and we want to reserve the namespace for future uses. 795 if (NMD.getName().startswith("llvm.dbg.")) 796 AssertDI(NMD.getName() == "llvm.dbg.cu", 797 "unrecognized named metadata node in the llvm.dbg namespace", 798 &NMD); 799 for (const MDNode *MD : NMD.operands()) { 800 if (NMD.getName() == "llvm.dbg.cu") 801 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 802 803 if (!MD) 804 continue; 805 806 visitMDNode(*MD, AreDebugLocsAllowed::Yes); 807 } 808 } 809 810 void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) { 811 // Only visit each node once. Metadata can be mutually recursive, so this 812 // avoids infinite recursion here, as well as being an optimization. 813 if (!MDNodes.insert(&MD).second) 814 return; 815 816 switch (MD.getMetadataID()) { 817 default: 818 llvm_unreachable("Invalid MDNode subclass"); 819 case Metadata::MDTupleKind: 820 break; 821 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 822 case Metadata::CLASS##Kind: \ 823 visit##CLASS(cast<CLASS>(MD)); \ 824 break; 825 #include "llvm/IR/Metadata.def" 826 } 827 828 for (const Metadata *Op : MD.operands()) { 829 if (!Op) 830 continue; 831 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 832 &MD, Op); 833 AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes, 834 "DILocation not allowed within this metadata node", &MD, Op); 835 if (auto *N = dyn_cast<MDNode>(Op)) { 836 visitMDNode(*N, AllowLocs); 837 continue; 838 } 839 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 840 visitValueAsMetadata(*V, nullptr); 841 continue; 842 } 843 } 844 845 // Check these last, so we diagnose problems in operands first. 846 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 847 Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 848 } 849 850 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 851 Assert(MD.getValue(), "Expected valid value", &MD); 852 Assert(!MD.getValue()->getType()->isMetadataTy(), 853 "Unexpected metadata round-trip through values", &MD, MD.getValue()); 854 855 auto *L = dyn_cast<LocalAsMetadata>(&MD); 856 if (!L) 857 return; 858 859 Assert(F, "function-local metadata used outside a function", L); 860 861 // If this was an instruction, bb, or argument, verify that it is in the 862 // function that we expect. 863 Function *ActualF = nullptr; 864 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 865 Assert(I->getParent(), "function-local metadata not in basic block", L, I); 866 ActualF = I->getParent()->getParent(); 867 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 868 ActualF = BB->getParent(); 869 else if (Argument *A = dyn_cast<Argument>(L->getValue())) 870 ActualF = A->getParent(); 871 assert(ActualF && "Unimplemented function local metadata case!"); 872 873 Assert(ActualF == F, "function-local metadata used in wrong function", L); 874 } 875 876 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 877 Metadata *MD = MDV.getMetadata(); 878 if (auto *N = dyn_cast<MDNode>(MD)) { 879 visitMDNode(*N, AreDebugLocsAllowed::No); 880 return; 881 } 882 883 // Only visit each node once. Metadata can be mutually recursive, so this 884 // avoids infinite recursion here, as well as being an optimization. 885 if (!MDNodes.insert(MD).second) 886 return; 887 888 if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 889 visitValueAsMetadata(*V, F); 890 } 891 892 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); } 893 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); } 894 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); } 895 896 void Verifier::visitDILocation(const DILocation &N) { 897 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 898 "location requires a valid scope", &N, N.getRawScope()); 899 if (auto *IA = N.getRawInlinedAt()) 900 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 901 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope())) 902 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N); 903 } 904 905 void Verifier::visitGenericDINode(const GenericDINode &N) { 906 AssertDI(N.getTag(), "invalid tag", &N); 907 } 908 909 void Verifier::visitDIScope(const DIScope &N) { 910 if (auto *F = N.getRawFile()) 911 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 912 } 913 914 void Verifier::visitDISubrange(const DISubrange &N) { 915 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 916 bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang); 917 AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() || 918 N.getRawUpperBound(), 919 "Subrange must contain count or upperBound", &N); 920 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(), 921 "Subrange can have any one of count or upperBound", &N); 922 AssertDI(!N.getRawCountNode() || N.getCount(), 923 "Count must either be a signed constant or a DIVariable", &N); 924 auto Count = N.getCount(); 925 AssertDI(!Count || !Count.is<ConstantInt *>() || 926 Count.get<ConstantInt *>()->getSExtValue() >= -1, 927 "invalid subrange count", &N); 928 auto *LBound = N.getRawLowerBound(); 929 AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) || 930 isa<DIVariable>(LBound) || isa<DIExpression>(LBound), 931 "LowerBound must be signed constant or DIVariable or DIExpression", 932 &N); 933 auto *UBound = N.getRawUpperBound(); 934 AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) || 935 isa<DIVariable>(UBound) || isa<DIExpression>(UBound), 936 "UpperBound must be signed constant or DIVariable or DIExpression", 937 &N); 938 auto *Stride = N.getRawStride(); 939 AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) || 940 isa<DIVariable>(Stride) || isa<DIExpression>(Stride), 941 "Stride must be signed constant or DIVariable or DIExpression", &N); 942 } 943 944 void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) { 945 AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N); 946 AssertDI(N.getRawCountNode() || N.getRawUpperBound(), 947 "GenericSubrange must contain count or upperBound", &N); 948 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(), 949 "GenericSubrange can have any one of count or upperBound", &N); 950 auto *CBound = N.getRawCountNode(); 951 AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound), 952 "Count must be signed constant or DIVariable or DIExpression", &N); 953 auto *LBound = N.getRawLowerBound(); 954 AssertDI(LBound, "GenericSubrange must contain lowerBound", &N); 955 AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound), 956 "LowerBound must be signed constant or DIVariable or DIExpression", 957 &N); 958 auto *UBound = N.getRawUpperBound(); 959 AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound), 960 "UpperBound must be signed constant or DIVariable or DIExpression", 961 &N); 962 auto *Stride = N.getRawStride(); 963 AssertDI(Stride, "GenericSubrange must contain stride", &N); 964 AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride), 965 "Stride must be signed constant or DIVariable or DIExpression", &N); 966 } 967 968 void Verifier::visitDIEnumerator(const DIEnumerator &N) { 969 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 970 } 971 972 void Verifier::visitDIBasicType(const DIBasicType &N) { 973 AssertDI(N.getTag() == dwarf::DW_TAG_base_type || 974 N.getTag() == dwarf::DW_TAG_unspecified_type || 975 N.getTag() == dwarf::DW_TAG_string_type, 976 "invalid tag", &N); 977 } 978 979 void Verifier::visitDIStringType(const DIStringType &N) { 980 AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N); 981 AssertDI(!(N.isBigEndian() && N.isLittleEndian()) , 982 "has conflicting flags", &N); 983 } 984 985 void Verifier::visitDIDerivedType(const DIDerivedType &N) { 986 // Common scope checks. 987 visitDIScope(N); 988 989 AssertDI(N.getTag() == dwarf::DW_TAG_typedef || 990 N.getTag() == dwarf::DW_TAG_pointer_type || 991 N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 992 N.getTag() == dwarf::DW_TAG_reference_type || 993 N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 994 N.getTag() == dwarf::DW_TAG_const_type || 995 N.getTag() == dwarf::DW_TAG_volatile_type || 996 N.getTag() == dwarf::DW_TAG_restrict_type || 997 N.getTag() == dwarf::DW_TAG_atomic_type || 998 N.getTag() == dwarf::DW_TAG_member || 999 N.getTag() == dwarf::DW_TAG_inheritance || 1000 N.getTag() == dwarf::DW_TAG_friend, 1001 "invalid tag", &N); 1002 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 1003 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N, 1004 N.getRawExtraData()); 1005 } 1006 1007 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1008 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 1009 N.getRawBaseType()); 1010 1011 if (N.getDWARFAddressSpace()) { 1012 AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type || 1013 N.getTag() == dwarf::DW_TAG_reference_type || 1014 N.getTag() == dwarf::DW_TAG_rvalue_reference_type, 1015 "DWARF address space only applies to pointer or reference types", 1016 &N); 1017 } 1018 } 1019 1020 /// Detect mutually exclusive flags. 1021 static bool hasConflictingReferenceFlags(unsigned Flags) { 1022 return ((Flags & DINode::FlagLValueReference) && 1023 (Flags & DINode::FlagRValueReference)) || 1024 ((Flags & DINode::FlagTypePassByValue) && 1025 (Flags & DINode::FlagTypePassByReference)); 1026 } 1027 1028 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 1029 auto *Params = dyn_cast<MDTuple>(&RawParams); 1030 AssertDI(Params, "invalid template params", &N, &RawParams); 1031 for (Metadata *Op : Params->operands()) { 1032 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter", 1033 &N, Params, Op); 1034 } 1035 } 1036 1037 void Verifier::visitDICompositeType(const DICompositeType &N) { 1038 // Common scope checks. 1039 visitDIScope(N); 1040 1041 AssertDI(N.getTag() == dwarf::DW_TAG_array_type || 1042 N.getTag() == dwarf::DW_TAG_structure_type || 1043 N.getTag() == dwarf::DW_TAG_union_type || 1044 N.getTag() == dwarf::DW_TAG_enumeration_type || 1045 N.getTag() == dwarf::DW_TAG_class_type || 1046 N.getTag() == dwarf::DW_TAG_variant_part, 1047 "invalid tag", &N); 1048 1049 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1050 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 1051 N.getRawBaseType()); 1052 1053 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 1054 "invalid composite elements", &N, N.getRawElements()); 1055 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N, 1056 N.getRawVTableHolder()); 1057 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1058 "invalid reference flags", &N); 1059 unsigned DIBlockByRefStruct = 1 << 4; 1060 AssertDI((N.getFlags() & DIBlockByRefStruct) == 0, 1061 "DIBlockByRefStruct on DICompositeType is no longer supported", &N); 1062 1063 if (N.isVector()) { 1064 const DINodeArray Elements = N.getElements(); 1065 AssertDI(Elements.size() == 1 && 1066 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type, 1067 "invalid vector, expected one element of type subrange", &N); 1068 } 1069 1070 if (auto *Params = N.getRawTemplateParams()) 1071 visitTemplateParams(N, *Params); 1072 1073 if (N.getTag() == dwarf::DW_TAG_class_type || 1074 N.getTag() == dwarf::DW_TAG_union_type) { 1075 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(), 1076 "class/union requires a filename", &N, N.getFile()); 1077 } 1078 1079 if (auto *D = N.getRawDiscriminator()) { 1080 AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part, 1081 "discriminator can only appear on variant part"); 1082 } 1083 1084 if (N.getRawDataLocation()) { 1085 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1086 "dataLocation can only appear in array type"); 1087 } 1088 1089 if (N.getRawAssociated()) { 1090 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1091 "associated can only appear in array type"); 1092 } 1093 1094 if (N.getRawAllocated()) { 1095 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1096 "allocated can only appear in array type"); 1097 } 1098 1099 if (N.getRawRank()) { 1100 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1101 "rank can only appear in array type"); 1102 } 1103 } 1104 1105 void Verifier::visitDISubroutineType(const DISubroutineType &N) { 1106 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 1107 if (auto *Types = N.getRawTypeArray()) { 1108 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 1109 for (Metadata *Ty : N.getTypeArray()->operands()) { 1110 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty); 1111 } 1112 } 1113 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1114 "invalid reference flags", &N); 1115 } 1116 1117 void Verifier::visitDIFile(const DIFile &N) { 1118 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 1119 Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum(); 1120 if (Checksum) { 1121 AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last, 1122 "invalid checksum kind", &N); 1123 size_t Size; 1124 switch (Checksum->Kind) { 1125 case DIFile::CSK_MD5: 1126 Size = 32; 1127 break; 1128 case DIFile::CSK_SHA1: 1129 Size = 40; 1130 break; 1131 case DIFile::CSK_SHA256: 1132 Size = 64; 1133 break; 1134 } 1135 AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N); 1136 AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos, 1137 "invalid checksum", &N); 1138 } 1139 } 1140 1141 void Verifier::visitDICompileUnit(const DICompileUnit &N) { 1142 AssertDI(N.isDistinct(), "compile units must be distinct", &N); 1143 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 1144 1145 // Don't bother verifying the compilation directory or producer string 1146 // as those could be empty. 1147 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 1148 N.getRawFile()); 1149 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N, 1150 N.getFile()); 1151 1152 CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage(); 1153 1154 verifySourceDebugInfo(N, *N.getFile()); 1155 1156 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind), 1157 "invalid emission kind", &N); 1158 1159 if (auto *Array = N.getRawEnumTypes()) { 1160 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array); 1161 for (Metadata *Op : N.getEnumTypes()->operands()) { 1162 auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 1163 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 1164 "invalid enum type", &N, N.getEnumTypes(), Op); 1165 } 1166 } 1167 if (auto *Array = N.getRawRetainedTypes()) { 1168 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 1169 for (Metadata *Op : N.getRetainedTypes()->operands()) { 1170 AssertDI(Op && (isa<DIType>(Op) || 1171 (isa<DISubprogram>(Op) && 1172 !cast<DISubprogram>(Op)->isDefinition())), 1173 "invalid retained type", &N, Op); 1174 } 1175 } 1176 if (auto *Array = N.getRawGlobalVariables()) { 1177 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 1178 for (Metadata *Op : N.getGlobalVariables()->operands()) { 1179 AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)), 1180 "invalid global variable ref", &N, Op); 1181 } 1182 } 1183 if (auto *Array = N.getRawImportedEntities()) { 1184 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 1185 for (Metadata *Op : N.getImportedEntities()->operands()) { 1186 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", 1187 &N, Op); 1188 } 1189 } 1190 if (auto *Array = N.getRawMacros()) { 1191 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1192 for (Metadata *Op : N.getMacros()->operands()) { 1193 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1194 } 1195 } 1196 CUVisited.insert(&N); 1197 } 1198 1199 void Verifier::visitDISubprogram(const DISubprogram &N) { 1200 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 1201 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1202 if (auto *F = N.getRawFile()) 1203 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1204 else 1205 AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine()); 1206 if (auto *T = N.getRawType()) 1207 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 1208 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N, 1209 N.getRawContainingType()); 1210 if (auto *Params = N.getRawTemplateParams()) 1211 visitTemplateParams(N, *Params); 1212 if (auto *S = N.getRawDeclaration()) 1213 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 1214 "invalid subprogram declaration", &N, S); 1215 if (auto *RawNode = N.getRawRetainedNodes()) { 1216 auto *Node = dyn_cast<MDTuple>(RawNode); 1217 AssertDI(Node, "invalid retained nodes list", &N, RawNode); 1218 for (Metadata *Op : Node->operands()) { 1219 AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)), 1220 "invalid retained nodes, expected DILocalVariable or DILabel", 1221 &N, Node, Op); 1222 } 1223 } 1224 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1225 "invalid reference flags", &N); 1226 1227 auto *Unit = N.getRawUnit(); 1228 if (N.isDefinition()) { 1229 // Subprogram definitions (not part of the type hierarchy). 1230 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N); 1231 AssertDI(Unit, "subprogram definitions must have a compile unit", &N); 1232 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit); 1233 if (N.getFile()) 1234 verifySourceDebugInfo(*N.getUnit(), *N.getFile()); 1235 } else { 1236 // Subprogram declarations (part of the type hierarchy). 1237 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N); 1238 } 1239 1240 if (auto *RawThrownTypes = N.getRawThrownTypes()) { 1241 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes); 1242 AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes); 1243 for (Metadata *Op : ThrownTypes->operands()) 1244 AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes, 1245 Op); 1246 } 1247 1248 if (N.areAllCallsDescribed()) 1249 AssertDI(N.isDefinition(), 1250 "DIFlagAllCallsDescribed must be attached to a definition"); 1251 } 1252 1253 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 1254 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 1255 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1256 "invalid local scope", &N, N.getRawScope()); 1257 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope())) 1258 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N); 1259 } 1260 1261 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 1262 visitDILexicalBlockBase(N); 1263 1264 AssertDI(N.getLine() || !N.getColumn(), 1265 "cannot have column info without line info", &N); 1266 } 1267 1268 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 1269 visitDILexicalBlockBase(N); 1270 } 1271 1272 void Verifier::visitDICommonBlock(const DICommonBlock &N) { 1273 AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N); 1274 if (auto *S = N.getRawScope()) 1275 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1276 if (auto *S = N.getRawDecl()) 1277 AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S); 1278 } 1279 1280 void Verifier::visitDINamespace(const DINamespace &N) { 1281 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 1282 if (auto *S = N.getRawScope()) 1283 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1284 } 1285 1286 void Verifier::visitDIMacro(const DIMacro &N) { 1287 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define || 1288 N.getMacinfoType() == dwarf::DW_MACINFO_undef, 1289 "invalid macinfo type", &N); 1290 AssertDI(!N.getName().empty(), "anonymous macro", &N); 1291 if (!N.getValue().empty()) { 1292 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1293 } 1294 } 1295 1296 void Verifier::visitDIMacroFile(const DIMacroFile &N) { 1297 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1298 "invalid macinfo type", &N); 1299 if (auto *F = N.getRawFile()) 1300 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1301 1302 if (auto *Array = N.getRawElements()) { 1303 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1304 for (Metadata *Op : N.getElements()->operands()) { 1305 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1306 } 1307 } 1308 } 1309 1310 void Verifier::visitDIModule(const DIModule &N) { 1311 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1312 AssertDI(!N.getName().empty(), "anonymous module", &N); 1313 } 1314 1315 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1316 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1317 } 1318 1319 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1320 visitDITemplateParameter(N); 1321 1322 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1323 &N); 1324 } 1325 1326 void Verifier::visitDITemplateValueParameter( 1327 const DITemplateValueParameter &N) { 1328 visitDITemplateParameter(N); 1329 1330 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1331 N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1332 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1333 "invalid tag", &N); 1334 } 1335 1336 void Verifier::visitDIVariable(const DIVariable &N) { 1337 if (auto *S = N.getRawScope()) 1338 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1339 if (auto *F = N.getRawFile()) 1340 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1341 } 1342 1343 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1344 // Checks common to all variables. 1345 visitDIVariable(N); 1346 1347 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1348 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1349 // Assert only if the global variable is not an extern 1350 if (N.isDefinition()) 1351 AssertDI(N.getType(), "missing global variable type", &N); 1352 if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1353 AssertDI(isa<DIDerivedType>(Member), 1354 "invalid static data member declaration", &N, Member); 1355 } 1356 } 1357 1358 void Verifier::visitDILocalVariable(const DILocalVariable &N) { 1359 // Checks common to all variables. 1360 visitDIVariable(N); 1361 1362 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1363 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1364 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1365 "local variable requires a valid scope", &N, N.getRawScope()); 1366 if (auto Ty = N.getType()) 1367 AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType()); 1368 } 1369 1370 void Verifier::visitDILabel(const DILabel &N) { 1371 if (auto *S = N.getRawScope()) 1372 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1373 if (auto *F = N.getRawFile()) 1374 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1375 1376 AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N); 1377 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1378 "label requires a valid scope", &N, N.getRawScope()); 1379 } 1380 1381 void Verifier::visitDIExpression(const DIExpression &N) { 1382 AssertDI(N.isValid(), "invalid expression", &N); 1383 } 1384 1385 void Verifier::visitDIGlobalVariableExpression( 1386 const DIGlobalVariableExpression &GVE) { 1387 AssertDI(GVE.getVariable(), "missing variable"); 1388 if (auto *Var = GVE.getVariable()) 1389 visitDIGlobalVariable(*Var); 1390 if (auto *Expr = GVE.getExpression()) { 1391 visitDIExpression(*Expr); 1392 if (auto Fragment = Expr->getFragmentInfo()) 1393 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE); 1394 } 1395 } 1396 1397 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1398 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1399 if (auto *T = N.getRawType()) 1400 AssertDI(isType(T), "invalid type ref", &N, T); 1401 if (auto *F = N.getRawFile()) 1402 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1403 } 1404 1405 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1406 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module || 1407 N.getTag() == dwarf::DW_TAG_imported_declaration, 1408 "invalid tag", &N); 1409 if (auto *S = N.getRawScope()) 1410 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1411 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N, 1412 N.getRawEntity()); 1413 } 1414 1415 void Verifier::visitComdat(const Comdat &C) { 1416 // In COFF the Module is invalid if the GlobalValue has private linkage. 1417 // Entities with private linkage don't have entries in the symbol table. 1418 if (TT.isOSBinFormatCOFF()) 1419 if (const GlobalValue *GV = M.getNamedValue(C.getName())) 1420 Assert(!GV->hasPrivateLinkage(), 1421 "comdat global value has private linkage", GV); 1422 } 1423 1424 void Verifier::visitModuleIdents(const Module &M) { 1425 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1426 if (!Idents) 1427 return; 1428 1429 // llvm.ident takes a list of metadata entry. Each entry has only one string. 1430 // Scan each llvm.ident entry and make sure that this requirement is met. 1431 for (const MDNode *N : Idents->operands()) { 1432 Assert(N->getNumOperands() == 1, 1433 "incorrect number of operands in llvm.ident metadata", N); 1434 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1435 ("invalid value for llvm.ident metadata entry operand" 1436 "(the operand should be a string)"), 1437 N->getOperand(0)); 1438 } 1439 } 1440 1441 void Verifier::visitModuleCommandLines(const Module &M) { 1442 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline"); 1443 if (!CommandLines) 1444 return; 1445 1446 // llvm.commandline takes a list of metadata entry. Each entry has only one 1447 // string. Scan each llvm.commandline entry and make sure that this 1448 // requirement is met. 1449 for (const MDNode *N : CommandLines->operands()) { 1450 Assert(N->getNumOperands() == 1, 1451 "incorrect number of operands in llvm.commandline metadata", N); 1452 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1453 ("invalid value for llvm.commandline metadata entry operand" 1454 "(the operand should be a string)"), 1455 N->getOperand(0)); 1456 } 1457 } 1458 1459 void Verifier::visitModuleFlags(const Module &M) { 1460 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1461 if (!Flags) return; 1462 1463 // Scan each flag, and track the flags and requirements. 1464 DenseMap<const MDString*, const MDNode*> SeenIDs; 1465 SmallVector<const MDNode*, 16> Requirements; 1466 for (const MDNode *MDN : Flags->operands()) 1467 visitModuleFlag(MDN, SeenIDs, Requirements); 1468 1469 // Validate that the requirements in the module are valid. 1470 for (const MDNode *Requirement : Requirements) { 1471 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1472 const Metadata *ReqValue = Requirement->getOperand(1); 1473 1474 const MDNode *Op = SeenIDs.lookup(Flag); 1475 if (!Op) { 1476 CheckFailed("invalid requirement on flag, flag is not present in module", 1477 Flag); 1478 continue; 1479 } 1480 1481 if (Op->getOperand(2) != ReqValue) { 1482 CheckFailed(("invalid requirement on flag, " 1483 "flag does not have the required value"), 1484 Flag); 1485 continue; 1486 } 1487 } 1488 } 1489 1490 void 1491 Verifier::visitModuleFlag(const MDNode *Op, 1492 DenseMap<const MDString *, const MDNode *> &SeenIDs, 1493 SmallVectorImpl<const MDNode *> &Requirements) { 1494 // Each module flag should have three arguments, the merge behavior (a 1495 // constant int), the flag ID (an MDString), and the value. 1496 Assert(Op->getNumOperands() == 3, 1497 "incorrect number of operands in module flag", Op); 1498 Module::ModFlagBehavior MFB; 1499 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1500 Assert( 1501 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1502 "invalid behavior operand in module flag (expected constant integer)", 1503 Op->getOperand(0)); 1504 Assert(false, 1505 "invalid behavior operand in module flag (unexpected constant)", 1506 Op->getOperand(0)); 1507 } 1508 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1509 Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1510 Op->getOperand(1)); 1511 1512 // Sanity check the values for behaviors with additional requirements. 1513 switch (MFB) { 1514 case Module::Error: 1515 case Module::Warning: 1516 case Module::Override: 1517 // These behavior types accept any value. 1518 break; 1519 1520 case Module::Max: { 1521 Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)), 1522 "invalid value for 'max' module flag (expected constant integer)", 1523 Op->getOperand(2)); 1524 break; 1525 } 1526 1527 case Module::Require: { 1528 // The value should itself be an MDNode with two operands, a flag ID (an 1529 // MDString), and a value. 1530 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1531 Assert(Value && Value->getNumOperands() == 2, 1532 "invalid value for 'require' module flag (expected metadata pair)", 1533 Op->getOperand(2)); 1534 Assert(isa<MDString>(Value->getOperand(0)), 1535 ("invalid value for 'require' module flag " 1536 "(first value operand should be a string)"), 1537 Value->getOperand(0)); 1538 1539 // Append it to the list of requirements, to check once all module flags are 1540 // scanned. 1541 Requirements.push_back(Value); 1542 break; 1543 } 1544 1545 case Module::Append: 1546 case Module::AppendUnique: { 1547 // These behavior types require the operand be an MDNode. 1548 Assert(isa<MDNode>(Op->getOperand(2)), 1549 "invalid value for 'append'-type module flag " 1550 "(expected a metadata node)", 1551 Op->getOperand(2)); 1552 break; 1553 } 1554 } 1555 1556 // Unless this is a "requires" flag, check the ID is unique. 1557 if (MFB != Module::Require) { 1558 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1559 Assert(Inserted, 1560 "module flag identifiers must be unique (or of 'require' type)", ID); 1561 } 1562 1563 if (ID->getString() == "wchar_size") { 1564 ConstantInt *Value 1565 = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)); 1566 Assert(Value, "wchar_size metadata requires constant integer argument"); 1567 } 1568 1569 if (ID->getString() == "Linker Options") { 1570 // If the llvm.linker.options named metadata exists, we assume that the 1571 // bitcode reader has upgraded the module flag. Otherwise the flag might 1572 // have been created by a client directly. 1573 Assert(M.getNamedMetadata("llvm.linker.options"), 1574 "'Linker Options' named metadata no longer supported"); 1575 } 1576 1577 if (ID->getString() == "SemanticInterposition") { 1578 ConstantInt *Value = 1579 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)); 1580 Assert(Value, 1581 "SemanticInterposition metadata requires constant integer argument"); 1582 } 1583 1584 if (ID->getString() == "CG Profile") { 1585 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands()) 1586 visitModuleFlagCGProfileEntry(MDO); 1587 } 1588 } 1589 1590 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) { 1591 auto CheckFunction = [&](const MDOperand &FuncMDO) { 1592 if (!FuncMDO) 1593 return; 1594 auto F = dyn_cast<ValueAsMetadata>(FuncMDO); 1595 Assert(F && isa<Function>(F->getValue()->stripPointerCasts()), 1596 "expected a Function or null", FuncMDO); 1597 }; 1598 auto Node = dyn_cast_or_null<MDNode>(MDO); 1599 Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO); 1600 CheckFunction(Node->getOperand(0)); 1601 CheckFunction(Node->getOperand(1)); 1602 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2)); 1603 Assert(Count && Count->getType()->isIntegerTy(), 1604 "expected an integer constant", Node->getOperand(2)); 1605 } 1606 1607 /// Return true if this attribute kind only applies to functions. 1608 static bool isFuncOnlyAttr(Attribute::AttrKind Kind) { 1609 switch (Kind) { 1610 case Attribute::NoMerge: 1611 case Attribute::NoReturn: 1612 case Attribute::NoSync: 1613 case Attribute::WillReturn: 1614 case Attribute::NoCallback: 1615 case Attribute::NoCfCheck: 1616 case Attribute::NoUnwind: 1617 case Attribute::NoInline: 1618 case Attribute::AlwaysInline: 1619 case Attribute::OptimizeForSize: 1620 case Attribute::StackProtect: 1621 case Attribute::StackProtectReq: 1622 case Attribute::StackProtectStrong: 1623 case Attribute::SafeStack: 1624 case Attribute::ShadowCallStack: 1625 case Attribute::NoRedZone: 1626 case Attribute::NoImplicitFloat: 1627 case Attribute::Naked: 1628 case Attribute::InlineHint: 1629 case Attribute::StackAlignment: 1630 case Attribute::UWTable: 1631 case Attribute::NonLazyBind: 1632 case Attribute::ReturnsTwice: 1633 case Attribute::SanitizeAddress: 1634 case Attribute::SanitizeHWAddress: 1635 case Attribute::SanitizeMemTag: 1636 case Attribute::SanitizeThread: 1637 case Attribute::SanitizeMemory: 1638 case Attribute::MinSize: 1639 case Attribute::NoDuplicate: 1640 case Attribute::Builtin: 1641 case Attribute::NoBuiltin: 1642 case Attribute::Cold: 1643 case Attribute::Hot: 1644 case Attribute::OptForFuzzing: 1645 case Attribute::OptimizeNone: 1646 case Attribute::JumpTable: 1647 case Attribute::Convergent: 1648 case Attribute::ArgMemOnly: 1649 case Attribute::NoRecurse: 1650 case Attribute::InaccessibleMemOnly: 1651 case Attribute::InaccessibleMemOrArgMemOnly: 1652 case Attribute::AllocSize: 1653 case Attribute::SpeculativeLoadHardening: 1654 case Attribute::Speculatable: 1655 case Attribute::StrictFP: 1656 case Attribute::NullPointerIsValid: 1657 case Attribute::MustProgress: 1658 case Attribute::NoProfile: 1659 return true; 1660 default: 1661 break; 1662 } 1663 return false; 1664 } 1665 1666 /// Return true if this is a function attribute that can also appear on 1667 /// arguments. 1668 static bool isFuncOrArgAttr(Attribute::AttrKind Kind) { 1669 return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly || 1670 Kind == Attribute::ReadNone || Kind == Attribute::NoFree || 1671 Kind == Attribute::Preallocated; 1672 } 1673 1674 void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 1675 const Value *V) { 1676 for (Attribute A : Attrs) { 1677 if (A.isStringAttribute()) 1678 continue; 1679 1680 if (A.isIntAttribute() != 1681 Attribute::doesAttrKindHaveArgument(A.getKindAsEnum())) { 1682 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument", 1683 V); 1684 return; 1685 } 1686 1687 if (isFuncOnlyAttr(A.getKindAsEnum())) { 1688 if (!IsFunction) { 1689 CheckFailed("Attribute '" + A.getAsString() + 1690 "' only applies to functions!", 1691 V); 1692 return; 1693 } 1694 } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) { 1695 CheckFailed("Attribute '" + A.getAsString() + 1696 "' does not apply to functions!", 1697 V); 1698 return; 1699 } 1700 } 1701 } 1702 1703 // VerifyParameterAttrs - Check the given attributes for an argument or return 1704 // value of the specified type. The value V is printed in error messages. 1705 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty, 1706 const Value *V) { 1707 if (!Attrs.hasAttributes()) 1708 return; 1709 1710 verifyAttributeTypes(Attrs, /*IsFunction=*/false, V); 1711 1712 if (Attrs.hasAttribute(Attribute::ImmArg)) { 1713 Assert(Attrs.getNumAttributes() == 1, 1714 "Attribute 'immarg' is incompatible with other attributes", V); 1715 } 1716 1717 // Check for mutually incompatible attributes. Only inreg is compatible with 1718 // sret. 1719 unsigned AttrCount = 0; 1720 AttrCount += Attrs.hasAttribute(Attribute::ByVal); 1721 AttrCount += Attrs.hasAttribute(Attribute::InAlloca); 1722 AttrCount += Attrs.hasAttribute(Attribute::Preallocated); 1723 AttrCount += Attrs.hasAttribute(Attribute::StructRet) || 1724 Attrs.hasAttribute(Attribute::InReg); 1725 AttrCount += Attrs.hasAttribute(Attribute::Nest); 1726 AttrCount += Attrs.hasAttribute(Attribute::ByRef); 1727 Assert(AttrCount <= 1, 1728 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', " 1729 "'byref', and 'sret' are incompatible!", 1730 V); 1731 1732 Assert(!(Attrs.hasAttribute(Attribute::InAlloca) && 1733 Attrs.hasAttribute(Attribute::ReadOnly)), 1734 "Attributes " 1735 "'inalloca and readonly' are incompatible!", 1736 V); 1737 1738 Assert(!(Attrs.hasAttribute(Attribute::StructRet) && 1739 Attrs.hasAttribute(Attribute::Returned)), 1740 "Attributes " 1741 "'sret and returned' are incompatible!", 1742 V); 1743 1744 Assert(!(Attrs.hasAttribute(Attribute::ZExt) && 1745 Attrs.hasAttribute(Attribute::SExt)), 1746 "Attributes " 1747 "'zeroext and signext' are incompatible!", 1748 V); 1749 1750 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1751 Attrs.hasAttribute(Attribute::ReadOnly)), 1752 "Attributes " 1753 "'readnone and readonly' are incompatible!", 1754 V); 1755 1756 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1757 Attrs.hasAttribute(Attribute::WriteOnly)), 1758 "Attributes " 1759 "'readnone and writeonly' are incompatible!", 1760 V); 1761 1762 Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) && 1763 Attrs.hasAttribute(Attribute::WriteOnly)), 1764 "Attributes " 1765 "'readonly and writeonly' are incompatible!", 1766 V); 1767 1768 Assert(!(Attrs.hasAttribute(Attribute::NoInline) && 1769 Attrs.hasAttribute(Attribute::AlwaysInline)), 1770 "Attributes " 1771 "'noinline and alwaysinline' are incompatible!", 1772 V); 1773 1774 AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty); 1775 Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs), 1776 "Wrong types for attribute: " + 1777 AttributeSet::get(Context, IncompatibleAttrs).getAsString(), 1778 V); 1779 1780 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1781 SmallPtrSet<Type*, 4> Visited; 1782 if (!PTy->getElementType()->isSized(&Visited)) { 1783 Assert(!Attrs.hasAttribute(Attribute::ByVal) && 1784 !Attrs.hasAttribute(Attribute::ByRef) && 1785 !Attrs.hasAttribute(Attribute::InAlloca) && 1786 !Attrs.hasAttribute(Attribute::Preallocated), 1787 "Attributes 'byval', 'byref', 'inalloca', and 'preallocated' do not " 1788 "support unsized types!", 1789 V); 1790 } 1791 if (!isa<PointerType>(PTy->getElementType())) 1792 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1793 "Attribute 'swifterror' only applies to parameters " 1794 "with pointer to pointer type!", 1795 V); 1796 1797 if (Attrs.hasAttribute(Attribute::ByRef)) { 1798 Assert(Attrs.getByRefType() == PTy->getElementType(), 1799 "Attribute 'byref' type does not match parameter!", V); 1800 } 1801 1802 if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) { 1803 Assert(Attrs.getByValType() == PTy->getElementType(), 1804 "Attribute 'byval' type does not match parameter!", V); 1805 } 1806 1807 if (Attrs.hasAttribute(Attribute::Preallocated)) { 1808 Assert(Attrs.getPreallocatedType() == PTy->getElementType(), 1809 "Attribute 'preallocated' type does not match parameter!", V); 1810 } 1811 } else { 1812 Assert(!Attrs.hasAttribute(Attribute::ByVal), 1813 "Attribute 'byval' only applies to parameters with pointer type!", 1814 V); 1815 Assert(!Attrs.hasAttribute(Attribute::ByRef), 1816 "Attribute 'byref' only applies to parameters with pointer type!", 1817 V); 1818 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1819 "Attribute 'swifterror' only applies to parameters " 1820 "with pointer type!", 1821 V); 1822 } 1823 } 1824 1825 // Check parameter attributes against a function type. 1826 // The value V is printed in error messages. 1827 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 1828 const Value *V, bool IsIntrinsic) { 1829 if (Attrs.isEmpty()) 1830 return; 1831 1832 bool SawNest = false; 1833 bool SawReturned = false; 1834 bool SawSRet = false; 1835 bool SawSwiftSelf = false; 1836 bool SawSwiftError = false; 1837 1838 // Verify return value attributes. 1839 AttributeSet RetAttrs = Attrs.getRetAttributes(); 1840 Assert((!RetAttrs.hasAttribute(Attribute::ByVal) && 1841 !RetAttrs.hasAttribute(Attribute::Nest) && 1842 !RetAttrs.hasAttribute(Attribute::StructRet) && 1843 !RetAttrs.hasAttribute(Attribute::NoCapture) && 1844 !RetAttrs.hasAttribute(Attribute::NoFree) && 1845 !RetAttrs.hasAttribute(Attribute::Returned) && 1846 !RetAttrs.hasAttribute(Attribute::InAlloca) && 1847 !RetAttrs.hasAttribute(Attribute::Preallocated) && 1848 !RetAttrs.hasAttribute(Attribute::ByRef) && 1849 !RetAttrs.hasAttribute(Attribute::SwiftSelf) && 1850 !RetAttrs.hasAttribute(Attribute::SwiftError)), 1851 "Attributes 'byval', 'inalloca', 'preallocated', 'byref', " 1852 "'nest', 'sret', 'nocapture', 'nofree', " 1853 "'returned', 'swiftself', and 'swifterror' do not apply to return " 1854 "values!", 1855 V); 1856 Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) && 1857 !RetAttrs.hasAttribute(Attribute::WriteOnly) && 1858 !RetAttrs.hasAttribute(Attribute::ReadNone)), 1859 "Attribute '" + RetAttrs.getAsString() + 1860 "' does not apply to function returns", 1861 V); 1862 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V); 1863 1864 // Verify parameter attributes. 1865 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1866 Type *Ty = FT->getParamType(i); 1867 AttributeSet ArgAttrs = Attrs.getParamAttributes(i); 1868 1869 if (!IsIntrinsic) { 1870 Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg), 1871 "immarg attribute only applies to intrinsics",V); 1872 } 1873 1874 verifyParameterAttrs(ArgAttrs, Ty, V); 1875 1876 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 1877 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1878 SawNest = true; 1879 } 1880 1881 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 1882 Assert(!SawReturned, "More than one parameter has attribute returned!", 1883 V); 1884 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1885 "Incompatible argument and return types for 'returned' attribute", 1886 V); 1887 SawReturned = true; 1888 } 1889 1890 if (ArgAttrs.hasAttribute(Attribute::StructRet)) { 1891 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1892 Assert(i == 0 || i == 1, 1893 "Attribute 'sret' is not on first or second parameter!", V); 1894 SawSRet = true; 1895 } 1896 1897 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) { 1898 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 1899 SawSwiftSelf = true; 1900 } 1901 1902 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) { 1903 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 1904 V); 1905 SawSwiftError = true; 1906 } 1907 1908 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) { 1909 Assert(i == FT->getNumParams() - 1, 1910 "inalloca isn't on the last parameter!", V); 1911 } 1912 } 1913 1914 if (!Attrs.hasAttributes(AttributeList::FunctionIndex)) 1915 return; 1916 1917 verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V); 1918 1919 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1920 Attrs.hasFnAttribute(Attribute::ReadOnly)), 1921 "Attributes 'readnone and readonly' are incompatible!", V); 1922 1923 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1924 Attrs.hasFnAttribute(Attribute::WriteOnly)), 1925 "Attributes 'readnone and writeonly' are incompatible!", V); 1926 1927 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) && 1928 Attrs.hasFnAttribute(Attribute::WriteOnly)), 1929 "Attributes 'readonly and writeonly' are incompatible!", V); 1930 1931 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1932 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)), 1933 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are " 1934 "incompatible!", 1935 V); 1936 1937 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 1938 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)), 1939 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 1940 1941 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) && 1942 Attrs.hasFnAttribute(Attribute::AlwaysInline)), 1943 "Attributes 'noinline and alwaysinline' are incompatible!", V); 1944 1945 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) { 1946 Assert(Attrs.hasFnAttribute(Attribute::NoInline), 1947 "Attribute 'optnone' requires 'noinline'!", V); 1948 1949 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize), 1950 "Attributes 'optsize and optnone' are incompatible!", V); 1951 1952 Assert(!Attrs.hasFnAttribute(Attribute::MinSize), 1953 "Attributes 'minsize and optnone' are incompatible!", V); 1954 } 1955 1956 if (Attrs.hasFnAttribute(Attribute::JumpTable)) { 1957 const GlobalValue *GV = cast<GlobalValue>(V); 1958 Assert(GV->hasGlobalUnnamedAddr(), 1959 "Attribute 'jumptable' requires 'unnamed_addr'", V); 1960 } 1961 1962 if (Attrs.hasFnAttribute(Attribute::AllocSize)) { 1963 std::pair<unsigned, Optional<unsigned>> Args = 1964 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex); 1965 1966 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 1967 if (ParamNo >= FT->getNumParams()) { 1968 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 1969 return false; 1970 } 1971 1972 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 1973 CheckFailed("'allocsize' " + Name + 1974 " argument must refer to an integer parameter", 1975 V); 1976 return false; 1977 } 1978 1979 return true; 1980 }; 1981 1982 if (!CheckParam("element size", Args.first)) 1983 return; 1984 1985 if (Args.second && !CheckParam("number of elements", *Args.second)) 1986 return; 1987 } 1988 1989 if (Attrs.hasFnAttribute("frame-pointer")) { 1990 StringRef FP = Attrs.getAttribute(AttributeList::FunctionIndex, 1991 "frame-pointer").getValueAsString(); 1992 if (FP != "all" && FP != "non-leaf" && FP != "none") 1993 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V); 1994 } 1995 1996 if (Attrs.hasFnAttribute("patchable-function-prefix")) { 1997 StringRef S = Attrs 1998 .getAttribute(AttributeList::FunctionIndex, 1999 "patchable-function-prefix") 2000 .getValueAsString(); 2001 unsigned N; 2002 if (S.getAsInteger(10, N)) 2003 CheckFailed( 2004 "\"patchable-function-prefix\" takes an unsigned integer: " + S, V); 2005 } 2006 if (Attrs.hasFnAttribute("patchable-function-entry")) { 2007 StringRef S = Attrs 2008 .getAttribute(AttributeList::FunctionIndex, 2009 "patchable-function-entry") 2010 .getValueAsString(); 2011 unsigned N; 2012 if (S.getAsInteger(10, N)) 2013 CheckFailed( 2014 "\"patchable-function-entry\" takes an unsigned integer: " + S, V); 2015 } 2016 } 2017 2018 void Verifier::verifyFunctionMetadata( 2019 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 2020 for (const auto &Pair : MDs) { 2021 if (Pair.first == LLVMContext::MD_prof) { 2022 MDNode *MD = Pair.second; 2023 Assert(MD->getNumOperands() >= 2, 2024 "!prof annotations should have no less than 2 operands", MD); 2025 2026 // Check first operand. 2027 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 2028 MD); 2029 Assert(isa<MDString>(MD->getOperand(0)), 2030 "expected string with name of the !prof annotation", MD); 2031 MDString *MDS = cast<MDString>(MD->getOperand(0)); 2032 StringRef ProfName = MDS->getString(); 2033 Assert(ProfName.equals("function_entry_count") || 2034 ProfName.equals("synthetic_function_entry_count"), 2035 "first operand should be 'function_entry_count'" 2036 " or 'synthetic_function_entry_count'", 2037 MD); 2038 2039 // Check second operand. 2040 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 2041 MD); 2042 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 2043 "expected integer argument to function_entry_count", MD); 2044 } 2045 } 2046 } 2047 2048 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 2049 if (!ConstantExprVisited.insert(EntryC).second) 2050 return; 2051 2052 SmallVector<const Constant *, 16> Stack; 2053 Stack.push_back(EntryC); 2054 2055 while (!Stack.empty()) { 2056 const Constant *C = Stack.pop_back_val(); 2057 2058 // Check this constant expression. 2059 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 2060 visitConstantExpr(CE); 2061 2062 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 2063 // Global Values get visited separately, but we do need to make sure 2064 // that the global value is in the correct module 2065 Assert(GV->getParent() == &M, "Referencing global in another module!", 2066 EntryC, &M, GV, GV->getParent()); 2067 continue; 2068 } 2069 2070 // Visit all sub-expressions. 2071 for (const Use &U : C->operands()) { 2072 const auto *OpC = dyn_cast<Constant>(U); 2073 if (!OpC) 2074 continue; 2075 if (!ConstantExprVisited.insert(OpC).second) 2076 continue; 2077 Stack.push_back(OpC); 2078 } 2079 } 2080 } 2081 2082 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 2083 if (CE->getOpcode() == Instruction::BitCast) 2084 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 2085 CE->getType()), 2086 "Invalid bitcast", CE); 2087 2088 if (CE->getOpcode() == Instruction::IntToPtr || 2089 CE->getOpcode() == Instruction::PtrToInt) { 2090 auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr 2091 ? CE->getType() 2092 : CE->getOperand(0)->getType(); 2093 StringRef Msg = CE->getOpcode() == Instruction::IntToPtr 2094 ? "inttoptr not supported for non-integral pointers" 2095 : "ptrtoint not supported for non-integral pointers"; 2096 Assert( 2097 !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())), 2098 Msg); 2099 } 2100 } 2101 2102 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) { 2103 // There shouldn't be more attribute sets than there are parameters plus the 2104 // function and return value. 2105 return Attrs.getNumAttrSets() <= Params + 2; 2106 } 2107 2108 /// Verify that statepoint intrinsic is well formed. 2109 void Verifier::verifyStatepoint(const CallBase &Call) { 2110 assert(Call.getCalledFunction() && 2111 Call.getCalledFunction()->getIntrinsicID() == 2112 Intrinsic::experimental_gc_statepoint); 2113 2114 Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() && 2115 !Call.onlyAccessesArgMemory(), 2116 "gc.statepoint must read and write all memory to preserve " 2117 "reordering restrictions required by safepoint semantics", 2118 Call); 2119 2120 const int64_t NumPatchBytes = 2121 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue(); 2122 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 2123 Assert(NumPatchBytes >= 0, 2124 "gc.statepoint number of patchable bytes must be " 2125 "positive", 2126 Call); 2127 2128 const Value *Target = Call.getArgOperand(2); 2129 auto *PT = dyn_cast<PointerType>(Target->getType()); 2130 Assert(PT && PT->getElementType()->isFunctionTy(), 2131 "gc.statepoint callee must be of function pointer type", Call, Target); 2132 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 2133 2134 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue(); 2135 Assert(NumCallArgs >= 0, 2136 "gc.statepoint number of arguments to underlying call " 2137 "must be positive", 2138 Call); 2139 const int NumParams = (int)TargetFuncType->getNumParams(); 2140 if (TargetFuncType->isVarArg()) { 2141 Assert(NumCallArgs >= NumParams, 2142 "gc.statepoint mismatch in number of vararg call args", Call); 2143 2144 // TODO: Remove this limitation 2145 Assert(TargetFuncType->getReturnType()->isVoidTy(), 2146 "gc.statepoint doesn't support wrapping non-void " 2147 "vararg functions yet", 2148 Call); 2149 } else 2150 Assert(NumCallArgs == NumParams, 2151 "gc.statepoint mismatch in number of call args", Call); 2152 2153 const uint64_t Flags 2154 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue(); 2155 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 2156 "unknown flag used in gc.statepoint flags argument", Call); 2157 2158 // Verify that the types of the call parameter arguments match 2159 // the type of the wrapped callee. 2160 AttributeList Attrs = Call.getAttributes(); 2161 for (int i = 0; i < NumParams; i++) { 2162 Type *ParamType = TargetFuncType->getParamType(i); 2163 Type *ArgType = Call.getArgOperand(5 + i)->getType(); 2164 Assert(ArgType == ParamType, 2165 "gc.statepoint call argument does not match wrapped " 2166 "function type", 2167 Call); 2168 2169 if (TargetFuncType->isVarArg()) { 2170 AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i); 2171 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 2172 "Attribute 'sret' cannot be used for vararg call arguments!", 2173 Call); 2174 } 2175 } 2176 2177 const int EndCallArgsInx = 4 + NumCallArgs; 2178 2179 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1); 2180 Assert(isa<ConstantInt>(NumTransitionArgsV), 2181 "gc.statepoint number of transition arguments " 2182 "must be constant integer", 2183 Call); 2184 const int NumTransitionArgs = 2185 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 2186 Assert(NumTransitionArgs == 0, 2187 "gc.statepoint w/inline transition bundle is deprecated", Call); 2188 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 2189 2190 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1); 2191 Assert(isa<ConstantInt>(NumDeoptArgsV), 2192 "gc.statepoint number of deoptimization arguments " 2193 "must be constant integer", 2194 Call); 2195 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 2196 Assert(NumDeoptArgs == 0, 2197 "gc.statepoint w/inline deopt operands is deprecated", Call); 2198 2199 const int ExpectedNumArgs = 7 + NumCallArgs; 2200 Assert(ExpectedNumArgs == (int)Call.arg_size(), 2201 "gc.statepoint too many arguments", Call); 2202 2203 // Check that the only uses of this gc.statepoint are gc.result or 2204 // gc.relocate calls which are tied to this statepoint and thus part 2205 // of the same statepoint sequence 2206 for (const User *U : Call.users()) { 2207 const CallInst *UserCall = dyn_cast<const CallInst>(U); 2208 Assert(UserCall, "illegal use of statepoint token", Call, U); 2209 if (!UserCall) 2210 continue; 2211 Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall), 2212 "gc.result or gc.relocate are the only value uses " 2213 "of a gc.statepoint", 2214 Call, U); 2215 if (isa<GCResultInst>(UserCall)) { 2216 Assert(UserCall->getArgOperand(0) == &Call, 2217 "gc.result connected to wrong gc.statepoint", Call, UserCall); 2218 } else if (isa<GCRelocateInst>(Call)) { 2219 Assert(UserCall->getArgOperand(0) == &Call, 2220 "gc.relocate connected to wrong gc.statepoint", Call, UserCall); 2221 } 2222 } 2223 2224 // Note: It is legal for a single derived pointer to be listed multiple 2225 // times. It's non-optimal, but it is legal. It can also happen after 2226 // insertion if we strip a bitcast away. 2227 // Note: It is really tempting to check that each base is relocated and 2228 // that a derived pointer is never reused as a base pointer. This turns 2229 // out to be problematic since optimizations run after safepoint insertion 2230 // can recognize equality properties that the insertion logic doesn't know 2231 // about. See example statepoint.ll in the verifier subdirectory 2232 } 2233 2234 void Verifier::verifyFrameRecoverIndices() { 2235 for (auto &Counts : FrameEscapeInfo) { 2236 Function *F = Counts.first; 2237 unsigned EscapedObjectCount = Counts.second.first; 2238 unsigned MaxRecoveredIndex = Counts.second.second; 2239 Assert(MaxRecoveredIndex <= EscapedObjectCount, 2240 "all indices passed to llvm.localrecover must be less than the " 2241 "number of arguments passed to llvm.localescape in the parent " 2242 "function", 2243 F); 2244 } 2245 } 2246 2247 static Instruction *getSuccPad(Instruction *Terminator) { 2248 BasicBlock *UnwindDest; 2249 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 2250 UnwindDest = II->getUnwindDest(); 2251 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 2252 UnwindDest = CSI->getUnwindDest(); 2253 else 2254 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 2255 return UnwindDest->getFirstNonPHI(); 2256 } 2257 2258 void Verifier::verifySiblingFuncletUnwinds() { 2259 SmallPtrSet<Instruction *, 8> Visited; 2260 SmallPtrSet<Instruction *, 8> Active; 2261 for (const auto &Pair : SiblingFuncletInfo) { 2262 Instruction *PredPad = Pair.first; 2263 if (Visited.count(PredPad)) 2264 continue; 2265 Active.insert(PredPad); 2266 Instruction *Terminator = Pair.second; 2267 do { 2268 Instruction *SuccPad = getSuccPad(Terminator); 2269 if (Active.count(SuccPad)) { 2270 // Found a cycle; report error 2271 Instruction *CyclePad = SuccPad; 2272 SmallVector<Instruction *, 8> CycleNodes; 2273 do { 2274 CycleNodes.push_back(CyclePad); 2275 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad]; 2276 if (CycleTerminator != CyclePad) 2277 CycleNodes.push_back(CycleTerminator); 2278 CyclePad = getSuccPad(CycleTerminator); 2279 } while (CyclePad != SuccPad); 2280 Assert(false, "EH pads can't handle each other's exceptions", 2281 ArrayRef<Instruction *>(CycleNodes)); 2282 } 2283 // Don't re-walk a node we've already checked 2284 if (!Visited.insert(SuccPad).second) 2285 break; 2286 // Walk to this successor if it has a map entry. 2287 PredPad = SuccPad; 2288 auto TermI = SiblingFuncletInfo.find(PredPad); 2289 if (TermI == SiblingFuncletInfo.end()) 2290 break; 2291 Terminator = TermI->second; 2292 Active.insert(PredPad); 2293 } while (true); 2294 // Each node only has one successor, so we've walked all the active 2295 // nodes' successors. 2296 Active.clear(); 2297 } 2298 } 2299 2300 // visitFunction - Verify that a function is ok. 2301 // 2302 void Verifier::visitFunction(const Function &F) { 2303 visitGlobalValue(F); 2304 2305 // Check function arguments. 2306 FunctionType *FT = F.getFunctionType(); 2307 unsigned NumArgs = F.arg_size(); 2308 2309 Assert(&Context == &F.getContext(), 2310 "Function context does not match Module context!", &F); 2311 2312 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 2313 Assert(FT->getNumParams() == NumArgs, 2314 "# formal arguments must match # of arguments for function type!", &F, 2315 FT); 2316 Assert(F.getReturnType()->isFirstClassType() || 2317 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 2318 "Functions cannot return aggregate values!", &F); 2319 2320 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 2321 "Invalid struct return type!", &F); 2322 2323 AttributeList Attrs = F.getAttributes(); 2324 2325 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 2326 "Attribute after last parameter!", &F); 2327 2328 bool isLLVMdotName = F.getName().size() >= 5 && 2329 F.getName().substr(0, 5) == "llvm."; 2330 2331 // Check function attributes. 2332 verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName); 2333 2334 // On function declarations/definitions, we do not support the builtin 2335 // attribute. We do not check this in VerifyFunctionAttrs since that is 2336 // checking for Attributes that can/can not ever be on functions. 2337 Assert(!Attrs.hasFnAttribute(Attribute::Builtin), 2338 "Attribute 'builtin' can only be applied to a callsite.", &F); 2339 2340 // Check that this function meets the restrictions on this calling convention. 2341 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 2342 // restrictions can be lifted. 2343 switch (F.getCallingConv()) { 2344 default: 2345 case CallingConv::C: 2346 break; 2347 case CallingConv::X86_INTR: { 2348 Assert(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute::ByVal), 2349 "Calling convention parameter requires byval", &F); 2350 break; 2351 } 2352 case CallingConv::AMDGPU_KERNEL: 2353 case CallingConv::SPIR_KERNEL: 2354 Assert(F.getReturnType()->isVoidTy(), 2355 "Calling convention requires void return type", &F); 2356 LLVM_FALLTHROUGH; 2357 case CallingConv::AMDGPU_VS: 2358 case CallingConv::AMDGPU_HS: 2359 case CallingConv::AMDGPU_GS: 2360 case CallingConv::AMDGPU_PS: 2361 case CallingConv::AMDGPU_CS: 2362 Assert(!F.hasStructRetAttr(), 2363 "Calling convention does not allow sret", &F); 2364 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) { 2365 const unsigned StackAS = DL.getAllocaAddrSpace(); 2366 unsigned i = 0; 2367 for (const Argument &Arg : F.args()) { 2368 Assert(!Attrs.hasParamAttribute(i, Attribute::ByVal), 2369 "Calling convention disallows byval", &F); 2370 Assert(!Attrs.hasParamAttribute(i, Attribute::Preallocated), 2371 "Calling convention disallows preallocated", &F); 2372 Assert(!Attrs.hasParamAttribute(i, Attribute::InAlloca), 2373 "Calling convention disallows inalloca", &F); 2374 2375 if (Attrs.hasParamAttribute(i, Attribute::ByRef)) { 2376 // FIXME: Should also disallow LDS and GDS, but we don't have the enum 2377 // value here. 2378 Assert(Arg.getType()->getPointerAddressSpace() != StackAS, 2379 "Calling convention disallows stack byref", &F); 2380 } 2381 2382 ++i; 2383 } 2384 } 2385 2386 LLVM_FALLTHROUGH; 2387 case CallingConv::Fast: 2388 case CallingConv::Cold: 2389 case CallingConv::Intel_OCL_BI: 2390 case CallingConv::PTX_Kernel: 2391 case CallingConv::PTX_Device: 2392 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 2393 "perfect forwarding!", 2394 &F); 2395 break; 2396 } 2397 2398 // Check that the argument values match the function type for this function... 2399 unsigned i = 0; 2400 for (const Argument &Arg : F.args()) { 2401 Assert(Arg.getType() == FT->getParamType(i), 2402 "Argument value does not match function argument type!", &Arg, 2403 FT->getParamType(i)); 2404 Assert(Arg.getType()->isFirstClassType(), 2405 "Function arguments must have first-class types!", &Arg); 2406 if (!isLLVMdotName) { 2407 Assert(!Arg.getType()->isMetadataTy(), 2408 "Function takes metadata but isn't an intrinsic", &Arg, &F); 2409 Assert(!Arg.getType()->isTokenTy(), 2410 "Function takes token but isn't an intrinsic", &Arg, &F); 2411 } 2412 2413 // Check that swifterror argument is only used by loads and stores. 2414 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) { 2415 verifySwiftErrorValue(&Arg); 2416 } 2417 ++i; 2418 } 2419 2420 if (!isLLVMdotName) 2421 Assert(!F.getReturnType()->isTokenTy(), 2422 "Functions returns a token but isn't an intrinsic", &F); 2423 2424 // Get the function metadata attachments. 2425 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2426 F.getAllMetadata(MDs); 2427 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 2428 verifyFunctionMetadata(MDs); 2429 2430 // Check validity of the personality function 2431 if (F.hasPersonalityFn()) { 2432 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 2433 if (Per) 2434 Assert(Per->getParent() == F.getParent(), 2435 "Referencing personality function in another module!", 2436 &F, F.getParent(), Per, Per->getParent()); 2437 } 2438 2439 if (F.isMaterializable()) { 2440 // Function has a body somewhere we can't see. 2441 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 2442 MDs.empty() ? nullptr : MDs.front().second); 2443 } else if (F.isDeclaration()) { 2444 for (const auto &I : MDs) { 2445 // This is used for call site debug information. 2446 AssertDI(I.first != LLVMContext::MD_dbg || 2447 !cast<DISubprogram>(I.second)->isDistinct(), 2448 "function declaration may only have a unique !dbg attachment", 2449 &F); 2450 Assert(I.first != LLVMContext::MD_prof, 2451 "function declaration may not have a !prof attachment", &F); 2452 2453 // Verify the metadata itself. 2454 visitMDNode(*I.second, AreDebugLocsAllowed::Yes); 2455 } 2456 Assert(!F.hasPersonalityFn(), 2457 "Function declaration shouldn't have a personality routine", &F); 2458 } else { 2459 // Verify that this function (which has a body) is not named "llvm.*". It 2460 // is not legal to define intrinsics. 2461 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 2462 2463 // Check the entry node 2464 const BasicBlock *Entry = &F.getEntryBlock(); 2465 Assert(pred_empty(Entry), 2466 "Entry block to function must not have predecessors!", Entry); 2467 2468 // The address of the entry block cannot be taken, unless it is dead. 2469 if (Entry->hasAddressTaken()) { 2470 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 2471 "blockaddress may not be used with the entry block!", Entry); 2472 } 2473 2474 unsigned NumDebugAttachments = 0, NumProfAttachments = 0; 2475 // Visit metadata attachments. 2476 for (const auto &I : MDs) { 2477 // Verify that the attachment is legal. 2478 auto AllowLocs = AreDebugLocsAllowed::No; 2479 switch (I.first) { 2480 default: 2481 break; 2482 case LLVMContext::MD_dbg: { 2483 ++NumDebugAttachments; 2484 AssertDI(NumDebugAttachments == 1, 2485 "function must have a single !dbg attachment", &F, I.second); 2486 AssertDI(isa<DISubprogram>(I.second), 2487 "function !dbg attachment must be a subprogram", &F, I.second); 2488 AssertDI(cast<DISubprogram>(I.second)->isDistinct(), 2489 "function definition may only have a distinct !dbg attachment", 2490 &F); 2491 2492 auto *SP = cast<DISubprogram>(I.second); 2493 const Function *&AttachedTo = DISubprogramAttachments[SP]; 2494 AssertDI(!AttachedTo || AttachedTo == &F, 2495 "DISubprogram attached to more than one function", SP, &F); 2496 AttachedTo = &F; 2497 AllowLocs = AreDebugLocsAllowed::Yes; 2498 break; 2499 } 2500 case LLVMContext::MD_prof: 2501 ++NumProfAttachments; 2502 Assert(NumProfAttachments == 1, 2503 "function must have a single !prof attachment", &F, I.second); 2504 break; 2505 } 2506 2507 // Verify the metadata itself. 2508 visitMDNode(*I.second, AllowLocs); 2509 } 2510 } 2511 2512 // If this function is actually an intrinsic, verify that it is only used in 2513 // direct call/invokes, never having its "address taken". 2514 // Only do this if the module is materialized, otherwise we don't have all the 2515 // uses. 2516 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2517 const User *U; 2518 if (F.hasAddressTaken(&U)) 2519 Assert(false, "Invalid user of intrinsic instruction!", U); 2520 } 2521 2522 auto *N = F.getSubprogram(); 2523 HasDebugInfo = (N != nullptr); 2524 if (!HasDebugInfo) 2525 return; 2526 2527 // Check that all !dbg attachments lead to back to N. 2528 // 2529 // FIXME: Check this incrementally while visiting !dbg attachments. 2530 // FIXME: Only check when N is the canonical subprogram for F. 2531 SmallPtrSet<const MDNode *, 32> Seen; 2532 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) { 2533 // Be careful about using DILocation here since we might be dealing with 2534 // broken code (this is the Verifier after all). 2535 const DILocation *DL = dyn_cast_or_null<DILocation>(Node); 2536 if (!DL) 2537 return; 2538 if (!Seen.insert(DL).second) 2539 return; 2540 2541 Metadata *Parent = DL->getRawScope(); 2542 AssertDI(Parent && isa<DILocalScope>(Parent), 2543 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, 2544 Parent); 2545 2546 DILocalScope *Scope = DL->getInlinedAtScope(); 2547 Assert(Scope, "Failed to find DILocalScope", DL); 2548 2549 if (!Seen.insert(Scope).second) 2550 return; 2551 2552 DISubprogram *SP = Scope->getSubprogram(); 2553 2554 // Scope and SP could be the same MDNode and we don't want to skip 2555 // validation in that case 2556 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2557 return; 2558 2559 AssertDI(SP->describes(&F), 2560 "!dbg attachment points at wrong subprogram for function", N, &F, 2561 &I, DL, Scope, SP); 2562 }; 2563 for (auto &BB : F) 2564 for (auto &I : BB) { 2565 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode()); 2566 // The llvm.loop annotations also contain two DILocations. 2567 if (auto MD = I.getMetadata(LLVMContext::MD_loop)) 2568 for (unsigned i = 1; i < MD->getNumOperands(); ++i) 2569 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i))); 2570 if (BrokenDebugInfo) 2571 return; 2572 } 2573 } 2574 2575 // verifyBasicBlock - Verify that a basic block is well formed... 2576 // 2577 void Verifier::visitBasicBlock(BasicBlock &BB) { 2578 InstsInThisBlock.clear(); 2579 2580 // Ensure that basic blocks have terminators! 2581 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2582 2583 // Check constraints that this basic block imposes on all of the PHI nodes in 2584 // it. 2585 if (isa<PHINode>(BB.front())) { 2586 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB)); 2587 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2588 llvm::sort(Preds); 2589 for (const PHINode &PN : BB.phis()) { 2590 Assert(PN.getNumIncomingValues() == Preds.size(), 2591 "PHINode should have one entry for each predecessor of its " 2592 "parent basic block!", 2593 &PN); 2594 2595 // Get and sort all incoming values in the PHI node... 2596 Values.clear(); 2597 Values.reserve(PN.getNumIncomingValues()); 2598 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 2599 Values.push_back( 2600 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i))); 2601 llvm::sort(Values); 2602 2603 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2604 // Check to make sure that if there is more than one entry for a 2605 // particular basic block in this PHI node, that the incoming values are 2606 // all identical. 2607 // 2608 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2609 Values[i].second == Values[i - 1].second, 2610 "PHI node has multiple entries for the same basic block with " 2611 "different incoming values!", 2612 &PN, Values[i].first, Values[i].second, Values[i - 1].second); 2613 2614 // Check to make sure that the predecessors and PHI node entries are 2615 // matched up. 2616 Assert(Values[i].first == Preds[i], 2617 "PHI node entries do not match predecessors!", &PN, 2618 Values[i].first, Preds[i]); 2619 } 2620 } 2621 } 2622 2623 // Check that all instructions have their parent pointers set up correctly. 2624 for (auto &I : BB) 2625 { 2626 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2627 } 2628 } 2629 2630 void Verifier::visitTerminator(Instruction &I) { 2631 // Ensure that terminators only exist at the end of the basic block. 2632 Assert(&I == I.getParent()->getTerminator(), 2633 "Terminator found in the middle of a basic block!", I.getParent()); 2634 visitInstruction(I); 2635 } 2636 2637 void Verifier::visitBranchInst(BranchInst &BI) { 2638 if (BI.isConditional()) { 2639 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2640 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2641 } 2642 visitTerminator(BI); 2643 } 2644 2645 void Verifier::visitReturnInst(ReturnInst &RI) { 2646 Function *F = RI.getParent()->getParent(); 2647 unsigned N = RI.getNumOperands(); 2648 if (F->getReturnType()->isVoidTy()) 2649 Assert(N == 0, 2650 "Found return instr that returns non-void in Function of void " 2651 "return type!", 2652 &RI, F->getReturnType()); 2653 else 2654 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2655 "Function return type does not match operand " 2656 "type of return inst!", 2657 &RI, F->getReturnType()); 2658 2659 // Check to make sure that the return value has necessary properties for 2660 // terminators... 2661 visitTerminator(RI); 2662 } 2663 2664 void Verifier::visitSwitchInst(SwitchInst &SI) { 2665 // Check to make sure that all of the constants in the switch instruction 2666 // have the same type as the switched-on value. 2667 Type *SwitchTy = SI.getCondition()->getType(); 2668 SmallPtrSet<ConstantInt*, 32> Constants; 2669 for (auto &Case : SI.cases()) { 2670 Assert(Case.getCaseValue()->getType() == SwitchTy, 2671 "Switch constants must all be same type as switch value!", &SI); 2672 Assert(Constants.insert(Case.getCaseValue()).second, 2673 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2674 } 2675 2676 visitTerminator(SI); 2677 } 2678 2679 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2680 Assert(BI.getAddress()->getType()->isPointerTy(), 2681 "Indirectbr operand must have pointer type!", &BI); 2682 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2683 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2684 "Indirectbr destinations must all have pointer type!", &BI); 2685 2686 visitTerminator(BI); 2687 } 2688 2689 void Verifier::visitCallBrInst(CallBrInst &CBI) { 2690 Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", 2691 &CBI); 2692 for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i) 2693 Assert(CBI.getSuccessor(i)->getType()->isLabelTy(), 2694 "Callbr successors must all have pointer type!", &CBI); 2695 for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) { 2696 Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)), 2697 "Using an unescaped label as a callbr argument!", &CBI); 2698 if (isa<BasicBlock>(CBI.getOperand(i))) 2699 for (unsigned j = i + 1; j != e; ++j) 2700 Assert(CBI.getOperand(i) != CBI.getOperand(j), 2701 "Duplicate callbr destination!", &CBI); 2702 } 2703 { 2704 SmallPtrSet<BasicBlock *, 4> ArgBBs; 2705 for (Value *V : CBI.args()) 2706 if (auto *BA = dyn_cast<BlockAddress>(V)) 2707 ArgBBs.insert(BA->getBasicBlock()); 2708 for (BasicBlock *BB : CBI.getIndirectDests()) 2709 Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI); 2710 } 2711 2712 visitTerminator(CBI); 2713 } 2714 2715 void Verifier::visitSelectInst(SelectInst &SI) { 2716 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2717 SI.getOperand(2)), 2718 "Invalid operands for select instruction!", &SI); 2719 2720 Assert(SI.getTrueValue()->getType() == SI.getType(), 2721 "Select values must have same type as select instruction!", &SI); 2722 visitInstruction(SI); 2723 } 2724 2725 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2726 /// a pass, if any exist, it's an error. 2727 /// 2728 void Verifier::visitUserOp1(Instruction &I) { 2729 Assert(false, "User-defined operators should not live outside of a pass!", &I); 2730 } 2731 2732 void Verifier::visitTruncInst(TruncInst &I) { 2733 // Get the source and destination types 2734 Type *SrcTy = I.getOperand(0)->getType(); 2735 Type *DestTy = I.getType(); 2736 2737 // Get the size of the types in bits, we'll need this later 2738 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2739 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2740 2741 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2742 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2743 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2744 "trunc source and destination must both be a vector or neither", &I); 2745 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2746 2747 visitInstruction(I); 2748 } 2749 2750 void Verifier::visitZExtInst(ZExtInst &I) { 2751 // Get the source and destination types 2752 Type *SrcTy = I.getOperand(0)->getType(); 2753 Type *DestTy = I.getType(); 2754 2755 // Get the size of the types in bits, we'll need this later 2756 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2757 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2758 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2759 "zext source and destination must both be a vector or neither", &I); 2760 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2761 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2762 2763 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2764 2765 visitInstruction(I); 2766 } 2767 2768 void Verifier::visitSExtInst(SExtInst &I) { 2769 // Get the source and destination types 2770 Type *SrcTy = I.getOperand(0)->getType(); 2771 Type *DestTy = I.getType(); 2772 2773 // Get the size of the types in bits, we'll need this later 2774 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2775 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2776 2777 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2778 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2779 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2780 "sext source and destination must both be a vector or neither", &I); 2781 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2782 2783 visitInstruction(I); 2784 } 2785 2786 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2787 // Get the source and destination types 2788 Type *SrcTy = I.getOperand(0)->getType(); 2789 Type *DestTy = I.getType(); 2790 // Get the size of the types in bits, we'll need this later 2791 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2792 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2793 2794 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2795 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2796 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2797 "fptrunc source and destination must both be a vector or neither", &I); 2798 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2799 2800 visitInstruction(I); 2801 } 2802 2803 void Verifier::visitFPExtInst(FPExtInst &I) { 2804 // Get the source and destination types 2805 Type *SrcTy = I.getOperand(0)->getType(); 2806 Type *DestTy = I.getType(); 2807 2808 // Get the size of the types in bits, we'll need this later 2809 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2810 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2811 2812 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2813 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2814 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2815 "fpext source and destination must both be a vector or neither", &I); 2816 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2817 2818 visitInstruction(I); 2819 } 2820 2821 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2822 // Get the source and destination types 2823 Type *SrcTy = I.getOperand(0)->getType(); 2824 Type *DestTy = I.getType(); 2825 2826 bool SrcVec = SrcTy->isVectorTy(); 2827 bool DstVec = DestTy->isVectorTy(); 2828 2829 Assert(SrcVec == DstVec, 2830 "UIToFP source and dest must both be vector or scalar", &I); 2831 Assert(SrcTy->isIntOrIntVectorTy(), 2832 "UIToFP source must be integer or integer vector", &I); 2833 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2834 &I); 2835 2836 if (SrcVec && DstVec) 2837 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2838 cast<VectorType>(DestTy)->getElementCount(), 2839 "UIToFP source and dest vector length mismatch", &I); 2840 2841 visitInstruction(I); 2842 } 2843 2844 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2845 // Get the source and destination types 2846 Type *SrcTy = I.getOperand(0)->getType(); 2847 Type *DestTy = I.getType(); 2848 2849 bool SrcVec = SrcTy->isVectorTy(); 2850 bool DstVec = DestTy->isVectorTy(); 2851 2852 Assert(SrcVec == DstVec, 2853 "SIToFP source and dest must both be vector or scalar", &I); 2854 Assert(SrcTy->isIntOrIntVectorTy(), 2855 "SIToFP source must be integer or integer vector", &I); 2856 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2857 &I); 2858 2859 if (SrcVec && DstVec) 2860 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2861 cast<VectorType>(DestTy)->getElementCount(), 2862 "SIToFP source and dest vector length mismatch", &I); 2863 2864 visitInstruction(I); 2865 } 2866 2867 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2868 // Get the source and destination types 2869 Type *SrcTy = I.getOperand(0)->getType(); 2870 Type *DestTy = I.getType(); 2871 2872 bool SrcVec = SrcTy->isVectorTy(); 2873 bool DstVec = DestTy->isVectorTy(); 2874 2875 Assert(SrcVec == DstVec, 2876 "FPToUI source and dest must both be vector or scalar", &I); 2877 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2878 &I); 2879 Assert(DestTy->isIntOrIntVectorTy(), 2880 "FPToUI result must be integer or integer vector", &I); 2881 2882 if (SrcVec && DstVec) 2883 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2884 cast<VectorType>(DestTy)->getElementCount(), 2885 "FPToUI source and dest vector length mismatch", &I); 2886 2887 visitInstruction(I); 2888 } 2889 2890 void Verifier::visitFPToSIInst(FPToSIInst &I) { 2891 // Get the source and destination types 2892 Type *SrcTy = I.getOperand(0)->getType(); 2893 Type *DestTy = I.getType(); 2894 2895 bool SrcVec = SrcTy->isVectorTy(); 2896 bool DstVec = DestTy->isVectorTy(); 2897 2898 Assert(SrcVec == DstVec, 2899 "FPToSI source and dest must both be vector or scalar", &I); 2900 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 2901 &I); 2902 Assert(DestTy->isIntOrIntVectorTy(), 2903 "FPToSI result must be integer or integer vector", &I); 2904 2905 if (SrcVec && DstVec) 2906 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2907 cast<VectorType>(DestTy)->getElementCount(), 2908 "FPToSI source and dest vector length mismatch", &I); 2909 2910 visitInstruction(I); 2911 } 2912 2913 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 2914 // Get the source and destination types 2915 Type *SrcTy = I.getOperand(0)->getType(); 2916 Type *DestTy = I.getType(); 2917 2918 Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I); 2919 2920 if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType())) 2921 Assert(!DL.isNonIntegralPointerType(PTy), 2922 "ptrtoint not supported for non-integral pointers"); 2923 2924 Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I); 2925 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 2926 &I); 2927 2928 if (SrcTy->isVectorTy()) { 2929 auto *VSrc = cast<VectorType>(SrcTy); 2930 auto *VDest = cast<VectorType>(DestTy); 2931 Assert(VSrc->getElementCount() == VDest->getElementCount(), 2932 "PtrToInt Vector width mismatch", &I); 2933 } 2934 2935 visitInstruction(I); 2936 } 2937 2938 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 2939 // Get the source and destination types 2940 Type *SrcTy = I.getOperand(0)->getType(); 2941 Type *DestTy = I.getType(); 2942 2943 Assert(SrcTy->isIntOrIntVectorTy(), 2944 "IntToPtr source must be an integral", &I); 2945 Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I); 2946 2947 if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType())) 2948 Assert(!DL.isNonIntegralPointerType(PTy), 2949 "inttoptr not supported for non-integral pointers"); 2950 2951 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 2952 &I); 2953 if (SrcTy->isVectorTy()) { 2954 auto *VSrc = cast<VectorType>(SrcTy); 2955 auto *VDest = cast<VectorType>(DestTy); 2956 Assert(VSrc->getElementCount() == VDest->getElementCount(), 2957 "IntToPtr Vector width mismatch", &I); 2958 } 2959 visitInstruction(I); 2960 } 2961 2962 void Verifier::visitBitCastInst(BitCastInst &I) { 2963 Assert( 2964 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 2965 "Invalid bitcast", &I); 2966 visitInstruction(I); 2967 } 2968 2969 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 2970 Type *SrcTy = I.getOperand(0)->getType(); 2971 Type *DestTy = I.getType(); 2972 2973 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 2974 &I); 2975 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 2976 &I); 2977 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 2978 "AddrSpaceCast must be between different address spaces", &I); 2979 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy)) 2980 Assert(SrcVTy->getElementCount() == 2981 cast<VectorType>(DestTy)->getElementCount(), 2982 "AddrSpaceCast vector pointer number of elements mismatch", &I); 2983 visitInstruction(I); 2984 } 2985 2986 /// visitPHINode - Ensure that a PHI node is well formed. 2987 /// 2988 void Verifier::visitPHINode(PHINode &PN) { 2989 // Ensure that the PHI nodes are all grouped together at the top of the block. 2990 // This can be tested by checking whether the instruction before this is 2991 // either nonexistent (because this is begin()) or is a PHI node. If not, 2992 // then there is some other instruction before a PHI. 2993 Assert(&PN == &PN.getParent()->front() || 2994 isa<PHINode>(--BasicBlock::iterator(&PN)), 2995 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 2996 2997 // Check that a PHI doesn't yield a Token. 2998 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 2999 3000 // Check that all of the values of the PHI node have the same type as the 3001 // result, and that the incoming blocks are really basic blocks. 3002 for (Value *IncValue : PN.incoming_values()) { 3003 Assert(PN.getType() == IncValue->getType(), 3004 "PHI node operands are not the same type as the result!", &PN); 3005 } 3006 3007 // All other PHI node constraints are checked in the visitBasicBlock method. 3008 3009 visitInstruction(PN); 3010 } 3011 3012 void Verifier::visitCallBase(CallBase &Call) { 3013 Assert(Call.getCalledOperand()->getType()->isPointerTy(), 3014 "Called function must be a pointer!", Call); 3015 PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType()); 3016 3017 Assert(FPTy->getElementType()->isFunctionTy(), 3018 "Called function is not pointer to function type!", Call); 3019 3020 Assert(FPTy->getElementType() == Call.getFunctionType(), 3021 "Called function is not the same type as the call!", Call); 3022 3023 FunctionType *FTy = Call.getFunctionType(); 3024 3025 // Verify that the correct number of arguments are being passed 3026 if (FTy->isVarArg()) 3027 Assert(Call.arg_size() >= FTy->getNumParams(), 3028 "Called function requires more parameters than were provided!", 3029 Call); 3030 else 3031 Assert(Call.arg_size() == FTy->getNumParams(), 3032 "Incorrect number of arguments passed to called function!", Call); 3033 3034 // Verify that all arguments to the call match the function type. 3035 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3036 Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i), 3037 "Call parameter type does not match function signature!", 3038 Call.getArgOperand(i), FTy->getParamType(i), Call); 3039 3040 AttributeList Attrs = Call.getAttributes(); 3041 3042 Assert(verifyAttributeCount(Attrs, Call.arg_size()), 3043 "Attribute after last parameter!", Call); 3044 3045 bool IsIntrinsic = Call.getCalledFunction() && 3046 Call.getCalledFunction()->getName().startswith("llvm."); 3047 3048 Function *Callee = 3049 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts()); 3050 3051 if (Attrs.hasFnAttribute(Attribute::Speculatable)) { 3052 // Don't allow speculatable on call sites, unless the underlying function 3053 // declaration is also speculatable. 3054 Assert(Callee && Callee->isSpeculatable(), 3055 "speculatable attribute may not apply to call sites", Call); 3056 } 3057 3058 if (Attrs.hasFnAttribute(Attribute::Preallocated)) { 3059 Assert(Call.getCalledFunction()->getIntrinsicID() == 3060 Intrinsic::call_preallocated_arg, 3061 "preallocated as a call site attribute can only be on " 3062 "llvm.call.preallocated.arg"); 3063 } 3064 3065 // Verify call attributes. 3066 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic); 3067 3068 // Conservatively check the inalloca argument. 3069 // We have a bug if we can find that there is an underlying alloca without 3070 // inalloca. 3071 if (Call.hasInAllocaArgument()) { 3072 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1); 3073 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 3074 Assert(AI->isUsedWithInAlloca(), 3075 "inalloca argument for call has mismatched alloca", AI, Call); 3076 } 3077 3078 // For each argument of the callsite, if it has the swifterror argument, 3079 // make sure the underlying alloca/parameter it comes from has a swifterror as 3080 // well. 3081 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3082 if (Call.paramHasAttr(i, Attribute::SwiftError)) { 3083 Value *SwiftErrorArg = Call.getArgOperand(i); 3084 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) { 3085 Assert(AI->isSwiftError(), 3086 "swifterror argument for call has mismatched alloca", AI, Call); 3087 continue; 3088 } 3089 auto ArgI = dyn_cast<Argument>(SwiftErrorArg); 3090 Assert(ArgI, 3091 "swifterror argument should come from an alloca or parameter", 3092 SwiftErrorArg, Call); 3093 Assert(ArgI->hasSwiftErrorAttr(), 3094 "swifterror argument for call has mismatched parameter", ArgI, 3095 Call); 3096 } 3097 3098 if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) { 3099 // Don't allow immarg on call sites, unless the underlying declaration 3100 // also has the matching immarg. 3101 Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg), 3102 "immarg may not apply only to call sites", 3103 Call.getArgOperand(i), Call); 3104 } 3105 3106 if (Call.paramHasAttr(i, Attribute::ImmArg)) { 3107 Value *ArgVal = Call.getArgOperand(i); 3108 Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal), 3109 "immarg operand has non-immediate parameter", ArgVal, Call); 3110 } 3111 3112 if (Call.paramHasAttr(i, Attribute::Preallocated)) { 3113 Value *ArgVal = Call.getArgOperand(i); 3114 bool hasOB = 3115 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0; 3116 bool isMustTail = Call.isMustTailCall(); 3117 Assert(hasOB != isMustTail, 3118 "preallocated operand either requires a preallocated bundle or " 3119 "the call to be musttail (but not both)", 3120 ArgVal, Call); 3121 } 3122 } 3123 3124 if (FTy->isVarArg()) { 3125 // FIXME? is 'nest' even legal here? 3126 bool SawNest = false; 3127 bool SawReturned = false; 3128 3129 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) { 3130 if (Attrs.hasParamAttribute(Idx, Attribute::Nest)) 3131 SawNest = true; 3132 if (Attrs.hasParamAttribute(Idx, Attribute::Returned)) 3133 SawReturned = true; 3134 } 3135 3136 // Check attributes on the varargs part. 3137 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) { 3138 Type *Ty = Call.getArgOperand(Idx)->getType(); 3139 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx); 3140 verifyParameterAttrs(ArgAttrs, Ty, &Call); 3141 3142 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 3143 Assert(!SawNest, "More than one parameter has attribute nest!", Call); 3144 SawNest = true; 3145 } 3146 3147 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 3148 Assert(!SawReturned, "More than one parameter has attribute returned!", 3149 Call); 3150 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 3151 "Incompatible argument and return types for 'returned' " 3152 "attribute", 3153 Call); 3154 SawReturned = true; 3155 } 3156 3157 // Statepoint intrinsic is vararg but the wrapped function may be not. 3158 // Allow sret here and check the wrapped function in verifyStatepoint. 3159 if (!Call.getCalledFunction() || 3160 Call.getCalledFunction()->getIntrinsicID() != 3161 Intrinsic::experimental_gc_statepoint) 3162 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 3163 "Attribute 'sret' cannot be used for vararg call arguments!", 3164 Call); 3165 3166 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) 3167 Assert(Idx == Call.arg_size() - 1, 3168 "inalloca isn't on the last argument!", Call); 3169 } 3170 } 3171 3172 // Verify that there's no metadata unless it's a direct call to an intrinsic. 3173 if (!IsIntrinsic) { 3174 for (Type *ParamTy : FTy->params()) { 3175 Assert(!ParamTy->isMetadataTy(), 3176 "Function has metadata parameter but isn't an intrinsic", Call); 3177 Assert(!ParamTy->isTokenTy(), 3178 "Function has token parameter but isn't an intrinsic", Call); 3179 } 3180 } 3181 3182 // Verify that indirect calls don't return tokens. 3183 if (!Call.getCalledFunction()) 3184 Assert(!FTy->getReturnType()->isTokenTy(), 3185 "Return type cannot be token for indirect call!"); 3186 3187 if (Function *F = Call.getCalledFunction()) 3188 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 3189 visitIntrinsicCall(ID, Call); 3190 3191 // Verify that a callsite has at most one "deopt", at most one "funclet", at 3192 // most one "gc-transition", at most one "cfguardtarget", 3193 // and at most one "preallocated" operand bundle. 3194 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 3195 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false, 3196 FoundPreallocatedBundle = false, FoundGCLiveBundle = false;; 3197 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) { 3198 OperandBundleUse BU = Call.getOperandBundleAt(i); 3199 uint32_t Tag = BU.getTagID(); 3200 if (Tag == LLVMContext::OB_deopt) { 3201 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call); 3202 FoundDeoptBundle = true; 3203 } else if (Tag == LLVMContext::OB_gc_transition) { 3204 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 3205 Call); 3206 FoundGCTransitionBundle = true; 3207 } else if (Tag == LLVMContext::OB_funclet) { 3208 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call); 3209 FoundFuncletBundle = true; 3210 Assert(BU.Inputs.size() == 1, 3211 "Expected exactly one funclet bundle operand", Call); 3212 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 3213 "Funclet bundle operands should correspond to a FuncletPadInst", 3214 Call); 3215 } else if (Tag == LLVMContext::OB_cfguardtarget) { 3216 Assert(!FoundCFGuardTargetBundle, 3217 "Multiple CFGuardTarget operand bundles", Call); 3218 FoundCFGuardTargetBundle = true; 3219 Assert(BU.Inputs.size() == 1, 3220 "Expected exactly one cfguardtarget bundle operand", Call); 3221 } else if (Tag == LLVMContext::OB_preallocated) { 3222 Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles", 3223 Call); 3224 FoundPreallocatedBundle = true; 3225 Assert(BU.Inputs.size() == 1, 3226 "Expected exactly one preallocated bundle operand", Call); 3227 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front()); 3228 Assert(Input && 3229 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup, 3230 "\"preallocated\" argument must be a token from " 3231 "llvm.call.preallocated.setup", 3232 Call); 3233 } else if (Tag == LLVMContext::OB_gc_live) { 3234 Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles", 3235 Call); 3236 FoundGCLiveBundle = true; 3237 } 3238 } 3239 3240 // Verify that each inlinable callsite of a debug-info-bearing function in a 3241 // debug-info-bearing function has a debug location attached to it. Failure to 3242 // do so causes assertion failures when the inliner sets up inline scope info. 3243 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() && 3244 Call.getCalledFunction()->getSubprogram()) 3245 AssertDI(Call.getDebugLoc(), 3246 "inlinable function call in a function with " 3247 "debug info must have a !dbg location", 3248 Call); 3249 3250 visitInstruction(Call); 3251 } 3252 3253 /// Two types are "congruent" if they are identical, or if they are both pointer 3254 /// types with different pointee types and the same address space. 3255 static bool isTypeCongruent(Type *L, Type *R) { 3256 if (L == R) 3257 return true; 3258 PointerType *PL = dyn_cast<PointerType>(L); 3259 PointerType *PR = dyn_cast<PointerType>(R); 3260 if (!PL || !PR) 3261 return false; 3262 return PL->getAddressSpace() == PR->getAddressSpace(); 3263 } 3264 3265 static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) { 3266 static const Attribute::AttrKind ABIAttrs[] = { 3267 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 3268 Attribute::InReg, Attribute::SwiftSelf, Attribute::SwiftError, 3269 Attribute::Preallocated, Attribute::ByRef}; 3270 AttrBuilder Copy; 3271 for (auto AK : ABIAttrs) { 3272 if (Attrs.hasParamAttribute(I, AK)) 3273 Copy.addAttribute(AK); 3274 } 3275 3276 // `align` is ABI-affecting only in combination with `byval` or `byref`. 3277 if (Attrs.hasParamAttribute(I, Attribute::Alignment) && 3278 (Attrs.hasParamAttribute(I, Attribute::ByVal) || 3279 Attrs.hasParamAttribute(I, Attribute::ByRef))) 3280 Copy.addAlignmentAttr(Attrs.getParamAlignment(I)); 3281 return Copy; 3282 } 3283 3284 void Verifier::verifyMustTailCall(CallInst &CI) { 3285 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 3286 3287 // - The caller and callee prototypes must match. Pointer types of 3288 // parameters or return types may differ in pointee type, but not 3289 // address space. 3290 Function *F = CI.getParent()->getParent(); 3291 FunctionType *CallerTy = F->getFunctionType(); 3292 FunctionType *CalleeTy = CI.getFunctionType(); 3293 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) { 3294 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 3295 "cannot guarantee tail call due to mismatched parameter counts", 3296 &CI); 3297 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3298 Assert( 3299 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 3300 "cannot guarantee tail call due to mismatched parameter types", &CI); 3301 } 3302 } 3303 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 3304 "cannot guarantee tail call due to mismatched varargs", &CI); 3305 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 3306 "cannot guarantee tail call due to mismatched return types", &CI); 3307 3308 // - The calling conventions of the caller and callee must match. 3309 Assert(F->getCallingConv() == CI.getCallingConv(), 3310 "cannot guarantee tail call due to mismatched calling conv", &CI); 3311 3312 // - All ABI-impacting function attributes, such as sret, byval, inreg, 3313 // returned, preallocated, and inalloca, must match. 3314 AttributeList CallerAttrs = F->getAttributes(); 3315 AttributeList CalleeAttrs = CI.getAttributes(); 3316 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3317 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 3318 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 3319 Assert(CallerABIAttrs == CalleeABIAttrs, 3320 "cannot guarantee tail call due to mismatched ABI impacting " 3321 "function attributes", 3322 &CI, CI.getOperand(I)); 3323 } 3324 3325 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 3326 // or a pointer bitcast followed by a ret instruction. 3327 // - The ret instruction must return the (possibly bitcasted) value 3328 // produced by the call or void. 3329 Value *RetVal = &CI; 3330 Instruction *Next = CI.getNextNode(); 3331 3332 // Handle the optional bitcast. 3333 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 3334 Assert(BI->getOperand(0) == RetVal, 3335 "bitcast following musttail call must use the call", BI); 3336 RetVal = BI; 3337 Next = BI->getNextNode(); 3338 } 3339 3340 // Check the return. 3341 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 3342 Assert(Ret, "musttail call must precede a ret with an optional bitcast", 3343 &CI); 3344 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 3345 "musttail call result must be returned", Ret); 3346 } 3347 3348 void Verifier::visitCallInst(CallInst &CI) { 3349 visitCallBase(CI); 3350 3351 if (CI.isMustTailCall()) 3352 verifyMustTailCall(CI); 3353 } 3354 3355 void Verifier::visitInvokeInst(InvokeInst &II) { 3356 visitCallBase(II); 3357 3358 // Verify that the first non-PHI instruction of the unwind destination is an 3359 // exception handling instruction. 3360 Assert( 3361 II.getUnwindDest()->isEHPad(), 3362 "The unwind destination does not have an exception handling instruction!", 3363 &II); 3364 3365 visitTerminator(II); 3366 } 3367 3368 /// visitUnaryOperator - Check the argument to the unary operator. 3369 /// 3370 void Verifier::visitUnaryOperator(UnaryOperator &U) { 3371 Assert(U.getType() == U.getOperand(0)->getType(), 3372 "Unary operators must have same type for" 3373 "operands and result!", 3374 &U); 3375 3376 switch (U.getOpcode()) { 3377 // Check that floating-point arithmetic operators are only used with 3378 // floating-point operands. 3379 case Instruction::FNeg: 3380 Assert(U.getType()->isFPOrFPVectorTy(), 3381 "FNeg operator only works with float types!", &U); 3382 break; 3383 default: 3384 llvm_unreachable("Unknown UnaryOperator opcode!"); 3385 } 3386 3387 visitInstruction(U); 3388 } 3389 3390 /// visitBinaryOperator - Check that both arguments to the binary operator are 3391 /// of the same type! 3392 /// 3393 void Verifier::visitBinaryOperator(BinaryOperator &B) { 3394 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 3395 "Both operands to a binary operator are not of the same type!", &B); 3396 3397 switch (B.getOpcode()) { 3398 // Check that integer arithmetic operators are only used with 3399 // integral operands. 3400 case Instruction::Add: 3401 case Instruction::Sub: 3402 case Instruction::Mul: 3403 case Instruction::SDiv: 3404 case Instruction::UDiv: 3405 case Instruction::SRem: 3406 case Instruction::URem: 3407 Assert(B.getType()->isIntOrIntVectorTy(), 3408 "Integer arithmetic operators only work with integral types!", &B); 3409 Assert(B.getType() == B.getOperand(0)->getType(), 3410 "Integer arithmetic operators must have same type " 3411 "for operands and result!", 3412 &B); 3413 break; 3414 // Check that floating-point arithmetic operators are only used with 3415 // floating-point operands. 3416 case Instruction::FAdd: 3417 case Instruction::FSub: 3418 case Instruction::FMul: 3419 case Instruction::FDiv: 3420 case Instruction::FRem: 3421 Assert(B.getType()->isFPOrFPVectorTy(), 3422 "Floating-point arithmetic operators only work with " 3423 "floating-point types!", 3424 &B); 3425 Assert(B.getType() == B.getOperand(0)->getType(), 3426 "Floating-point arithmetic operators must have same type " 3427 "for operands and result!", 3428 &B); 3429 break; 3430 // Check that logical operators are only used with integral operands. 3431 case Instruction::And: 3432 case Instruction::Or: 3433 case Instruction::Xor: 3434 Assert(B.getType()->isIntOrIntVectorTy(), 3435 "Logical operators only work with integral types!", &B); 3436 Assert(B.getType() == B.getOperand(0)->getType(), 3437 "Logical operators must have same type for operands and result!", 3438 &B); 3439 break; 3440 case Instruction::Shl: 3441 case Instruction::LShr: 3442 case Instruction::AShr: 3443 Assert(B.getType()->isIntOrIntVectorTy(), 3444 "Shifts only work with integral types!", &B); 3445 Assert(B.getType() == B.getOperand(0)->getType(), 3446 "Shift return type must be same as operands!", &B); 3447 break; 3448 default: 3449 llvm_unreachable("Unknown BinaryOperator opcode!"); 3450 } 3451 3452 visitInstruction(B); 3453 } 3454 3455 void Verifier::visitICmpInst(ICmpInst &IC) { 3456 // Check that the operands are the same type 3457 Type *Op0Ty = IC.getOperand(0)->getType(); 3458 Type *Op1Ty = IC.getOperand(1)->getType(); 3459 Assert(Op0Ty == Op1Ty, 3460 "Both operands to ICmp instruction are not of the same type!", &IC); 3461 // Check that the operands are the right type 3462 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(), 3463 "Invalid operand types for ICmp instruction", &IC); 3464 // Check that the predicate is valid. 3465 Assert(IC.isIntPredicate(), 3466 "Invalid predicate in ICmp instruction!", &IC); 3467 3468 visitInstruction(IC); 3469 } 3470 3471 void Verifier::visitFCmpInst(FCmpInst &FC) { 3472 // Check that the operands are the same type 3473 Type *Op0Ty = FC.getOperand(0)->getType(); 3474 Type *Op1Ty = FC.getOperand(1)->getType(); 3475 Assert(Op0Ty == Op1Ty, 3476 "Both operands to FCmp instruction are not of the same type!", &FC); 3477 // Check that the operands are the right type 3478 Assert(Op0Ty->isFPOrFPVectorTy(), 3479 "Invalid operand types for FCmp instruction", &FC); 3480 // Check that the predicate is valid. 3481 Assert(FC.isFPPredicate(), 3482 "Invalid predicate in FCmp instruction!", &FC); 3483 3484 visitInstruction(FC); 3485 } 3486 3487 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 3488 Assert( 3489 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 3490 "Invalid extractelement operands!", &EI); 3491 visitInstruction(EI); 3492 } 3493 3494 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 3495 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 3496 IE.getOperand(2)), 3497 "Invalid insertelement operands!", &IE); 3498 visitInstruction(IE); 3499 } 3500 3501 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 3502 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 3503 SV.getShuffleMask()), 3504 "Invalid shufflevector operands!", &SV); 3505 visitInstruction(SV); 3506 } 3507 3508 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 3509 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 3510 3511 Assert(isa<PointerType>(TargetTy), 3512 "GEP base pointer is not a vector or a vector of pointers", &GEP); 3513 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 3514 3515 SmallVector<Value *, 16> Idxs(GEP.indices()); 3516 Assert(all_of( 3517 Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }), 3518 "GEP indexes must be integers", &GEP); 3519 Type *ElTy = 3520 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 3521 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 3522 3523 Assert(GEP.getType()->isPtrOrPtrVectorTy() && 3524 GEP.getResultElementType() == ElTy, 3525 "GEP is not of right type for indices!", &GEP, ElTy); 3526 3527 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) { 3528 // Additional checks for vector GEPs. 3529 ElementCount GEPWidth = GEPVTy->getElementCount(); 3530 if (GEP.getPointerOperandType()->isVectorTy()) 3531 Assert( 3532 GEPWidth == 3533 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(), 3534 "Vector GEP result width doesn't match operand's", &GEP); 3535 for (Value *Idx : Idxs) { 3536 Type *IndexTy = Idx->getType(); 3537 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) { 3538 ElementCount IndexWidth = IndexVTy->getElementCount(); 3539 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 3540 } 3541 Assert(IndexTy->isIntOrIntVectorTy(), 3542 "All GEP indices should be of integer type"); 3543 } 3544 } 3545 3546 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) { 3547 Assert(GEP.getAddressSpace() == PTy->getAddressSpace(), 3548 "GEP address space doesn't match type", &GEP); 3549 } 3550 3551 visitInstruction(GEP); 3552 } 3553 3554 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 3555 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 3556 } 3557 3558 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) { 3559 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) && 3560 "precondition violation"); 3561 3562 unsigned NumOperands = Range->getNumOperands(); 3563 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 3564 unsigned NumRanges = NumOperands / 2; 3565 Assert(NumRanges >= 1, "It should have at least one range!", Range); 3566 3567 ConstantRange LastRange(1, true); // Dummy initial value 3568 for (unsigned i = 0; i < NumRanges; ++i) { 3569 ConstantInt *Low = 3570 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 3571 Assert(Low, "The lower limit must be an integer!", Low); 3572 ConstantInt *High = 3573 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 3574 Assert(High, "The upper limit must be an integer!", High); 3575 Assert(High->getType() == Low->getType() && High->getType() == Ty, 3576 "Range types must match instruction type!", &I); 3577 3578 APInt HighV = High->getValue(); 3579 APInt LowV = Low->getValue(); 3580 ConstantRange CurRange(LowV, HighV); 3581 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 3582 "Range must not be empty!", Range); 3583 if (i != 0) { 3584 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 3585 "Intervals are overlapping", Range); 3586 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 3587 Range); 3588 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 3589 Range); 3590 } 3591 LastRange = ConstantRange(LowV, HighV); 3592 } 3593 if (NumRanges > 2) { 3594 APInt FirstLow = 3595 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 3596 APInt FirstHigh = 3597 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 3598 ConstantRange FirstRange(FirstLow, FirstHigh); 3599 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 3600 "Intervals are overlapping", Range); 3601 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 3602 Range); 3603 } 3604 } 3605 3606 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) { 3607 unsigned Size = DL.getTypeSizeInBits(Ty); 3608 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 3609 Assert(!(Size & (Size - 1)), 3610 "atomic memory access' operand must have a power-of-two size", Ty, I); 3611 } 3612 3613 void Verifier::visitLoadInst(LoadInst &LI) { 3614 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 3615 Assert(PTy, "Load operand must be a pointer.", &LI); 3616 Type *ElTy = LI.getType(); 3617 Assert(LI.getAlignment() <= Value::MaximumAlignment, 3618 "huge alignment values are unsupported", &LI); 3619 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 3620 if (LI.isAtomic()) { 3621 Assert(LI.getOrdering() != AtomicOrdering::Release && 3622 LI.getOrdering() != AtomicOrdering::AcquireRelease, 3623 "Load cannot have Release ordering", &LI); 3624 Assert(LI.getAlignment() != 0, 3625 "Atomic load must specify explicit alignment", &LI); 3626 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3627 "atomic load operand must have integer, pointer, or floating point " 3628 "type!", 3629 ElTy, &LI); 3630 checkAtomicMemAccessSize(ElTy, &LI); 3631 } else { 3632 Assert(LI.getSyncScopeID() == SyncScope::System, 3633 "Non-atomic load cannot have SynchronizationScope specified", &LI); 3634 } 3635 3636 visitInstruction(LI); 3637 } 3638 3639 void Verifier::visitStoreInst(StoreInst &SI) { 3640 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 3641 Assert(PTy, "Store operand must be a pointer.", &SI); 3642 Type *ElTy = PTy->getElementType(); 3643 Assert(ElTy == SI.getOperand(0)->getType(), 3644 "Stored value type does not match pointer operand type!", &SI, ElTy); 3645 Assert(SI.getAlignment() <= Value::MaximumAlignment, 3646 "huge alignment values are unsupported", &SI); 3647 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 3648 if (SI.isAtomic()) { 3649 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 3650 SI.getOrdering() != AtomicOrdering::AcquireRelease, 3651 "Store cannot have Acquire ordering", &SI); 3652 Assert(SI.getAlignment() != 0, 3653 "Atomic store must specify explicit alignment", &SI); 3654 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3655 "atomic store operand must have integer, pointer, or floating point " 3656 "type!", 3657 ElTy, &SI); 3658 checkAtomicMemAccessSize(ElTy, &SI); 3659 } else { 3660 Assert(SI.getSyncScopeID() == SyncScope::System, 3661 "Non-atomic store cannot have SynchronizationScope specified", &SI); 3662 } 3663 visitInstruction(SI); 3664 } 3665 3666 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3667 void Verifier::verifySwiftErrorCall(CallBase &Call, 3668 const Value *SwiftErrorVal) { 3669 unsigned Idx = 0; 3670 for (auto I = Call.arg_begin(), E = Call.arg_end(); I != E; ++I, ++Idx) { 3671 if (*I == SwiftErrorVal) { 3672 Assert(Call.paramHasAttr(Idx, Attribute::SwiftError), 3673 "swifterror value when used in a callsite should be marked " 3674 "with swifterror attribute", 3675 SwiftErrorVal, Call); 3676 } 3677 } 3678 } 3679 3680 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3681 // Check that swifterror value is only used by loads, stores, or as 3682 // a swifterror argument. 3683 for (const User *U : SwiftErrorVal->users()) { 3684 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3685 isa<InvokeInst>(U), 3686 "swifterror value can only be loaded and stored from, or " 3687 "as a swifterror argument!", 3688 SwiftErrorVal, U); 3689 // If it is used by a store, check it is the second operand. 3690 if (auto StoreI = dyn_cast<StoreInst>(U)) 3691 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3692 "swifterror value should be the second operand when used " 3693 "by stores", SwiftErrorVal, U); 3694 if (auto *Call = dyn_cast<CallBase>(U)) 3695 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal); 3696 } 3697 } 3698 3699 void Verifier::visitAllocaInst(AllocaInst &AI) { 3700 SmallPtrSet<Type*, 4> Visited; 3701 PointerType *PTy = AI.getType(); 3702 // TODO: Relax this restriction? 3703 Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(), 3704 "Allocation instruction pointer not in the stack address space!", 3705 &AI); 3706 Assert(AI.getAllocatedType()->isSized(&Visited), 3707 "Cannot allocate unsized type", &AI); 3708 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3709 "Alloca array size must have integer type", &AI); 3710 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3711 "huge alignment values are unsupported", &AI); 3712 3713 if (AI.isSwiftError()) { 3714 verifySwiftErrorValue(&AI); 3715 } 3716 3717 visitInstruction(AI); 3718 } 3719 3720 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3721 3722 // FIXME: more conditions??? 3723 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic, 3724 "cmpxchg instructions must be atomic.", &CXI); 3725 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic, 3726 "cmpxchg instructions must be atomic.", &CXI); 3727 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered, 3728 "cmpxchg instructions cannot be unordered.", &CXI); 3729 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered, 3730 "cmpxchg instructions cannot be unordered.", &CXI); 3731 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()), 3732 "cmpxchg instructions failure argument shall be no stronger than the " 3733 "success argument", 3734 &CXI); 3735 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release && 3736 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease, 3737 "cmpxchg failure ordering cannot include release semantics", &CXI); 3738 3739 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 3740 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI); 3741 Type *ElTy = PTy->getElementType(); 3742 Assert(ElTy->isIntOrPtrTy(), 3743 "cmpxchg operand must have integer or pointer type", ElTy, &CXI); 3744 checkAtomicMemAccessSize(ElTy, &CXI); 3745 Assert(ElTy == CXI.getOperand(1)->getType(), 3746 "Expected value type does not match pointer operand type!", &CXI, 3747 ElTy); 3748 Assert(ElTy == CXI.getOperand(2)->getType(), 3749 "Stored value type does not match pointer operand type!", &CXI, ElTy); 3750 visitInstruction(CXI); 3751 } 3752 3753 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3754 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic, 3755 "atomicrmw instructions must be atomic.", &RMWI); 3756 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3757 "atomicrmw instructions cannot be unordered.", &RMWI); 3758 auto Op = RMWI.getOperation(); 3759 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 3760 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 3761 Type *ElTy = PTy->getElementType(); 3762 if (Op == AtomicRMWInst::Xchg) { 3763 Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " + 3764 AtomicRMWInst::getOperationName(Op) + 3765 " operand must have integer or floating point type!", 3766 &RMWI, ElTy); 3767 } else if (AtomicRMWInst::isFPOperation(Op)) { 3768 Assert(ElTy->isFloatingPointTy(), "atomicrmw " + 3769 AtomicRMWInst::getOperationName(Op) + 3770 " operand must have floating point type!", 3771 &RMWI, ElTy); 3772 } else { 3773 Assert(ElTy->isIntegerTy(), "atomicrmw " + 3774 AtomicRMWInst::getOperationName(Op) + 3775 " operand must have integer type!", 3776 &RMWI, ElTy); 3777 } 3778 checkAtomicMemAccessSize(ElTy, &RMWI); 3779 Assert(ElTy == RMWI.getOperand(1)->getType(), 3780 "Argument value type does not match pointer operand type!", &RMWI, 3781 ElTy); 3782 Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP, 3783 "Invalid binary operation!", &RMWI); 3784 visitInstruction(RMWI); 3785 } 3786 3787 void Verifier::visitFenceInst(FenceInst &FI) { 3788 const AtomicOrdering Ordering = FI.getOrdering(); 3789 Assert(Ordering == AtomicOrdering::Acquire || 3790 Ordering == AtomicOrdering::Release || 3791 Ordering == AtomicOrdering::AcquireRelease || 3792 Ordering == AtomicOrdering::SequentiallyConsistent, 3793 "fence instructions may only have acquire, release, acq_rel, or " 3794 "seq_cst ordering.", 3795 &FI); 3796 visitInstruction(FI); 3797 } 3798 3799 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3800 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3801 EVI.getIndices()) == EVI.getType(), 3802 "Invalid ExtractValueInst operands!", &EVI); 3803 3804 visitInstruction(EVI); 3805 } 3806 3807 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3808 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3809 IVI.getIndices()) == 3810 IVI.getOperand(1)->getType(), 3811 "Invalid InsertValueInst operands!", &IVI); 3812 3813 visitInstruction(IVI); 3814 } 3815 3816 static Value *getParentPad(Value *EHPad) { 3817 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3818 return FPI->getParentPad(); 3819 3820 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3821 } 3822 3823 void Verifier::visitEHPadPredecessors(Instruction &I) { 3824 assert(I.isEHPad()); 3825 3826 BasicBlock *BB = I.getParent(); 3827 Function *F = BB->getParent(); 3828 3829 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3830 3831 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3832 // The landingpad instruction defines its parent as a landing pad block. The 3833 // landing pad block may be branched to only by the unwind edge of an 3834 // invoke. 3835 for (BasicBlock *PredBB : predecessors(BB)) { 3836 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3837 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3838 "Block containing LandingPadInst must be jumped to " 3839 "only by the unwind edge of an invoke.", 3840 LPI); 3841 } 3842 return; 3843 } 3844 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3845 if (!pred_empty(BB)) 3846 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3847 "Block containg CatchPadInst must be jumped to " 3848 "only by its catchswitch.", 3849 CPI); 3850 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3851 "Catchswitch cannot unwind to one of its catchpads", 3852 CPI->getCatchSwitch(), CPI); 3853 return; 3854 } 3855 3856 // Verify that each pred has a legal terminator with a legal to/from EH 3857 // pad relationship. 3858 Instruction *ToPad = &I; 3859 Value *ToPadParent = getParentPad(ToPad); 3860 for (BasicBlock *PredBB : predecessors(BB)) { 3861 Instruction *TI = PredBB->getTerminator(); 3862 Value *FromPad; 3863 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3864 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3865 "EH pad must be jumped to via an unwind edge", ToPad, II); 3866 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3867 FromPad = Bundle->Inputs[0]; 3868 else 3869 FromPad = ConstantTokenNone::get(II->getContext()); 3870 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3871 FromPad = CRI->getOperand(0); 3872 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3873 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 3874 FromPad = CSI; 3875 } else { 3876 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 3877 } 3878 3879 // The edge may exit from zero or more nested pads. 3880 SmallSet<Value *, 8> Seen; 3881 for (;; FromPad = getParentPad(FromPad)) { 3882 Assert(FromPad != ToPad, 3883 "EH pad cannot handle exceptions raised within it", FromPad, TI); 3884 if (FromPad == ToPadParent) { 3885 // This is a legal unwind edge. 3886 break; 3887 } 3888 Assert(!isa<ConstantTokenNone>(FromPad), 3889 "A single unwind edge may only enter one EH pad", TI); 3890 Assert(Seen.insert(FromPad).second, 3891 "EH pad jumps through a cycle of pads", FromPad); 3892 } 3893 } 3894 } 3895 3896 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 3897 // The landingpad instruction is ill-formed if it doesn't have any clauses and 3898 // isn't a cleanup. 3899 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 3900 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 3901 3902 visitEHPadPredecessors(LPI); 3903 3904 if (!LandingPadResultTy) 3905 LandingPadResultTy = LPI.getType(); 3906 else 3907 Assert(LandingPadResultTy == LPI.getType(), 3908 "The landingpad instruction should have a consistent result type " 3909 "inside a function.", 3910 &LPI); 3911 3912 Function *F = LPI.getParent()->getParent(); 3913 Assert(F->hasPersonalityFn(), 3914 "LandingPadInst needs to be in a function with a personality.", &LPI); 3915 3916 // The landingpad instruction must be the first non-PHI instruction in the 3917 // block. 3918 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 3919 "LandingPadInst not the first non-PHI instruction in the block.", 3920 &LPI); 3921 3922 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 3923 Constant *Clause = LPI.getClause(i); 3924 if (LPI.isCatch(i)) { 3925 Assert(isa<PointerType>(Clause->getType()), 3926 "Catch operand does not have pointer type!", &LPI); 3927 } else { 3928 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 3929 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 3930 "Filter operand is not an array of constants!", &LPI); 3931 } 3932 } 3933 3934 visitInstruction(LPI); 3935 } 3936 3937 void Verifier::visitResumeInst(ResumeInst &RI) { 3938 Assert(RI.getFunction()->hasPersonalityFn(), 3939 "ResumeInst needs to be in a function with a personality.", &RI); 3940 3941 if (!LandingPadResultTy) 3942 LandingPadResultTy = RI.getValue()->getType(); 3943 else 3944 Assert(LandingPadResultTy == RI.getValue()->getType(), 3945 "The resume instruction should have a consistent result type " 3946 "inside a function.", 3947 &RI); 3948 3949 visitTerminator(RI); 3950 } 3951 3952 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 3953 BasicBlock *BB = CPI.getParent(); 3954 3955 Function *F = BB->getParent(); 3956 Assert(F->hasPersonalityFn(), 3957 "CatchPadInst needs to be in a function with a personality.", &CPI); 3958 3959 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 3960 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 3961 CPI.getParentPad()); 3962 3963 // The catchpad instruction must be the first non-PHI instruction in the 3964 // block. 3965 Assert(BB->getFirstNonPHI() == &CPI, 3966 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 3967 3968 visitEHPadPredecessors(CPI); 3969 visitFuncletPadInst(CPI); 3970 } 3971 3972 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 3973 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 3974 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 3975 CatchReturn.getOperand(0)); 3976 3977 visitTerminator(CatchReturn); 3978 } 3979 3980 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 3981 BasicBlock *BB = CPI.getParent(); 3982 3983 Function *F = BB->getParent(); 3984 Assert(F->hasPersonalityFn(), 3985 "CleanupPadInst needs to be in a function with a personality.", &CPI); 3986 3987 // The cleanuppad instruction must be the first non-PHI instruction in the 3988 // block. 3989 Assert(BB->getFirstNonPHI() == &CPI, 3990 "CleanupPadInst not the first non-PHI instruction in the block.", 3991 &CPI); 3992 3993 auto *ParentPad = CPI.getParentPad(); 3994 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3995 "CleanupPadInst has an invalid parent.", &CPI); 3996 3997 visitEHPadPredecessors(CPI); 3998 visitFuncletPadInst(CPI); 3999 } 4000 4001 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 4002 User *FirstUser = nullptr; 4003 Value *FirstUnwindPad = nullptr; 4004 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 4005 SmallSet<FuncletPadInst *, 8> Seen; 4006 4007 while (!Worklist.empty()) { 4008 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 4009 Assert(Seen.insert(CurrentPad).second, 4010 "FuncletPadInst must not be nested within itself", CurrentPad); 4011 Value *UnresolvedAncestorPad = nullptr; 4012 for (User *U : CurrentPad->users()) { 4013 BasicBlock *UnwindDest; 4014 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 4015 UnwindDest = CRI->getUnwindDest(); 4016 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 4017 // We allow catchswitch unwind to caller to nest 4018 // within an outer pad that unwinds somewhere else, 4019 // because catchswitch doesn't have a nounwind variant. 4020 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 4021 if (CSI->unwindsToCaller()) 4022 continue; 4023 UnwindDest = CSI->getUnwindDest(); 4024 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 4025 UnwindDest = II->getUnwindDest(); 4026 } else if (isa<CallInst>(U)) { 4027 // Calls which don't unwind may be found inside funclet 4028 // pads that unwind somewhere else. We don't *require* 4029 // such calls to be annotated nounwind. 4030 continue; 4031 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 4032 // The unwind dest for a cleanup can only be found by 4033 // recursive search. Add it to the worklist, and we'll 4034 // search for its first use that determines where it unwinds. 4035 Worklist.push_back(CPI); 4036 continue; 4037 } else { 4038 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 4039 continue; 4040 } 4041 4042 Value *UnwindPad; 4043 bool ExitsFPI; 4044 if (UnwindDest) { 4045 UnwindPad = UnwindDest->getFirstNonPHI(); 4046 if (!cast<Instruction>(UnwindPad)->isEHPad()) 4047 continue; 4048 Value *UnwindParent = getParentPad(UnwindPad); 4049 // Ignore unwind edges that don't exit CurrentPad. 4050 if (UnwindParent == CurrentPad) 4051 continue; 4052 // Determine whether the original funclet pad is exited, 4053 // and if we are scanning nested pads determine how many 4054 // of them are exited so we can stop searching their 4055 // children. 4056 Value *ExitedPad = CurrentPad; 4057 ExitsFPI = false; 4058 do { 4059 if (ExitedPad == &FPI) { 4060 ExitsFPI = true; 4061 // Now we can resolve any ancestors of CurrentPad up to 4062 // FPI, but not including FPI since we need to make sure 4063 // to check all direct users of FPI for consistency. 4064 UnresolvedAncestorPad = &FPI; 4065 break; 4066 } 4067 Value *ExitedParent = getParentPad(ExitedPad); 4068 if (ExitedParent == UnwindParent) { 4069 // ExitedPad is the ancestor-most pad which this unwind 4070 // edge exits, so we can resolve up to it, meaning that 4071 // ExitedParent is the first ancestor still unresolved. 4072 UnresolvedAncestorPad = ExitedParent; 4073 break; 4074 } 4075 ExitedPad = ExitedParent; 4076 } while (!isa<ConstantTokenNone>(ExitedPad)); 4077 } else { 4078 // Unwinding to caller exits all pads. 4079 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 4080 ExitsFPI = true; 4081 UnresolvedAncestorPad = &FPI; 4082 } 4083 4084 if (ExitsFPI) { 4085 // This unwind edge exits FPI. Make sure it agrees with other 4086 // such edges. 4087 if (FirstUser) { 4088 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 4089 "pad must have the same unwind " 4090 "dest", 4091 &FPI, U, FirstUser); 4092 } else { 4093 FirstUser = U; 4094 FirstUnwindPad = UnwindPad; 4095 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 4096 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 4097 getParentPad(UnwindPad) == getParentPad(&FPI)) 4098 SiblingFuncletInfo[&FPI] = cast<Instruction>(U); 4099 } 4100 } 4101 // Make sure we visit all uses of FPI, but for nested pads stop as 4102 // soon as we know where they unwind to. 4103 if (CurrentPad != &FPI) 4104 break; 4105 } 4106 if (UnresolvedAncestorPad) { 4107 if (CurrentPad == UnresolvedAncestorPad) { 4108 // When CurrentPad is FPI itself, we don't mark it as resolved even if 4109 // we've found an unwind edge that exits it, because we need to verify 4110 // all direct uses of FPI. 4111 assert(CurrentPad == &FPI); 4112 continue; 4113 } 4114 // Pop off the worklist any nested pads that we've found an unwind 4115 // destination for. The pads on the worklist are the uncles, 4116 // great-uncles, etc. of CurrentPad. We've found an unwind destination 4117 // for all ancestors of CurrentPad up to but not including 4118 // UnresolvedAncestorPad. 4119 Value *ResolvedPad = CurrentPad; 4120 while (!Worklist.empty()) { 4121 Value *UnclePad = Worklist.back(); 4122 Value *AncestorPad = getParentPad(UnclePad); 4123 // Walk ResolvedPad up the ancestor list until we either find the 4124 // uncle's parent or the last resolved ancestor. 4125 while (ResolvedPad != AncestorPad) { 4126 Value *ResolvedParent = getParentPad(ResolvedPad); 4127 if (ResolvedParent == UnresolvedAncestorPad) { 4128 break; 4129 } 4130 ResolvedPad = ResolvedParent; 4131 } 4132 // If the resolved ancestor search didn't find the uncle's parent, 4133 // then the uncle is not yet resolved. 4134 if (ResolvedPad != AncestorPad) 4135 break; 4136 // This uncle is resolved, so pop it from the worklist. 4137 Worklist.pop_back(); 4138 } 4139 } 4140 } 4141 4142 if (FirstUnwindPad) { 4143 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 4144 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 4145 Value *SwitchUnwindPad; 4146 if (SwitchUnwindDest) 4147 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 4148 else 4149 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 4150 Assert(SwitchUnwindPad == FirstUnwindPad, 4151 "Unwind edges out of a catch must have the same unwind dest as " 4152 "the parent catchswitch", 4153 &FPI, FirstUser, CatchSwitch); 4154 } 4155 } 4156 4157 visitInstruction(FPI); 4158 } 4159 4160 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 4161 BasicBlock *BB = CatchSwitch.getParent(); 4162 4163 Function *F = BB->getParent(); 4164 Assert(F->hasPersonalityFn(), 4165 "CatchSwitchInst needs to be in a function with a personality.", 4166 &CatchSwitch); 4167 4168 // The catchswitch instruction must be the first non-PHI instruction in the 4169 // block. 4170 Assert(BB->getFirstNonPHI() == &CatchSwitch, 4171 "CatchSwitchInst not the first non-PHI instruction in the block.", 4172 &CatchSwitch); 4173 4174 auto *ParentPad = CatchSwitch.getParentPad(); 4175 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 4176 "CatchSwitchInst has an invalid parent.", ParentPad); 4177 4178 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 4179 Instruction *I = UnwindDest->getFirstNonPHI(); 4180 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4181 "CatchSwitchInst must unwind to an EH block which is not a " 4182 "landingpad.", 4183 &CatchSwitch); 4184 4185 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 4186 if (getParentPad(I) == ParentPad) 4187 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 4188 } 4189 4190 Assert(CatchSwitch.getNumHandlers() != 0, 4191 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 4192 4193 for (BasicBlock *Handler : CatchSwitch.handlers()) { 4194 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 4195 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 4196 } 4197 4198 visitEHPadPredecessors(CatchSwitch); 4199 visitTerminator(CatchSwitch); 4200 } 4201 4202 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 4203 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 4204 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 4205 CRI.getOperand(0)); 4206 4207 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 4208 Instruction *I = UnwindDest->getFirstNonPHI(); 4209 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4210 "CleanupReturnInst must unwind to an EH block which is not a " 4211 "landingpad.", 4212 &CRI); 4213 } 4214 4215 visitTerminator(CRI); 4216 } 4217 4218 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 4219 Instruction *Op = cast<Instruction>(I.getOperand(i)); 4220 // If the we have an invalid invoke, don't try to compute the dominance. 4221 // We already reject it in the invoke specific checks and the dominance 4222 // computation doesn't handle multiple edges. 4223 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 4224 if (II->getNormalDest() == II->getUnwindDest()) 4225 return; 4226 } 4227 4228 // Quick check whether the def has already been encountered in the same block. 4229 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI 4230 // uses are defined to happen on the incoming edge, not at the instruction. 4231 // 4232 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 4233 // wrapping an SSA value, assert that we've already encountered it. See 4234 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 4235 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 4236 return; 4237 4238 const Use &U = I.getOperandUse(i); 4239 Assert(DT.dominates(Op, U), 4240 "Instruction does not dominate all uses!", Op, &I); 4241 } 4242 4243 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 4244 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 4245 "apply only to pointer types", &I); 4246 Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)), 4247 "dereferenceable, dereferenceable_or_null apply only to load" 4248 " and inttoptr instructions, use attributes for calls or invokes", &I); 4249 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 4250 "take one operand!", &I); 4251 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 4252 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 4253 "dereferenceable_or_null metadata value must be an i64!", &I); 4254 } 4255 4256 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) { 4257 Assert(MD->getNumOperands() >= 2, 4258 "!prof annotations should have no less than 2 operands", MD); 4259 4260 // Check first operand. 4261 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD); 4262 Assert(isa<MDString>(MD->getOperand(0)), 4263 "expected string with name of the !prof annotation", MD); 4264 MDString *MDS = cast<MDString>(MD->getOperand(0)); 4265 StringRef ProfName = MDS->getString(); 4266 4267 // Check consistency of !prof branch_weights metadata. 4268 if (ProfName.equals("branch_weights")) { 4269 if (isa<InvokeInst>(&I)) { 4270 Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3, 4271 "Wrong number of InvokeInst branch_weights operands", MD); 4272 } else { 4273 unsigned ExpectedNumOperands = 0; 4274 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 4275 ExpectedNumOperands = BI->getNumSuccessors(); 4276 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 4277 ExpectedNumOperands = SI->getNumSuccessors(); 4278 else if (isa<CallInst>(&I)) 4279 ExpectedNumOperands = 1; 4280 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 4281 ExpectedNumOperands = IBI->getNumDestinations(); 4282 else if (isa<SelectInst>(&I)) 4283 ExpectedNumOperands = 2; 4284 else 4285 CheckFailed("!prof branch_weights are not allowed for this instruction", 4286 MD); 4287 4288 Assert(MD->getNumOperands() == 1 + ExpectedNumOperands, 4289 "Wrong number of operands", MD); 4290 } 4291 for (unsigned i = 1; i < MD->getNumOperands(); ++i) { 4292 auto &MDO = MD->getOperand(i); 4293 Assert(MDO, "second operand should not be null", MD); 4294 Assert(mdconst::dyn_extract<ConstantInt>(MDO), 4295 "!prof brunch_weights operand is not a const int"); 4296 } 4297 } 4298 } 4299 4300 void Verifier::visitAnnotationMetadata(MDNode *Annotation) { 4301 Assert(isa<MDTuple>(Annotation), "annotation must be a tuple"); 4302 Assert(Annotation->getNumOperands() >= 1, 4303 "annotation must have at least one operand"); 4304 for (const MDOperand &Op : Annotation->operands()) 4305 Assert(isa<MDString>(Op.get()), "operands must be strings"); 4306 } 4307 4308 /// verifyInstruction - Verify that an instruction is well formed. 4309 /// 4310 void Verifier::visitInstruction(Instruction &I) { 4311 BasicBlock *BB = I.getParent(); 4312 Assert(BB, "Instruction not embedded in basic block!", &I); 4313 4314 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 4315 for (User *U : I.users()) { 4316 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 4317 "Only PHI nodes may reference their own value!", &I); 4318 } 4319 } 4320 4321 // Check that void typed values don't have names 4322 Assert(!I.getType()->isVoidTy() || !I.hasName(), 4323 "Instruction has a name, but provides a void value!", &I); 4324 4325 // Check that the return value of the instruction is either void or a legal 4326 // value type. 4327 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 4328 "Instruction returns a non-scalar type!", &I); 4329 4330 // Check that the instruction doesn't produce metadata. Calls are already 4331 // checked against the callee type. 4332 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 4333 "Invalid use of metadata!", &I); 4334 4335 // Check that all uses of the instruction, if they are instructions 4336 // themselves, actually have parent basic blocks. If the use is not an 4337 // instruction, it is an error! 4338 for (Use &U : I.uses()) { 4339 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 4340 Assert(Used->getParent() != nullptr, 4341 "Instruction referencing" 4342 " instruction not embedded in a basic block!", 4343 &I, Used); 4344 else { 4345 CheckFailed("Use of instruction is not an instruction!", U); 4346 return; 4347 } 4348 } 4349 4350 // Get a pointer to the call base of the instruction if it is some form of 4351 // call. 4352 const CallBase *CBI = dyn_cast<CallBase>(&I); 4353 4354 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 4355 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 4356 4357 // Check to make sure that only first-class-values are operands to 4358 // instructions. 4359 if (!I.getOperand(i)->getType()->isFirstClassType()) { 4360 Assert(false, "Instruction operands must be first-class values!", &I); 4361 } 4362 4363 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 4364 // Check to make sure that the "address of" an intrinsic function is never 4365 // taken. 4366 Assert(!F->isIntrinsic() || 4367 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)), 4368 "Cannot take the address of an intrinsic!", &I); 4369 Assert( 4370 !F->isIntrinsic() || isa<CallInst>(I) || 4371 F->getIntrinsicID() == Intrinsic::donothing || 4372 F->getIntrinsicID() == Intrinsic::coro_resume || 4373 F->getIntrinsicID() == Intrinsic::coro_destroy || 4374 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 4375 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 4376 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint || 4377 F->getIntrinsicID() == Intrinsic::wasm_rethrow, 4378 "Cannot invoke an intrinsic other than donothing, patchpoint, " 4379 "statepoint, coro_resume or coro_destroy", 4380 &I); 4381 Assert(F->getParent() == &M, "Referencing function in another module!", 4382 &I, &M, F, F->getParent()); 4383 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 4384 Assert(OpBB->getParent() == BB->getParent(), 4385 "Referring to a basic block in another function!", &I); 4386 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 4387 Assert(OpArg->getParent() == BB->getParent(), 4388 "Referring to an argument in another function!", &I); 4389 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 4390 Assert(GV->getParent() == &M, "Referencing global in another module!", &I, 4391 &M, GV, GV->getParent()); 4392 } else if (isa<Instruction>(I.getOperand(i))) { 4393 verifyDominatesUse(I, i); 4394 } else if (isa<InlineAsm>(I.getOperand(i))) { 4395 Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i), 4396 "Cannot take the address of an inline asm!", &I); 4397 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 4398 if (CE->getType()->isPtrOrPtrVectorTy() || 4399 !DL.getNonIntegralAddressSpaces().empty()) { 4400 // If we have a ConstantExpr pointer, we need to see if it came from an 4401 // illegal bitcast. If the datalayout string specifies non-integral 4402 // address spaces then we also need to check for illegal ptrtoint and 4403 // inttoptr expressions. 4404 visitConstantExprsRecursively(CE); 4405 } 4406 } 4407 } 4408 4409 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 4410 Assert(I.getType()->isFPOrFPVectorTy(), 4411 "fpmath requires a floating point result!", &I); 4412 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 4413 if (ConstantFP *CFP0 = 4414 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 4415 const APFloat &Accuracy = CFP0->getValueAPF(); 4416 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(), 4417 "fpmath accuracy must have float type", &I); 4418 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 4419 "fpmath accuracy not a positive number!", &I); 4420 } else { 4421 Assert(false, "invalid fpmath accuracy!", &I); 4422 } 4423 } 4424 4425 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 4426 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 4427 "Ranges are only for loads, calls and invokes!", &I); 4428 visitRangeMetadata(I, Range, I.getType()); 4429 } 4430 4431 if (I.getMetadata(LLVMContext::MD_nonnull)) { 4432 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 4433 &I); 4434 Assert(isa<LoadInst>(I), 4435 "nonnull applies only to load instructions, use attributes" 4436 " for calls or invokes", 4437 &I); 4438 } 4439 4440 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 4441 visitDereferenceableMetadata(I, MD); 4442 4443 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 4444 visitDereferenceableMetadata(I, MD); 4445 4446 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) 4447 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA); 4448 4449 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 4450 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 4451 &I); 4452 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 4453 "use attributes for calls or invokes", &I); 4454 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 4455 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 4456 Assert(CI && CI->getType()->isIntegerTy(64), 4457 "align metadata value must be an i64!", &I); 4458 uint64_t Align = CI->getZExtValue(); 4459 Assert(isPowerOf2_64(Align), 4460 "align metadata value must be a power of 2!", &I); 4461 Assert(Align <= Value::MaximumAlignment, 4462 "alignment is larger that implementation defined limit", &I); 4463 } 4464 4465 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof)) 4466 visitProfMetadata(I, MD); 4467 4468 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation)) 4469 visitAnnotationMetadata(Annotation); 4470 4471 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 4472 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 4473 visitMDNode(*N, AreDebugLocsAllowed::Yes); 4474 } 4475 4476 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) { 4477 verifyFragmentExpression(*DII); 4478 verifyNotEntryValue(*DII); 4479 } 4480 4481 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 4482 I.getAllMetadata(MDs); 4483 for (auto Attachment : MDs) { 4484 unsigned Kind = Attachment.first; 4485 auto AllowLocs = 4486 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop) 4487 ? AreDebugLocsAllowed::Yes 4488 : AreDebugLocsAllowed::No; 4489 visitMDNode(*Attachment.second, AllowLocs); 4490 } 4491 4492 InstsInThisBlock.insert(&I); 4493 } 4494 4495 /// Allow intrinsics to be verified in different ways. 4496 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) { 4497 Function *IF = Call.getCalledFunction(); 4498 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 4499 IF); 4500 4501 // Verify that the intrinsic prototype lines up with what the .td files 4502 // describe. 4503 FunctionType *IFTy = IF->getFunctionType(); 4504 bool IsVarArg = IFTy->isVarArg(); 4505 4506 SmallVector<Intrinsic::IITDescriptor, 8> Table; 4507 getIntrinsicInfoTableEntries(ID, Table); 4508 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 4509 4510 // Walk the descriptors to extract overloaded types. 4511 SmallVector<Type *, 4> ArgTys; 4512 Intrinsic::MatchIntrinsicTypesResult Res = 4513 Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys); 4514 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet, 4515 "Intrinsic has incorrect return type!", IF); 4516 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg, 4517 "Intrinsic has incorrect argument type!", IF); 4518 4519 // Verify if the intrinsic call matches the vararg property. 4520 if (IsVarArg) 4521 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4522 "Intrinsic was not defined with variable arguments!", IF); 4523 else 4524 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4525 "Callsite was not defined with variable arguments!", IF); 4526 4527 // All descriptors should be absorbed by now. 4528 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 4529 4530 // Now that we have the intrinsic ID and the actual argument types (and we 4531 // know they are legal for the intrinsic!) get the intrinsic name through the 4532 // usual means. This allows us to verify the mangling of argument types into 4533 // the name. 4534 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 4535 Assert(ExpectedName == IF->getName(), 4536 "Intrinsic name not mangled correctly for type arguments! " 4537 "Should be: " + 4538 ExpectedName, 4539 IF); 4540 4541 // If the intrinsic takes MDNode arguments, verify that they are either global 4542 // or are local to *this* function. 4543 for (Value *V : Call.args()) 4544 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 4545 visitMetadataAsValue(*MD, Call.getCaller()); 4546 4547 switch (ID) { 4548 default: 4549 break; 4550 case Intrinsic::assume: { 4551 for (auto &Elem : Call.bundle_op_infos()) { 4552 Assert(Elem.Tag->getKey() == "ignore" || 4553 Attribute::isExistingAttribute(Elem.Tag->getKey()), 4554 "tags must be valid attribute names"); 4555 Attribute::AttrKind Kind = 4556 Attribute::getAttrKindFromName(Elem.Tag->getKey()); 4557 unsigned ArgCount = Elem.End - Elem.Begin; 4558 if (Kind == Attribute::Alignment) { 4559 Assert(ArgCount <= 3 && ArgCount >= 2, 4560 "alignment assumptions should have 2 or 3 arguments"); 4561 Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(), 4562 "first argument should be a pointer"); 4563 Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(), 4564 "second argument should be an integer"); 4565 if (ArgCount == 3) 4566 Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(), 4567 "third argument should be an integer if present"); 4568 return; 4569 } 4570 Assert(ArgCount <= 2, "to many arguments"); 4571 if (Kind == Attribute::None) 4572 break; 4573 if (Attribute::doesAttrKindHaveArgument(Kind)) { 4574 Assert(ArgCount == 2, "this attribute should have 2 arguments"); 4575 Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)), 4576 "the second argument should be a constant integral value"); 4577 } else if (isFuncOnlyAttr(Kind)) { 4578 Assert((ArgCount) == 0, "this attribute has no argument"); 4579 } else if (!isFuncOrArgAttr(Kind)) { 4580 Assert((ArgCount) == 1, "this attribute should have one argument"); 4581 } 4582 } 4583 break; 4584 } 4585 case Intrinsic::coro_id: { 4586 auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts(); 4587 if (isa<ConstantPointerNull>(InfoArg)) 4588 break; 4589 auto *GV = dyn_cast<GlobalVariable>(InfoArg); 4590 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(), 4591 "info argument of llvm.coro.begin must refer to an initialized " 4592 "constant"); 4593 Constant *Init = GV->getInitializer(); 4594 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init), 4595 "info argument of llvm.coro.begin must refer to either a struct or " 4596 "an array"); 4597 break; 4598 } 4599 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \ 4600 case Intrinsic::INTRINSIC: 4601 #include "llvm/IR/ConstrainedOps.def" 4602 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call)); 4603 break; 4604 case Intrinsic::dbg_declare: // llvm.dbg.declare 4605 Assert(isa<MetadataAsValue>(Call.getArgOperand(0)), 4606 "invalid llvm.dbg.declare intrinsic call 1", Call); 4607 visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call)); 4608 break; 4609 case Intrinsic::dbg_addr: // llvm.dbg.addr 4610 visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call)); 4611 break; 4612 case Intrinsic::dbg_value: // llvm.dbg.value 4613 visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call)); 4614 break; 4615 case Intrinsic::dbg_label: // llvm.dbg.label 4616 visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call)); 4617 break; 4618 case Intrinsic::memcpy: 4619 case Intrinsic::memcpy_inline: 4620 case Intrinsic::memmove: 4621 case Intrinsic::memset: { 4622 const auto *MI = cast<MemIntrinsic>(&Call); 4623 auto IsValidAlignment = [&](unsigned Alignment) -> bool { 4624 return Alignment == 0 || isPowerOf2_32(Alignment); 4625 }; 4626 Assert(IsValidAlignment(MI->getDestAlignment()), 4627 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2", 4628 Call); 4629 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) { 4630 Assert(IsValidAlignment(MTI->getSourceAlignment()), 4631 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2", 4632 Call); 4633 } 4634 4635 break; 4636 } 4637 case Intrinsic::memcpy_element_unordered_atomic: 4638 case Intrinsic::memmove_element_unordered_atomic: 4639 case Intrinsic::memset_element_unordered_atomic: { 4640 const auto *AMI = cast<AtomicMemIntrinsic>(&Call); 4641 4642 ConstantInt *ElementSizeCI = 4643 cast<ConstantInt>(AMI->getRawElementSizeInBytes()); 4644 const APInt &ElementSizeVal = ElementSizeCI->getValue(); 4645 Assert(ElementSizeVal.isPowerOf2(), 4646 "element size of the element-wise atomic memory intrinsic " 4647 "must be a power of 2", 4648 Call); 4649 4650 auto IsValidAlignment = [&](uint64_t Alignment) { 4651 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment); 4652 }; 4653 uint64_t DstAlignment = AMI->getDestAlignment(); 4654 Assert(IsValidAlignment(DstAlignment), 4655 "incorrect alignment of the destination argument", Call); 4656 if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) { 4657 uint64_t SrcAlignment = AMT->getSourceAlignment(); 4658 Assert(IsValidAlignment(SrcAlignment), 4659 "incorrect alignment of the source argument", Call); 4660 } 4661 break; 4662 } 4663 case Intrinsic::call_preallocated_setup: { 4664 auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 4665 Assert(NumArgs != nullptr, 4666 "llvm.call.preallocated.setup argument must be a constant"); 4667 bool FoundCall = false; 4668 for (User *U : Call.users()) { 4669 auto *UseCall = dyn_cast<CallBase>(U); 4670 Assert(UseCall != nullptr, 4671 "Uses of llvm.call.preallocated.setup must be calls"); 4672 const Function *Fn = UseCall->getCalledFunction(); 4673 if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) { 4674 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1)); 4675 Assert(AllocArgIndex != nullptr, 4676 "llvm.call.preallocated.alloc arg index must be a constant"); 4677 auto AllocArgIndexInt = AllocArgIndex->getValue(); 4678 Assert(AllocArgIndexInt.sge(0) && 4679 AllocArgIndexInt.slt(NumArgs->getValue()), 4680 "llvm.call.preallocated.alloc arg index must be between 0 and " 4681 "corresponding " 4682 "llvm.call.preallocated.setup's argument count"); 4683 } else if (Fn && Fn->getIntrinsicID() == 4684 Intrinsic::call_preallocated_teardown) { 4685 // nothing to do 4686 } else { 4687 Assert(!FoundCall, "Can have at most one call corresponding to a " 4688 "llvm.call.preallocated.setup"); 4689 FoundCall = true; 4690 size_t NumPreallocatedArgs = 0; 4691 for (unsigned i = 0; i < UseCall->getNumArgOperands(); i++) { 4692 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) { 4693 ++NumPreallocatedArgs; 4694 } 4695 } 4696 Assert(NumPreallocatedArgs != 0, 4697 "cannot use preallocated intrinsics on a call without " 4698 "preallocated arguments"); 4699 Assert(NumArgs->equalsInt(NumPreallocatedArgs), 4700 "llvm.call.preallocated.setup arg size must be equal to number " 4701 "of preallocated arguments " 4702 "at call site", 4703 Call, *UseCall); 4704 // getOperandBundle() cannot be called if more than one of the operand 4705 // bundle exists. There is already a check elsewhere for this, so skip 4706 // here if we see more than one. 4707 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) > 4708 1) { 4709 return; 4710 } 4711 auto PreallocatedBundle = 4712 UseCall->getOperandBundle(LLVMContext::OB_preallocated); 4713 Assert(PreallocatedBundle, 4714 "Use of llvm.call.preallocated.setup outside intrinsics " 4715 "must be in \"preallocated\" operand bundle"); 4716 Assert(PreallocatedBundle->Inputs.front().get() == &Call, 4717 "preallocated bundle must have token from corresponding " 4718 "llvm.call.preallocated.setup"); 4719 } 4720 } 4721 break; 4722 } 4723 case Intrinsic::call_preallocated_arg: { 4724 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4725 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4726 Intrinsic::call_preallocated_setup, 4727 "llvm.call.preallocated.arg token argument must be a " 4728 "llvm.call.preallocated.setup"); 4729 Assert(Call.hasFnAttr(Attribute::Preallocated), 4730 "llvm.call.preallocated.arg must be called with a \"preallocated\" " 4731 "call site attribute"); 4732 break; 4733 } 4734 case Intrinsic::call_preallocated_teardown: { 4735 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4736 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4737 Intrinsic::call_preallocated_setup, 4738 "llvm.call.preallocated.teardown token argument must be a " 4739 "llvm.call.preallocated.setup"); 4740 break; 4741 } 4742 case Intrinsic::gcroot: 4743 case Intrinsic::gcwrite: 4744 case Intrinsic::gcread: 4745 if (ID == Intrinsic::gcroot) { 4746 AllocaInst *AI = 4747 dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts()); 4748 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call); 4749 Assert(isa<Constant>(Call.getArgOperand(1)), 4750 "llvm.gcroot parameter #2 must be a constant.", Call); 4751 if (!AI->getAllocatedType()->isPointerTy()) { 4752 Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)), 4753 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4754 "or argument #2 must be a non-null constant.", 4755 Call); 4756 } 4757 } 4758 4759 Assert(Call.getParent()->getParent()->hasGC(), 4760 "Enclosing function does not use GC.", Call); 4761 break; 4762 case Intrinsic::init_trampoline: 4763 Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()), 4764 "llvm.init_trampoline parameter #2 must resolve to a function.", 4765 Call); 4766 break; 4767 case Intrinsic::prefetch: 4768 Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 && 4769 cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4, 4770 "invalid arguments to llvm.prefetch", Call); 4771 break; 4772 case Intrinsic::stackprotector: 4773 Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()), 4774 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call); 4775 break; 4776 case Intrinsic::localescape: { 4777 BasicBlock *BB = Call.getParent(); 4778 Assert(BB == &BB->getParent()->front(), 4779 "llvm.localescape used outside of entry block", Call); 4780 Assert(!SawFrameEscape, 4781 "multiple calls to llvm.localescape in one function", Call); 4782 for (Value *Arg : Call.args()) { 4783 if (isa<ConstantPointerNull>(Arg)) 4784 continue; // Null values are allowed as placeholders. 4785 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4786 Assert(AI && AI->isStaticAlloca(), 4787 "llvm.localescape only accepts static allocas", Call); 4788 } 4789 FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands(); 4790 SawFrameEscape = true; 4791 break; 4792 } 4793 case Intrinsic::localrecover: { 4794 Value *FnArg = Call.getArgOperand(0)->stripPointerCasts(); 4795 Function *Fn = dyn_cast<Function>(FnArg); 4796 Assert(Fn && !Fn->isDeclaration(), 4797 "llvm.localrecover first " 4798 "argument must be function defined in this module", 4799 Call); 4800 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2)); 4801 auto &Entry = FrameEscapeInfo[Fn]; 4802 Entry.second = unsigned( 4803 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4804 break; 4805 } 4806 4807 case Intrinsic::experimental_gc_statepoint: 4808 if (auto *CI = dyn_cast<CallInst>(&Call)) 4809 Assert(!CI->isInlineAsm(), 4810 "gc.statepoint support for inline assembly unimplemented", CI); 4811 Assert(Call.getParent()->getParent()->hasGC(), 4812 "Enclosing function does not use GC.", Call); 4813 4814 verifyStatepoint(Call); 4815 break; 4816 case Intrinsic::experimental_gc_result: { 4817 Assert(Call.getParent()->getParent()->hasGC(), 4818 "Enclosing function does not use GC.", Call); 4819 // Are we tied to a statepoint properly? 4820 const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0)); 4821 const Function *StatepointFn = 4822 StatepointCall ? StatepointCall->getCalledFunction() : nullptr; 4823 Assert(StatepointFn && StatepointFn->isDeclaration() && 4824 StatepointFn->getIntrinsicID() == 4825 Intrinsic::experimental_gc_statepoint, 4826 "gc.result operand #1 must be from a statepoint", Call, 4827 Call.getArgOperand(0)); 4828 4829 // Assert that result type matches wrapped callee. 4830 const Value *Target = StatepointCall->getArgOperand(2); 4831 auto *PT = cast<PointerType>(Target->getType()); 4832 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4833 Assert(Call.getType() == TargetFuncType->getReturnType(), 4834 "gc.result result type does not match wrapped callee", Call); 4835 break; 4836 } 4837 case Intrinsic::experimental_gc_relocate: { 4838 Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call); 4839 4840 Assert(isa<PointerType>(Call.getType()->getScalarType()), 4841 "gc.relocate must return a pointer or a vector of pointers", Call); 4842 4843 // Check that this relocate is correctly tied to the statepoint 4844 4845 // This is case for relocate on the unwinding path of an invoke statepoint 4846 if (LandingPadInst *LandingPad = 4847 dyn_cast<LandingPadInst>(Call.getArgOperand(0))) { 4848 4849 const BasicBlock *InvokeBB = 4850 LandingPad->getParent()->getUniquePredecessor(); 4851 4852 // Landingpad relocates should have only one predecessor with invoke 4853 // statepoint terminator 4854 Assert(InvokeBB, "safepoints should have unique landingpads", 4855 LandingPad->getParent()); 4856 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4857 InvokeBB); 4858 Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()), 4859 "gc relocate should be linked to a statepoint", InvokeBB); 4860 } else { 4861 // In all other cases relocate should be tied to the statepoint directly. 4862 // This covers relocates on a normal return path of invoke statepoint and 4863 // relocates of a call statepoint. 4864 auto Token = Call.getArgOperand(0); 4865 Assert(isa<GCStatepointInst>(Token), 4866 "gc relocate is incorrectly tied to the statepoint", Call, Token); 4867 } 4868 4869 // Verify rest of the relocate arguments. 4870 const CallBase &StatepointCall = 4871 *cast<GCRelocateInst>(Call).getStatepoint(); 4872 4873 // Both the base and derived must be piped through the safepoint. 4874 Value *Base = Call.getArgOperand(1); 4875 Assert(isa<ConstantInt>(Base), 4876 "gc.relocate operand #2 must be integer offset", Call); 4877 4878 Value *Derived = Call.getArgOperand(2); 4879 Assert(isa<ConstantInt>(Derived), 4880 "gc.relocate operand #3 must be integer offset", Call); 4881 4882 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 4883 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 4884 4885 // Check the bounds 4886 if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) { 4887 Assert(BaseIndex < Opt->Inputs.size(), 4888 "gc.relocate: statepoint base index out of bounds", Call); 4889 Assert(DerivedIndex < Opt->Inputs.size(), 4890 "gc.relocate: statepoint derived index out of bounds", Call); 4891 } 4892 4893 // Relocated value must be either a pointer type or vector-of-pointer type, 4894 // but gc_relocate does not need to return the same pointer type as the 4895 // relocated pointer. It can be casted to the correct type later if it's 4896 // desired. However, they must have the same address space and 'vectorness' 4897 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call); 4898 Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(), 4899 "gc.relocate: relocated value must be a gc pointer", Call); 4900 4901 auto ResultType = Call.getType(); 4902 auto DerivedType = Relocate.getDerivedPtr()->getType(); 4903 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 4904 "gc.relocate: vector relocates to vector and pointer to pointer", 4905 Call); 4906 Assert( 4907 ResultType->getPointerAddressSpace() == 4908 DerivedType->getPointerAddressSpace(), 4909 "gc.relocate: relocating a pointer shouldn't change its address space", 4910 Call); 4911 break; 4912 } 4913 case Intrinsic::eh_exceptioncode: 4914 case Intrinsic::eh_exceptionpointer: { 4915 Assert(isa<CatchPadInst>(Call.getArgOperand(0)), 4916 "eh.exceptionpointer argument must be a catchpad", Call); 4917 break; 4918 } 4919 case Intrinsic::get_active_lane_mask: { 4920 Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a " 4921 "vector", Call); 4922 auto *ElemTy = Call.getType()->getScalarType(); 4923 Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not " 4924 "i1", Call); 4925 break; 4926 } 4927 case Intrinsic::masked_load: { 4928 Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector", 4929 Call); 4930 4931 Value *Ptr = Call.getArgOperand(0); 4932 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1)); 4933 Value *Mask = Call.getArgOperand(2); 4934 Value *PassThru = Call.getArgOperand(3); 4935 Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector", 4936 Call); 4937 Assert(Alignment->getValue().isPowerOf2(), 4938 "masked_load: alignment must be a power of 2", Call); 4939 4940 // DataTy is the overloaded type 4941 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4942 Assert(DataTy == Call.getType(), 4943 "masked_load: return must match pointer type", Call); 4944 Assert(PassThru->getType() == DataTy, 4945 "masked_load: pass through and data type must match", Call); 4946 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 4947 cast<VectorType>(DataTy)->getElementCount(), 4948 "masked_load: vector mask must be same length as data", Call); 4949 break; 4950 } 4951 case Intrinsic::masked_store: { 4952 Value *Val = Call.getArgOperand(0); 4953 Value *Ptr = Call.getArgOperand(1); 4954 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2)); 4955 Value *Mask = Call.getArgOperand(3); 4956 Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector", 4957 Call); 4958 Assert(Alignment->getValue().isPowerOf2(), 4959 "masked_store: alignment must be a power of 2", Call); 4960 4961 // DataTy is the overloaded type 4962 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4963 Assert(DataTy == Val->getType(), 4964 "masked_store: storee must match pointer type", Call); 4965 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 4966 cast<VectorType>(DataTy)->getElementCount(), 4967 "masked_store: vector mask must be same length as data", Call); 4968 break; 4969 } 4970 4971 case Intrinsic::masked_gather: { 4972 const APInt &Alignment = 4973 cast<ConstantInt>(Call.getArgOperand(1))->getValue(); 4974 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 4975 "masked_gather: alignment must be 0 or a power of 2", Call); 4976 break; 4977 } 4978 case Intrinsic::masked_scatter: { 4979 const APInt &Alignment = 4980 cast<ConstantInt>(Call.getArgOperand(2))->getValue(); 4981 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 4982 "masked_scatter: alignment must be 0 or a power of 2", Call); 4983 break; 4984 } 4985 4986 case Intrinsic::experimental_guard: { 4987 Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call); 4988 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4989 "experimental_guard must have exactly one " 4990 "\"deopt\" operand bundle"); 4991 break; 4992 } 4993 4994 case Intrinsic::experimental_deoptimize: { 4995 Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked", 4996 Call); 4997 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4998 "experimental_deoptimize must have exactly one " 4999 "\"deopt\" operand bundle"); 5000 Assert(Call.getType() == Call.getFunction()->getReturnType(), 5001 "experimental_deoptimize return type must match caller return type"); 5002 5003 if (isa<CallInst>(Call)) { 5004 auto *RI = dyn_cast<ReturnInst>(Call.getNextNode()); 5005 Assert(RI, 5006 "calls to experimental_deoptimize must be followed by a return"); 5007 5008 if (!Call.getType()->isVoidTy() && RI) 5009 Assert(RI->getReturnValue() == &Call, 5010 "calls to experimental_deoptimize must be followed by a return " 5011 "of the value computed by experimental_deoptimize"); 5012 } 5013 5014 break; 5015 } 5016 case Intrinsic::sadd_sat: 5017 case Intrinsic::uadd_sat: 5018 case Intrinsic::ssub_sat: 5019 case Intrinsic::usub_sat: 5020 case Intrinsic::sshl_sat: 5021 case Intrinsic::ushl_sat: { 5022 Value *Op1 = Call.getArgOperand(0); 5023 Value *Op2 = Call.getArgOperand(1); 5024 Assert(Op1->getType()->isIntOrIntVectorTy(), 5025 "first operand of [us][add|sub|shl]_sat must be an int type or " 5026 "vector of ints"); 5027 Assert(Op2->getType()->isIntOrIntVectorTy(), 5028 "second operand of [us][add|sub|shl]_sat must be an int type or " 5029 "vector of ints"); 5030 break; 5031 } 5032 case Intrinsic::smul_fix: 5033 case Intrinsic::smul_fix_sat: 5034 case Intrinsic::umul_fix: 5035 case Intrinsic::umul_fix_sat: 5036 case Intrinsic::sdiv_fix: 5037 case Intrinsic::sdiv_fix_sat: 5038 case Intrinsic::udiv_fix: 5039 case Intrinsic::udiv_fix_sat: { 5040 Value *Op1 = Call.getArgOperand(0); 5041 Value *Op2 = Call.getArgOperand(1); 5042 Assert(Op1->getType()->isIntOrIntVectorTy(), 5043 "first operand of [us][mul|div]_fix[_sat] must be an int type or " 5044 "vector of ints"); 5045 Assert(Op2->getType()->isIntOrIntVectorTy(), 5046 "second operand of [us][mul|div]_fix[_sat] must be an int type or " 5047 "vector of ints"); 5048 5049 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2)); 5050 Assert(Op3->getType()->getBitWidth() <= 32, 5051 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits"); 5052 5053 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat || 5054 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) { 5055 Assert( 5056 Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(), 5057 "the scale of s[mul|div]_fix[_sat] must be less than the width of " 5058 "the operands"); 5059 } else { 5060 Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(), 5061 "the scale of u[mul|div]_fix[_sat] must be less than or equal " 5062 "to the width of the operands"); 5063 } 5064 break; 5065 } 5066 case Intrinsic::lround: 5067 case Intrinsic::llround: 5068 case Intrinsic::lrint: 5069 case Intrinsic::llrint: { 5070 Type *ValTy = Call.getArgOperand(0)->getType(); 5071 Type *ResultTy = Call.getType(); 5072 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5073 "Intrinsic does not support vectors", &Call); 5074 break; 5075 } 5076 case Intrinsic::bswap: { 5077 Type *Ty = Call.getType(); 5078 unsigned Size = Ty->getScalarSizeInBits(); 5079 Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call); 5080 break; 5081 } 5082 case Intrinsic::invariant_start: { 5083 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 5084 Assert(InvariantSize && 5085 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()), 5086 "invariant_start parameter must be -1, 0 or a positive number", 5087 &Call); 5088 break; 5089 } 5090 case Intrinsic::matrix_multiply: 5091 case Intrinsic::matrix_transpose: 5092 case Intrinsic::matrix_column_major_load: 5093 case Intrinsic::matrix_column_major_store: { 5094 Function *IF = Call.getCalledFunction(); 5095 ConstantInt *Stride = nullptr; 5096 ConstantInt *NumRows; 5097 ConstantInt *NumColumns; 5098 VectorType *ResultTy; 5099 Type *Op0ElemTy = nullptr; 5100 Type *Op1ElemTy = nullptr; 5101 switch (ID) { 5102 case Intrinsic::matrix_multiply: 5103 NumRows = cast<ConstantInt>(Call.getArgOperand(2)); 5104 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5105 ResultTy = cast<VectorType>(Call.getType()); 5106 Op0ElemTy = 5107 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5108 Op1ElemTy = 5109 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType(); 5110 break; 5111 case Intrinsic::matrix_transpose: 5112 NumRows = cast<ConstantInt>(Call.getArgOperand(1)); 5113 NumColumns = cast<ConstantInt>(Call.getArgOperand(2)); 5114 ResultTy = cast<VectorType>(Call.getType()); 5115 Op0ElemTy = 5116 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5117 break; 5118 case Intrinsic::matrix_column_major_load: 5119 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1)); 5120 NumRows = cast<ConstantInt>(Call.getArgOperand(3)); 5121 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5122 ResultTy = cast<VectorType>(Call.getType()); 5123 Op0ElemTy = 5124 cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType(); 5125 break; 5126 case Intrinsic::matrix_column_major_store: 5127 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2)); 5128 NumRows = cast<ConstantInt>(Call.getArgOperand(4)); 5129 NumColumns = cast<ConstantInt>(Call.getArgOperand(5)); 5130 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5131 Op0ElemTy = 5132 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5133 Op1ElemTy = 5134 cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType(); 5135 break; 5136 default: 5137 llvm_unreachable("unexpected intrinsic"); 5138 } 5139 5140 Assert(ResultTy->getElementType()->isIntegerTy() || 5141 ResultTy->getElementType()->isFloatingPointTy(), 5142 "Result type must be an integer or floating-point type!", IF); 5143 5144 Assert(ResultTy->getElementType() == Op0ElemTy, 5145 "Vector element type mismatch of the result and first operand " 5146 "vector!", IF); 5147 5148 if (Op1ElemTy) 5149 Assert(ResultTy->getElementType() == Op1ElemTy, 5150 "Vector element type mismatch of the result and second operand " 5151 "vector!", IF); 5152 5153 Assert(cast<FixedVectorType>(ResultTy)->getNumElements() == 5154 NumRows->getZExtValue() * NumColumns->getZExtValue(), 5155 "Result of a matrix operation does not fit in the returned vector!"); 5156 5157 if (Stride) 5158 Assert(Stride->getZExtValue() >= NumRows->getZExtValue(), 5159 "Stride must be greater or equal than the number of rows!", IF); 5160 5161 break; 5162 } 5163 case Intrinsic::experimental_vector_insert: { 5164 VectorType *VecTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5165 VectorType *SubVecTy = cast<VectorType>(Call.getArgOperand(1)->getType()); 5166 5167 Assert(VecTy->getElementType() == SubVecTy->getElementType(), 5168 "experimental_vector_insert parameters must have the same element " 5169 "type.", 5170 &Call); 5171 break; 5172 } 5173 case Intrinsic::experimental_vector_extract: { 5174 VectorType *ResultTy = cast<VectorType>(Call.getType()); 5175 VectorType *VecTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5176 5177 Assert(ResultTy->getElementType() == VecTy->getElementType(), 5178 "experimental_vector_extract result must have the same element " 5179 "type as the input vector.", 5180 &Call); 5181 break; 5182 } 5183 case Intrinsic::experimental_noalias_scope_decl: { 5184 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call)); 5185 break; 5186 } 5187 }; 5188 } 5189 5190 /// Carefully grab the subprogram from a local scope. 5191 /// 5192 /// This carefully grabs the subprogram from a local scope, avoiding the 5193 /// built-in assertions that would typically fire. 5194 static DISubprogram *getSubprogram(Metadata *LocalScope) { 5195 if (!LocalScope) 5196 return nullptr; 5197 5198 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 5199 return SP; 5200 5201 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 5202 return getSubprogram(LB->getRawScope()); 5203 5204 // Just return null; broken scope chains are checked elsewhere. 5205 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 5206 return nullptr; 5207 } 5208 5209 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) { 5210 unsigned NumOperands; 5211 bool HasRoundingMD; 5212 switch (FPI.getIntrinsicID()) { 5213 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 5214 case Intrinsic::INTRINSIC: \ 5215 NumOperands = NARG; \ 5216 HasRoundingMD = ROUND_MODE; \ 5217 break; 5218 #include "llvm/IR/ConstrainedOps.def" 5219 default: 5220 llvm_unreachable("Invalid constrained FP intrinsic!"); 5221 } 5222 NumOperands += (1 + HasRoundingMD); 5223 // Compare intrinsics carry an extra predicate metadata operand. 5224 if (isa<ConstrainedFPCmpIntrinsic>(FPI)) 5225 NumOperands += 1; 5226 Assert((FPI.getNumArgOperands() == NumOperands), 5227 "invalid arguments for constrained FP intrinsic", &FPI); 5228 5229 switch (FPI.getIntrinsicID()) { 5230 case Intrinsic::experimental_constrained_lrint: 5231 case Intrinsic::experimental_constrained_llrint: { 5232 Type *ValTy = FPI.getArgOperand(0)->getType(); 5233 Type *ResultTy = FPI.getType(); 5234 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5235 "Intrinsic does not support vectors", &FPI); 5236 } 5237 break; 5238 5239 case Intrinsic::experimental_constrained_lround: 5240 case Intrinsic::experimental_constrained_llround: { 5241 Type *ValTy = FPI.getArgOperand(0)->getType(); 5242 Type *ResultTy = FPI.getType(); 5243 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5244 "Intrinsic does not support vectors", &FPI); 5245 break; 5246 } 5247 5248 case Intrinsic::experimental_constrained_fcmp: 5249 case Intrinsic::experimental_constrained_fcmps: { 5250 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate(); 5251 Assert(CmpInst::isFPPredicate(Pred), 5252 "invalid predicate for constrained FP comparison intrinsic", &FPI); 5253 break; 5254 } 5255 5256 case Intrinsic::experimental_constrained_fptosi: 5257 case Intrinsic::experimental_constrained_fptoui: { 5258 Value *Operand = FPI.getArgOperand(0); 5259 uint64_t NumSrcElem = 0; 5260 Assert(Operand->getType()->isFPOrFPVectorTy(), 5261 "Intrinsic first argument must be floating point", &FPI); 5262 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5263 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5264 } 5265 5266 Operand = &FPI; 5267 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5268 "Intrinsic first argument and result disagree on vector use", &FPI); 5269 Assert(Operand->getType()->isIntOrIntVectorTy(), 5270 "Intrinsic result must be an integer", &FPI); 5271 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5272 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5273 "Intrinsic first argument and result vector lengths must be equal", 5274 &FPI); 5275 } 5276 } 5277 break; 5278 5279 case Intrinsic::experimental_constrained_sitofp: 5280 case Intrinsic::experimental_constrained_uitofp: { 5281 Value *Operand = FPI.getArgOperand(0); 5282 uint64_t NumSrcElem = 0; 5283 Assert(Operand->getType()->isIntOrIntVectorTy(), 5284 "Intrinsic first argument must be integer", &FPI); 5285 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5286 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5287 } 5288 5289 Operand = &FPI; 5290 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5291 "Intrinsic first argument and result disagree on vector use", &FPI); 5292 Assert(Operand->getType()->isFPOrFPVectorTy(), 5293 "Intrinsic result must be a floating point", &FPI); 5294 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5295 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5296 "Intrinsic first argument and result vector lengths must be equal", 5297 &FPI); 5298 } 5299 } break; 5300 5301 case Intrinsic::experimental_constrained_fptrunc: 5302 case Intrinsic::experimental_constrained_fpext: { 5303 Value *Operand = FPI.getArgOperand(0); 5304 Type *OperandTy = Operand->getType(); 5305 Value *Result = &FPI; 5306 Type *ResultTy = Result->getType(); 5307 Assert(OperandTy->isFPOrFPVectorTy(), 5308 "Intrinsic first argument must be FP or FP vector", &FPI); 5309 Assert(ResultTy->isFPOrFPVectorTy(), 5310 "Intrinsic result must be FP or FP vector", &FPI); 5311 Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(), 5312 "Intrinsic first argument and result disagree on vector use", &FPI); 5313 if (OperandTy->isVectorTy()) { 5314 Assert(cast<FixedVectorType>(OperandTy)->getNumElements() == 5315 cast<FixedVectorType>(ResultTy)->getNumElements(), 5316 "Intrinsic first argument and result vector lengths must be equal", 5317 &FPI); 5318 } 5319 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) { 5320 Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(), 5321 "Intrinsic first argument's type must be larger than result type", 5322 &FPI); 5323 } else { 5324 Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(), 5325 "Intrinsic first argument's type must be smaller than result type", 5326 &FPI); 5327 } 5328 } 5329 break; 5330 5331 default: 5332 break; 5333 } 5334 5335 // If a non-metadata argument is passed in a metadata slot then the 5336 // error will be caught earlier when the incorrect argument doesn't 5337 // match the specification in the intrinsic call table. Thus, no 5338 // argument type check is needed here. 5339 5340 Assert(FPI.getExceptionBehavior().hasValue(), 5341 "invalid exception behavior argument", &FPI); 5342 if (HasRoundingMD) { 5343 Assert(FPI.getRoundingMode().hasValue(), 5344 "invalid rounding mode argument", &FPI); 5345 } 5346 } 5347 5348 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) { 5349 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata(); 5350 AssertDI(isa<ValueAsMetadata>(MD) || 5351 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 5352 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 5353 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 5354 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 5355 DII.getRawVariable()); 5356 AssertDI(isa<DIExpression>(DII.getRawExpression()), 5357 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 5358 DII.getRawExpression()); 5359 5360 // Ignore broken !dbg attachments; they're checked elsewhere. 5361 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 5362 if (!isa<DILocation>(N)) 5363 return; 5364 5365 BasicBlock *BB = DII.getParent(); 5366 Function *F = BB ? BB->getParent() : nullptr; 5367 5368 // The scopes for variables and !dbg attachments must agree. 5369 DILocalVariable *Var = DII.getVariable(); 5370 DILocation *Loc = DII.getDebugLoc(); 5371 AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5372 &DII, BB, F); 5373 5374 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 5375 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5376 if (!VarSP || !LocSP) 5377 return; // Broken scope chains are checked elsewhere. 5378 5379 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5380 " variable and !dbg attachment", 5381 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 5382 Loc->getScope()->getSubprogram()); 5383 5384 // This check is redundant with one in visitLocalVariable(). 5385 AssertDI(isType(Var->getRawType()), "invalid type ref", Var, 5386 Var->getRawType()); 5387 verifyFnArgs(DII); 5388 } 5389 5390 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) { 5391 AssertDI(isa<DILabel>(DLI.getRawLabel()), 5392 "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI, 5393 DLI.getRawLabel()); 5394 5395 // Ignore broken !dbg attachments; they're checked elsewhere. 5396 if (MDNode *N = DLI.getDebugLoc().getAsMDNode()) 5397 if (!isa<DILocation>(N)) 5398 return; 5399 5400 BasicBlock *BB = DLI.getParent(); 5401 Function *F = BB ? BB->getParent() : nullptr; 5402 5403 // The scopes for variables and !dbg attachments must agree. 5404 DILabel *Label = DLI.getLabel(); 5405 DILocation *Loc = DLI.getDebugLoc(); 5406 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5407 &DLI, BB, F); 5408 5409 DISubprogram *LabelSP = getSubprogram(Label->getRawScope()); 5410 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5411 if (!LabelSP || !LocSP) 5412 return; 5413 5414 AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5415 " label and !dbg attachment", 5416 &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc, 5417 Loc->getScope()->getSubprogram()); 5418 } 5419 5420 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) { 5421 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable()); 5422 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5423 5424 // We don't know whether this intrinsic verified correctly. 5425 if (!V || !E || !E->isValid()) 5426 return; 5427 5428 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression. 5429 auto Fragment = E->getFragmentInfo(); 5430 if (!Fragment) 5431 return; 5432 5433 // The frontend helps out GDB by emitting the members of local anonymous 5434 // unions as artificial local variables with shared storage. When SROA splits 5435 // the storage for artificial local variables that are smaller than the entire 5436 // union, the overhang piece will be outside of the allotted space for the 5437 // variable and this check fails. 5438 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 5439 if (V->isArtificial()) 5440 return; 5441 5442 verifyFragmentExpression(*V, *Fragment, &I); 5443 } 5444 5445 template <typename ValueOrMetadata> 5446 void Verifier::verifyFragmentExpression(const DIVariable &V, 5447 DIExpression::FragmentInfo Fragment, 5448 ValueOrMetadata *Desc) { 5449 // If there's no size, the type is broken, but that should be checked 5450 // elsewhere. 5451 auto VarSize = V.getSizeInBits(); 5452 if (!VarSize) 5453 return; 5454 5455 unsigned FragSize = Fragment.SizeInBits; 5456 unsigned FragOffset = Fragment.OffsetInBits; 5457 AssertDI(FragSize + FragOffset <= *VarSize, 5458 "fragment is larger than or outside of variable", Desc, &V); 5459 AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V); 5460 } 5461 5462 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) { 5463 // This function does not take the scope of noninlined function arguments into 5464 // account. Don't run it if current function is nodebug, because it may 5465 // contain inlined debug intrinsics. 5466 if (!HasDebugInfo) 5467 return; 5468 5469 // For performance reasons only check non-inlined ones. 5470 if (I.getDebugLoc()->getInlinedAt()) 5471 return; 5472 5473 DILocalVariable *Var = I.getVariable(); 5474 AssertDI(Var, "dbg intrinsic without variable"); 5475 5476 unsigned ArgNo = Var->getArg(); 5477 if (!ArgNo) 5478 return; 5479 5480 // Verify there are no duplicate function argument debug info entries. 5481 // These will cause hard-to-debug assertions in the DWARF backend. 5482 if (DebugFnArgs.size() < ArgNo) 5483 DebugFnArgs.resize(ArgNo, nullptr); 5484 5485 auto *Prev = DebugFnArgs[ArgNo - 1]; 5486 DebugFnArgs[ArgNo - 1] = Var; 5487 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I, 5488 Prev, Var); 5489 } 5490 5491 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) { 5492 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5493 5494 // We don't know whether this intrinsic verified correctly. 5495 if (!E || !E->isValid()) 5496 return; 5497 5498 AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I); 5499 } 5500 5501 void Verifier::verifyCompileUnits() { 5502 // When more than one Module is imported into the same context, such as during 5503 // an LTO build before linking the modules, ODR type uniquing may cause types 5504 // to point to a different CU. This check does not make sense in this case. 5505 if (M.getContext().isODRUniquingDebugTypes()) 5506 return; 5507 auto *CUs = M.getNamedMetadata("llvm.dbg.cu"); 5508 SmallPtrSet<const Metadata *, 2> Listed; 5509 if (CUs) 5510 Listed.insert(CUs->op_begin(), CUs->op_end()); 5511 for (auto *CU : CUVisited) 5512 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU); 5513 CUVisited.clear(); 5514 } 5515 5516 void Verifier::verifyDeoptimizeCallingConvs() { 5517 if (DeoptimizeDeclarations.empty()) 5518 return; 5519 5520 const Function *First = DeoptimizeDeclarations[0]; 5521 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 5522 Assert(First->getCallingConv() == F->getCallingConv(), 5523 "All llvm.experimental.deoptimize declarations must have the same " 5524 "calling convention", 5525 First, F); 5526 } 5527 } 5528 5529 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) { 5530 bool HasSource = F.getSource().hasValue(); 5531 if (!HasSourceDebugInfo.count(&U)) 5532 HasSourceDebugInfo[&U] = HasSource; 5533 AssertDI(HasSource == HasSourceDebugInfo[&U], 5534 "inconsistent use of embedded source"); 5535 } 5536 5537 void Verifier::verifyNoAliasScopeDecl() { 5538 if (NoAliasScopeDecls.empty()) 5539 return; 5540 5541 // only a single scope must be declared at a time. 5542 for (auto *II : NoAliasScopeDecls) { 5543 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl && 5544 "Not a llvm.experimental.noalias.scope.decl ?"); 5545 const auto *ScopeListMV = dyn_cast<MetadataAsValue>( 5546 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5547 Assert(ScopeListMV != nullptr, 5548 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue " 5549 "argument", 5550 II); 5551 5552 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata()); 5553 Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", 5554 II); 5555 Assert(ScopeListMD->getNumOperands() == 1, 5556 "!id.scope.list must point to a list with a single scope", II); 5557 } 5558 5559 // Only check the domination rule when requested. Once all passes have been 5560 // adapted this option can go away. 5561 if (!VerifyNoAliasScopeDomination) 5562 return; 5563 5564 // Now sort the intrinsics based on the scope MDNode so that declarations of 5565 // the same scopes are next to each other. 5566 auto GetScope = [](IntrinsicInst *II) { 5567 const auto *ScopeListMV = cast<MetadataAsValue>( 5568 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5569 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0); 5570 }; 5571 5572 // We are sorting on MDNode pointers here. For valid input IR this is ok. 5573 // TODO: Sort on Metadata ID to avoid non-deterministic error messages. 5574 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) { 5575 return GetScope(Lhs) < GetScope(Rhs); 5576 }; 5577 5578 llvm::sort(NoAliasScopeDecls, Compare); 5579 5580 // Go over the intrinsics and check that for the same scope, they are not 5581 // dominating each other. 5582 auto ItCurrent = NoAliasScopeDecls.begin(); 5583 while (ItCurrent != NoAliasScopeDecls.end()) { 5584 auto CurScope = GetScope(*ItCurrent); 5585 auto ItNext = ItCurrent; 5586 do { 5587 ++ItNext; 5588 } while (ItNext != NoAliasScopeDecls.end() && 5589 GetScope(*ItNext) == CurScope); 5590 5591 // [ItCurrent, ItNext) represents the declarations for the same scope. 5592 // Ensure they are not dominating each other.. but only if it is not too 5593 // expensive. 5594 if (ItNext - ItCurrent < 32) 5595 for (auto *I : llvm::make_range(ItCurrent, ItNext)) 5596 for (auto *J : llvm::make_range(ItCurrent, ItNext)) 5597 if (I != J) 5598 Assert(!DT.dominates(I, J), 5599 "llvm.experimental.noalias.scope.decl dominates another one " 5600 "with the same scope", 5601 I); 5602 ItCurrent = ItNext; 5603 } 5604 } 5605 5606 //===----------------------------------------------------------------------===// 5607 // Implement the public interfaces to this file... 5608 //===----------------------------------------------------------------------===// 5609 5610 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 5611 Function &F = const_cast<Function &>(f); 5612 5613 // Don't use a raw_null_ostream. Printing IR is expensive. 5614 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent()); 5615 5616 // Note that this function's return value is inverted from what you would 5617 // expect of a function called "verify". 5618 return !V.verify(F); 5619 } 5620 5621 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 5622 bool *BrokenDebugInfo) { 5623 // Don't use a raw_null_ostream. Printing IR is expensive. 5624 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M); 5625 5626 bool Broken = false; 5627 for (const Function &F : M) 5628 Broken |= !V.verify(F); 5629 5630 Broken |= !V.verify(); 5631 if (BrokenDebugInfo) 5632 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 5633 // Note that this function's return value is inverted from what you would 5634 // expect of a function called "verify". 5635 return Broken; 5636 } 5637 5638 namespace { 5639 5640 struct VerifierLegacyPass : public FunctionPass { 5641 static char ID; 5642 5643 std::unique_ptr<Verifier> V; 5644 bool FatalErrors = true; 5645 5646 VerifierLegacyPass() : FunctionPass(ID) { 5647 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5648 } 5649 explicit VerifierLegacyPass(bool FatalErrors) 5650 : FunctionPass(ID), 5651 FatalErrors(FatalErrors) { 5652 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5653 } 5654 5655 bool doInitialization(Module &M) override { 5656 V = std::make_unique<Verifier>( 5657 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M); 5658 return false; 5659 } 5660 5661 bool runOnFunction(Function &F) override { 5662 if (!V->verify(F) && FatalErrors) { 5663 errs() << "in function " << F.getName() << '\n'; 5664 report_fatal_error("Broken function found, compilation aborted!"); 5665 } 5666 return false; 5667 } 5668 5669 bool doFinalization(Module &M) override { 5670 bool HasErrors = false; 5671 for (Function &F : M) 5672 if (F.isDeclaration()) 5673 HasErrors |= !V->verify(F); 5674 5675 HasErrors |= !V->verify(); 5676 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo())) 5677 report_fatal_error("Broken module found, compilation aborted!"); 5678 return false; 5679 } 5680 5681 void getAnalysisUsage(AnalysisUsage &AU) const override { 5682 AU.setPreservesAll(); 5683 } 5684 }; 5685 5686 } // end anonymous namespace 5687 5688 /// Helper to issue failure from the TBAA verification 5689 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) { 5690 if (Diagnostic) 5691 return Diagnostic->CheckFailed(Args...); 5692 } 5693 5694 #define AssertTBAA(C, ...) \ 5695 do { \ 5696 if (!(C)) { \ 5697 CheckFailed(__VA_ARGS__); \ 5698 return false; \ 5699 } \ 5700 } while (false) 5701 5702 /// Verify that \p BaseNode can be used as the "base type" in the struct-path 5703 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a 5704 /// struct-type node describing an aggregate data structure (like a struct). 5705 TBAAVerifier::TBAABaseNodeSummary 5706 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode, 5707 bool IsNewFormat) { 5708 if (BaseNode->getNumOperands() < 2) { 5709 CheckFailed("Base nodes must have at least two operands", &I, BaseNode); 5710 return {true, ~0u}; 5711 } 5712 5713 auto Itr = TBAABaseNodes.find(BaseNode); 5714 if (Itr != TBAABaseNodes.end()) 5715 return Itr->second; 5716 5717 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat); 5718 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result}); 5719 (void)InsertResult; 5720 assert(InsertResult.second && "We just checked!"); 5721 return Result; 5722 } 5723 5724 TBAAVerifier::TBAABaseNodeSummary 5725 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode, 5726 bool IsNewFormat) { 5727 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u}; 5728 5729 if (BaseNode->getNumOperands() == 2) { 5730 // Scalar nodes can only be accessed at offset 0. 5731 return isValidScalarTBAANode(BaseNode) 5732 ? TBAAVerifier::TBAABaseNodeSummary({false, 0}) 5733 : InvalidNode; 5734 } 5735 5736 if (IsNewFormat) { 5737 if (BaseNode->getNumOperands() % 3 != 0) { 5738 CheckFailed("Access tag nodes must have the number of operands that is a " 5739 "multiple of 3!", BaseNode); 5740 return InvalidNode; 5741 } 5742 } else { 5743 if (BaseNode->getNumOperands() % 2 != 1) { 5744 CheckFailed("Struct tag nodes must have an odd number of operands!", 5745 BaseNode); 5746 return InvalidNode; 5747 } 5748 } 5749 5750 // Check the type size field. 5751 if (IsNewFormat) { 5752 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5753 BaseNode->getOperand(1)); 5754 if (!TypeSizeNode) { 5755 CheckFailed("Type size nodes must be constants!", &I, BaseNode); 5756 return InvalidNode; 5757 } 5758 } 5759 5760 // Check the type name field. In the new format it can be anything. 5761 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) { 5762 CheckFailed("Struct tag nodes have a string as their first operand", 5763 BaseNode); 5764 return InvalidNode; 5765 } 5766 5767 bool Failed = false; 5768 5769 Optional<APInt> PrevOffset; 5770 unsigned BitWidth = ~0u; 5771 5772 // We've already checked that BaseNode is not a degenerate root node with one 5773 // operand in \c verifyTBAABaseNode, so this loop should run at least once. 5774 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 5775 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 5776 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 5777 Idx += NumOpsPerField) { 5778 const MDOperand &FieldTy = BaseNode->getOperand(Idx); 5779 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1); 5780 if (!isa<MDNode>(FieldTy)) { 5781 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode); 5782 Failed = true; 5783 continue; 5784 } 5785 5786 auto *OffsetEntryCI = 5787 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset); 5788 if (!OffsetEntryCI) { 5789 CheckFailed("Offset entries must be constants!", &I, BaseNode); 5790 Failed = true; 5791 continue; 5792 } 5793 5794 if (BitWidth == ~0u) 5795 BitWidth = OffsetEntryCI->getBitWidth(); 5796 5797 if (OffsetEntryCI->getBitWidth() != BitWidth) { 5798 CheckFailed( 5799 "Bitwidth between the offsets and struct type entries must match", &I, 5800 BaseNode); 5801 Failed = true; 5802 continue; 5803 } 5804 5805 // NB! As far as I can tell, we generate a non-strictly increasing offset 5806 // sequence only from structs that have zero size bit fields. When 5807 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we 5808 // pick the field lexically the latest in struct type metadata node. This 5809 // mirrors the actual behavior of the alias analysis implementation. 5810 bool IsAscending = 5811 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue()); 5812 5813 if (!IsAscending) { 5814 CheckFailed("Offsets must be increasing!", &I, BaseNode); 5815 Failed = true; 5816 } 5817 5818 PrevOffset = OffsetEntryCI->getValue(); 5819 5820 if (IsNewFormat) { 5821 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5822 BaseNode->getOperand(Idx + 2)); 5823 if (!MemberSizeNode) { 5824 CheckFailed("Member size entries must be constants!", &I, BaseNode); 5825 Failed = true; 5826 continue; 5827 } 5828 } 5829 } 5830 5831 return Failed ? InvalidNode 5832 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth); 5833 } 5834 5835 static bool IsRootTBAANode(const MDNode *MD) { 5836 return MD->getNumOperands() < 2; 5837 } 5838 5839 static bool IsScalarTBAANodeImpl(const MDNode *MD, 5840 SmallPtrSetImpl<const MDNode *> &Visited) { 5841 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3) 5842 return false; 5843 5844 if (!isa<MDString>(MD->getOperand(0))) 5845 return false; 5846 5847 if (MD->getNumOperands() == 3) { 5848 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 5849 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0)))) 5850 return false; 5851 } 5852 5853 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 5854 return Parent && Visited.insert(Parent).second && 5855 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited)); 5856 } 5857 5858 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) { 5859 auto ResultIt = TBAAScalarNodes.find(MD); 5860 if (ResultIt != TBAAScalarNodes.end()) 5861 return ResultIt->second; 5862 5863 SmallPtrSet<const MDNode *, 4> Visited; 5864 bool Result = IsScalarTBAANodeImpl(MD, Visited); 5865 auto InsertResult = TBAAScalarNodes.insert({MD, Result}); 5866 (void)InsertResult; 5867 assert(InsertResult.second && "Just checked!"); 5868 5869 return Result; 5870 } 5871 5872 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p 5873 /// Offset in place to be the offset within the field node returned. 5874 /// 5875 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode. 5876 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I, 5877 const MDNode *BaseNode, 5878 APInt &Offset, 5879 bool IsNewFormat) { 5880 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!"); 5881 5882 // Scalar nodes have only one possible "field" -- their parent in the access 5883 // hierarchy. Offset must be zero at this point, but our caller is supposed 5884 // to Assert that. 5885 if (BaseNode->getNumOperands() == 2) 5886 return cast<MDNode>(BaseNode->getOperand(1)); 5887 5888 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 5889 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 5890 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 5891 Idx += NumOpsPerField) { 5892 auto *OffsetEntryCI = 5893 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1)); 5894 if (OffsetEntryCI->getValue().ugt(Offset)) { 5895 if (Idx == FirstFieldOpNo) { 5896 CheckFailed("Could not find TBAA parent in struct type node", &I, 5897 BaseNode, &Offset); 5898 return nullptr; 5899 } 5900 5901 unsigned PrevIdx = Idx - NumOpsPerField; 5902 auto *PrevOffsetEntryCI = 5903 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1)); 5904 Offset -= PrevOffsetEntryCI->getValue(); 5905 return cast<MDNode>(BaseNode->getOperand(PrevIdx)); 5906 } 5907 } 5908 5909 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField; 5910 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>( 5911 BaseNode->getOperand(LastIdx + 1)); 5912 Offset -= LastOffsetEntryCI->getValue(); 5913 return cast<MDNode>(BaseNode->getOperand(LastIdx)); 5914 } 5915 5916 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) { 5917 if (!Type || Type->getNumOperands() < 3) 5918 return false; 5919 5920 // In the new format type nodes shall have a reference to the parent type as 5921 // its first operand. 5922 MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0)); 5923 if (!Parent) 5924 return false; 5925 5926 return true; 5927 } 5928 5929 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) { 5930 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 5931 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) || 5932 isa<AtomicCmpXchgInst>(I), 5933 "This instruction shall not have a TBAA access tag!", &I); 5934 5935 bool IsStructPathTBAA = 5936 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 5937 5938 AssertTBAA( 5939 IsStructPathTBAA, 5940 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I); 5941 5942 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0)); 5943 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 5944 5945 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType); 5946 5947 if (IsNewFormat) { 5948 AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5, 5949 "Access tag metadata must have either 4 or 5 operands", &I, MD); 5950 } else { 5951 AssertTBAA(MD->getNumOperands() < 5, 5952 "Struct tag metadata must have either 3 or 4 operands", &I, MD); 5953 } 5954 5955 // Check the access size field. 5956 if (IsNewFormat) { 5957 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5958 MD->getOperand(3)); 5959 AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD); 5960 } 5961 5962 // Check the immutability flag. 5963 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3; 5964 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) { 5965 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>( 5966 MD->getOperand(ImmutabilityFlagOpNo)); 5967 AssertTBAA(IsImmutableCI, 5968 "Immutability tag on struct tag metadata must be a constant", 5969 &I, MD); 5970 AssertTBAA( 5971 IsImmutableCI->isZero() || IsImmutableCI->isOne(), 5972 "Immutability part of the struct tag metadata must be either 0 or 1", 5973 &I, MD); 5974 } 5975 5976 AssertTBAA(BaseNode && AccessType, 5977 "Malformed struct tag metadata: base and access-type " 5978 "should be non-null and point to Metadata nodes", 5979 &I, MD, BaseNode, AccessType); 5980 5981 if (!IsNewFormat) { 5982 AssertTBAA(isValidScalarTBAANode(AccessType), 5983 "Access type node must be a valid scalar type", &I, MD, 5984 AccessType); 5985 } 5986 5987 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2)); 5988 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD); 5989 5990 APInt Offset = OffsetCI->getValue(); 5991 bool SeenAccessTypeInPath = false; 5992 5993 SmallPtrSet<MDNode *, 4> StructPath; 5994 5995 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode); 5996 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, 5997 IsNewFormat)) { 5998 if (!StructPath.insert(BaseNode).second) { 5999 CheckFailed("Cycle detected in struct path", &I, MD); 6000 return false; 6001 } 6002 6003 bool Invalid; 6004 unsigned BaseNodeBitWidth; 6005 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode, 6006 IsNewFormat); 6007 6008 // If the base node is invalid in itself, then we've already printed all the 6009 // errors we wanted to print. 6010 if (Invalid) 6011 return false; 6012 6013 SeenAccessTypeInPath |= BaseNode == AccessType; 6014 6015 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType) 6016 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access", 6017 &I, MD, &Offset); 6018 6019 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() || 6020 (BaseNodeBitWidth == 0 && Offset == 0) || 6021 (IsNewFormat && BaseNodeBitWidth == ~0u), 6022 "Access bit-width not the same as description bit-width", &I, MD, 6023 BaseNodeBitWidth, Offset.getBitWidth()); 6024 6025 if (IsNewFormat && SeenAccessTypeInPath) 6026 break; 6027 } 6028 6029 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", 6030 &I, MD); 6031 return true; 6032 } 6033 6034 char VerifierLegacyPass::ID = 0; 6035 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 6036 6037 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 6038 return new VerifierLegacyPass(FatalErrors); 6039 } 6040 6041 AnalysisKey VerifierAnalysis::Key; 6042 VerifierAnalysis::Result VerifierAnalysis::run(Module &M, 6043 ModuleAnalysisManager &) { 6044 Result Res; 6045 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 6046 return Res; 6047 } 6048 6049 VerifierAnalysis::Result VerifierAnalysis::run(Function &F, 6050 FunctionAnalysisManager &) { 6051 return { llvm::verifyFunction(F, &dbgs()), false }; 6052 } 6053 6054 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 6055 auto Res = AM.getResult<VerifierAnalysis>(M); 6056 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken)) 6057 report_fatal_error("Broken module found, compilation aborted!"); 6058 6059 return PreservedAnalyses::all(); 6060 } 6061 6062 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 6063 auto res = AM.getResult<VerifierAnalysis>(F); 6064 if (res.IRBroken && FatalErrors) 6065 report_fatal_error("Broken function found, compilation aborted!"); 6066 6067 return PreservedAnalyses::all(); 6068 } 6069