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