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