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