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