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