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 if (Attrs.hasAttribute(Attribute::ByVal)) { 1843 SmallPtrSet<Type *, 4> Visited; 1844 Assert(Attrs.getByValType()->isSized(&Visited), 1845 "Attribute 'byval' does not support unsized types!", V); 1846 } 1847 if (Attrs.hasAttribute(Attribute::ByRef)) { 1848 SmallPtrSet<Type *, 4> Visited; 1849 Assert(Attrs.getByRefType()->isSized(&Visited), 1850 "Attribute 'byref' does not support unsized types!", V); 1851 } 1852 if (Attrs.hasAttribute(Attribute::InAlloca)) { 1853 SmallPtrSet<Type *, 4> Visited; 1854 Assert(Attrs.getInAllocaType()->isSized(&Visited), 1855 "Attribute 'inalloca' does not support unsized types!", V); 1856 } 1857 if (Attrs.hasAttribute(Attribute::Preallocated)) { 1858 SmallPtrSet<Type *, 4> Visited; 1859 Assert(Attrs.getPreallocatedType()->isSized(&Visited), 1860 "Attribute 'preallocated' does not support unsized types!", V); 1861 } 1862 if (!PTy->isOpaque()) { 1863 if (!isa<PointerType>(PTy->getElementType())) 1864 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1865 "Attribute 'swifterror' only applies to parameters " 1866 "with pointer to pointer type!", 1867 V); 1868 if (Attrs.hasAttribute(Attribute::ByRef)) { 1869 Assert(Attrs.getByRefType() == PTy->getElementType(), 1870 "Attribute 'byref' type does not match parameter!", V); 1871 } 1872 1873 if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) { 1874 Assert(Attrs.getByValType() == PTy->getElementType(), 1875 "Attribute 'byval' type does not match parameter!", V); 1876 } 1877 1878 if (Attrs.hasAttribute(Attribute::Preallocated)) { 1879 Assert(Attrs.getPreallocatedType() == PTy->getElementType(), 1880 "Attribute 'preallocated' type does not match parameter!", V); 1881 } 1882 1883 if (Attrs.hasAttribute(Attribute::InAlloca)) { 1884 Assert(Attrs.getInAllocaType() == PTy->getElementType(), 1885 "Attribute 'inalloca' type does not match parameter!", V); 1886 } 1887 } 1888 } else { 1889 Assert(!Attrs.hasAttribute(Attribute::ByVal), 1890 "Attribute 'byval' only applies to parameters with pointer type!", 1891 V); 1892 Assert(!Attrs.hasAttribute(Attribute::ByRef), 1893 "Attribute 'byref' only applies to parameters with pointer type!", 1894 V); 1895 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1896 "Attribute 'swifterror' only applies to parameters " 1897 "with pointer type!", 1898 V); 1899 } 1900 } 1901 1902 // Check parameter attributes against a function type. 1903 // The value V is printed in error messages. 1904 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 1905 const Value *V, bool IsIntrinsic) { 1906 if (Attrs.isEmpty()) 1907 return; 1908 1909 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) { 1910 Assert(Attrs.hasParentContext(Context), 1911 "Attribute list does not match Module context!", &Attrs, V); 1912 for (const auto &AttrSet : Attrs) { 1913 Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context), 1914 "Attribute set does not match Module context!", &AttrSet, V); 1915 for (const auto &A : AttrSet) { 1916 Assert(A.hasParentContext(Context), 1917 "Attribute does not match Module context!", &A, V); 1918 } 1919 } 1920 } 1921 1922 bool SawNest = false; 1923 bool SawReturned = false; 1924 bool SawSRet = false; 1925 bool SawSwiftSelf = false; 1926 bool SawSwiftAsync = false; 1927 bool SawSwiftError = false; 1928 1929 // Verify return value attributes. 1930 AttributeSet RetAttrs = Attrs.getRetAttributes(); 1931 Assert((!RetAttrs.hasAttribute(Attribute::ByVal) && 1932 !RetAttrs.hasAttribute(Attribute::Nest) && 1933 !RetAttrs.hasAttribute(Attribute::StructRet) && 1934 !RetAttrs.hasAttribute(Attribute::NoCapture) && 1935 !RetAttrs.hasAttribute(Attribute::NoFree) && 1936 !RetAttrs.hasAttribute(Attribute::Returned) && 1937 !RetAttrs.hasAttribute(Attribute::InAlloca) && 1938 !RetAttrs.hasAttribute(Attribute::Preallocated) && 1939 !RetAttrs.hasAttribute(Attribute::ByRef) && 1940 !RetAttrs.hasAttribute(Attribute::SwiftSelf) && 1941 !RetAttrs.hasAttribute(Attribute::SwiftAsync) && 1942 !RetAttrs.hasAttribute(Attribute::SwiftError)), 1943 "Attributes 'byval', 'inalloca', 'preallocated', 'byref', " 1944 "'nest', 'sret', 'nocapture', 'nofree', " 1945 "'returned', 'swiftself', 'swiftasync', and 'swifterror'" 1946 " do not apply to return values!", 1947 V); 1948 Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) && 1949 !RetAttrs.hasAttribute(Attribute::WriteOnly) && 1950 !RetAttrs.hasAttribute(Attribute::ReadNone)), 1951 "Attribute '" + RetAttrs.getAsString() + 1952 "' does not apply to function returns", 1953 V); 1954 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V); 1955 1956 // Verify parameter attributes. 1957 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1958 Type *Ty = FT->getParamType(i); 1959 AttributeSet ArgAttrs = Attrs.getParamAttributes(i); 1960 1961 if (!IsIntrinsic) { 1962 Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg), 1963 "immarg attribute only applies to intrinsics",V); 1964 } 1965 1966 verifyParameterAttrs(ArgAttrs, Ty, V); 1967 1968 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 1969 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1970 SawNest = true; 1971 } 1972 1973 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 1974 Assert(!SawReturned, "More than one parameter has attribute returned!", 1975 V); 1976 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1977 "Incompatible argument and return types for 'returned' attribute", 1978 V); 1979 SawReturned = true; 1980 } 1981 1982 if (ArgAttrs.hasAttribute(Attribute::StructRet)) { 1983 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1984 Assert(i == 0 || i == 1, 1985 "Attribute 'sret' is not on first or second parameter!", V); 1986 SawSRet = true; 1987 } 1988 1989 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) { 1990 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 1991 SawSwiftSelf = true; 1992 } 1993 1994 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) { 1995 Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V); 1996 SawSwiftAsync = true; 1997 } 1998 1999 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) { 2000 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 2001 V); 2002 SawSwiftError = true; 2003 } 2004 2005 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) { 2006 Assert(i == FT->getNumParams() - 1, 2007 "inalloca isn't on the last parameter!", V); 2008 } 2009 } 2010 2011 if (!Attrs.hasAttributes(AttributeList::FunctionIndex)) 2012 return; 2013 2014 verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V); 2015 2016 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2017 Attrs.hasFnAttribute(Attribute::ReadOnly)), 2018 "Attributes 'readnone and readonly' are incompatible!", V); 2019 2020 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2021 Attrs.hasFnAttribute(Attribute::WriteOnly)), 2022 "Attributes 'readnone and writeonly' are incompatible!", V); 2023 2024 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) && 2025 Attrs.hasFnAttribute(Attribute::WriteOnly)), 2026 "Attributes 'readonly and writeonly' are incompatible!", V); 2027 2028 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2029 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)), 2030 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are " 2031 "incompatible!", 2032 V); 2033 2034 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2035 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)), 2036 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 2037 2038 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) && 2039 Attrs.hasFnAttribute(Attribute::AlwaysInline)), 2040 "Attributes 'noinline and alwaysinline' are incompatible!", V); 2041 2042 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) { 2043 Assert(Attrs.hasFnAttribute(Attribute::NoInline), 2044 "Attribute 'optnone' requires 'noinline'!", V); 2045 2046 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize), 2047 "Attributes 'optsize and optnone' are incompatible!", V); 2048 2049 Assert(!Attrs.hasFnAttribute(Attribute::MinSize), 2050 "Attributes 'minsize and optnone' are incompatible!", V); 2051 } 2052 2053 if (Attrs.hasFnAttribute(Attribute::JumpTable)) { 2054 const GlobalValue *GV = cast<GlobalValue>(V); 2055 Assert(GV->hasGlobalUnnamedAddr(), 2056 "Attribute 'jumptable' requires 'unnamed_addr'", V); 2057 } 2058 2059 if (Attrs.hasFnAttribute(Attribute::AllocSize)) { 2060 std::pair<unsigned, Optional<unsigned>> Args = 2061 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex); 2062 2063 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 2064 if (ParamNo >= FT->getNumParams()) { 2065 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 2066 return false; 2067 } 2068 2069 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 2070 CheckFailed("'allocsize' " + Name + 2071 " argument must refer to an integer parameter", 2072 V); 2073 return false; 2074 } 2075 2076 return true; 2077 }; 2078 2079 if (!CheckParam("element size", Args.first)) 2080 return; 2081 2082 if (Args.second && !CheckParam("number of elements", *Args.second)) 2083 return; 2084 } 2085 2086 if (Attrs.hasFnAttribute(Attribute::VScaleRange)) { 2087 std::pair<unsigned, unsigned> Args = 2088 Attrs.getVScaleRangeArgs(AttributeList::FunctionIndex); 2089 2090 if (Args.first > Args.second && Args.second != 0) 2091 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V); 2092 } 2093 2094 if (Attrs.hasFnAttribute("frame-pointer")) { 2095 StringRef FP = Attrs.getAttribute(AttributeList::FunctionIndex, 2096 "frame-pointer").getValueAsString(); 2097 if (FP != "all" && FP != "non-leaf" && FP != "none") 2098 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V); 2099 } 2100 2101 if (Attrs.hasFnAttribute("patchable-function-prefix")) { 2102 StringRef S = Attrs 2103 .getAttribute(AttributeList::FunctionIndex, 2104 "patchable-function-prefix") 2105 .getValueAsString(); 2106 unsigned N; 2107 if (S.getAsInteger(10, N)) 2108 CheckFailed( 2109 "\"patchable-function-prefix\" takes an unsigned integer: " + S, V); 2110 } 2111 if (Attrs.hasFnAttribute("patchable-function-entry")) { 2112 StringRef S = Attrs 2113 .getAttribute(AttributeList::FunctionIndex, 2114 "patchable-function-entry") 2115 .getValueAsString(); 2116 unsigned N; 2117 if (S.getAsInteger(10, N)) 2118 CheckFailed( 2119 "\"patchable-function-entry\" takes an unsigned integer: " + S, V); 2120 } 2121 } 2122 2123 void Verifier::verifyFunctionMetadata( 2124 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 2125 for (const auto &Pair : MDs) { 2126 if (Pair.first == LLVMContext::MD_prof) { 2127 MDNode *MD = Pair.second; 2128 Assert(MD->getNumOperands() >= 2, 2129 "!prof annotations should have no less than 2 operands", MD); 2130 2131 // Check first operand. 2132 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 2133 MD); 2134 Assert(isa<MDString>(MD->getOperand(0)), 2135 "expected string with name of the !prof annotation", MD); 2136 MDString *MDS = cast<MDString>(MD->getOperand(0)); 2137 StringRef ProfName = MDS->getString(); 2138 Assert(ProfName.equals("function_entry_count") || 2139 ProfName.equals("synthetic_function_entry_count"), 2140 "first operand should be 'function_entry_count'" 2141 " or 'synthetic_function_entry_count'", 2142 MD); 2143 2144 // Check second operand. 2145 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 2146 MD); 2147 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 2148 "expected integer argument to function_entry_count", MD); 2149 } 2150 } 2151 } 2152 2153 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 2154 if (!ConstantExprVisited.insert(EntryC).second) 2155 return; 2156 2157 SmallVector<const Constant *, 16> Stack; 2158 Stack.push_back(EntryC); 2159 2160 while (!Stack.empty()) { 2161 const Constant *C = Stack.pop_back_val(); 2162 2163 // Check this constant expression. 2164 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 2165 visitConstantExpr(CE); 2166 2167 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 2168 // Global Values get visited separately, but we do need to make sure 2169 // that the global value is in the correct module 2170 Assert(GV->getParent() == &M, "Referencing global in another module!", 2171 EntryC, &M, GV, GV->getParent()); 2172 continue; 2173 } 2174 2175 // Visit all sub-expressions. 2176 for (const Use &U : C->operands()) { 2177 const auto *OpC = dyn_cast<Constant>(U); 2178 if (!OpC) 2179 continue; 2180 if (!ConstantExprVisited.insert(OpC).second) 2181 continue; 2182 Stack.push_back(OpC); 2183 } 2184 } 2185 } 2186 2187 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 2188 if (CE->getOpcode() == Instruction::BitCast) 2189 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 2190 CE->getType()), 2191 "Invalid bitcast", CE); 2192 } 2193 2194 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) { 2195 // There shouldn't be more attribute sets than there are parameters plus the 2196 // function and return value. 2197 return Attrs.getNumAttrSets() <= Params + 2; 2198 } 2199 2200 /// Verify that statepoint intrinsic is well formed. 2201 void Verifier::verifyStatepoint(const CallBase &Call) { 2202 assert(Call.getCalledFunction() && 2203 Call.getCalledFunction()->getIntrinsicID() == 2204 Intrinsic::experimental_gc_statepoint); 2205 2206 Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() && 2207 !Call.onlyAccessesArgMemory(), 2208 "gc.statepoint must read and write all memory to preserve " 2209 "reordering restrictions required by safepoint semantics", 2210 Call); 2211 2212 const int64_t NumPatchBytes = 2213 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue(); 2214 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 2215 Assert(NumPatchBytes >= 0, 2216 "gc.statepoint number of patchable bytes must be " 2217 "positive", 2218 Call); 2219 2220 const Value *Target = Call.getArgOperand(2); 2221 auto *PT = dyn_cast<PointerType>(Target->getType()); 2222 Assert(PT && PT->getElementType()->isFunctionTy(), 2223 "gc.statepoint callee must be of function pointer type", Call, Target); 2224 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 2225 2226 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue(); 2227 Assert(NumCallArgs >= 0, 2228 "gc.statepoint number of arguments to underlying call " 2229 "must be positive", 2230 Call); 2231 const int NumParams = (int)TargetFuncType->getNumParams(); 2232 if (TargetFuncType->isVarArg()) { 2233 Assert(NumCallArgs >= NumParams, 2234 "gc.statepoint mismatch in number of vararg call args", Call); 2235 2236 // TODO: Remove this limitation 2237 Assert(TargetFuncType->getReturnType()->isVoidTy(), 2238 "gc.statepoint doesn't support wrapping non-void " 2239 "vararg functions yet", 2240 Call); 2241 } else 2242 Assert(NumCallArgs == NumParams, 2243 "gc.statepoint mismatch in number of call args", Call); 2244 2245 const uint64_t Flags 2246 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue(); 2247 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 2248 "unknown flag used in gc.statepoint flags argument", Call); 2249 2250 // Verify that the types of the call parameter arguments match 2251 // the type of the wrapped callee. 2252 AttributeList Attrs = Call.getAttributes(); 2253 for (int i = 0; i < NumParams; i++) { 2254 Type *ParamType = TargetFuncType->getParamType(i); 2255 Type *ArgType = Call.getArgOperand(5 + i)->getType(); 2256 Assert(ArgType == ParamType, 2257 "gc.statepoint call argument does not match wrapped " 2258 "function type", 2259 Call); 2260 2261 if (TargetFuncType->isVarArg()) { 2262 AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i); 2263 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 2264 "Attribute 'sret' cannot be used for vararg call arguments!", 2265 Call); 2266 } 2267 } 2268 2269 const int EndCallArgsInx = 4 + NumCallArgs; 2270 2271 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1); 2272 Assert(isa<ConstantInt>(NumTransitionArgsV), 2273 "gc.statepoint number of transition arguments " 2274 "must be constant integer", 2275 Call); 2276 const int NumTransitionArgs = 2277 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 2278 Assert(NumTransitionArgs == 0, 2279 "gc.statepoint w/inline transition bundle is deprecated", Call); 2280 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 2281 2282 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1); 2283 Assert(isa<ConstantInt>(NumDeoptArgsV), 2284 "gc.statepoint number of deoptimization arguments " 2285 "must be constant integer", 2286 Call); 2287 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 2288 Assert(NumDeoptArgs == 0, 2289 "gc.statepoint w/inline deopt operands is deprecated", Call); 2290 2291 const int ExpectedNumArgs = 7 + NumCallArgs; 2292 Assert(ExpectedNumArgs == (int)Call.arg_size(), 2293 "gc.statepoint too many arguments", Call); 2294 2295 // Check that the only uses of this gc.statepoint are gc.result or 2296 // gc.relocate calls which are tied to this statepoint and thus part 2297 // of the same statepoint sequence 2298 for (const User *U : Call.users()) { 2299 const CallInst *UserCall = dyn_cast<const CallInst>(U); 2300 Assert(UserCall, "illegal use of statepoint token", Call, U); 2301 if (!UserCall) 2302 continue; 2303 Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall), 2304 "gc.result or gc.relocate are the only value uses " 2305 "of a gc.statepoint", 2306 Call, U); 2307 if (isa<GCResultInst>(UserCall)) { 2308 Assert(UserCall->getArgOperand(0) == &Call, 2309 "gc.result connected to wrong gc.statepoint", Call, UserCall); 2310 } else if (isa<GCRelocateInst>(Call)) { 2311 Assert(UserCall->getArgOperand(0) == &Call, 2312 "gc.relocate connected to wrong gc.statepoint", Call, UserCall); 2313 } 2314 } 2315 2316 // Note: It is legal for a single derived pointer to be listed multiple 2317 // times. It's non-optimal, but it is legal. It can also happen after 2318 // insertion if we strip a bitcast away. 2319 // Note: It is really tempting to check that each base is relocated and 2320 // that a derived pointer is never reused as a base pointer. This turns 2321 // out to be problematic since optimizations run after safepoint insertion 2322 // can recognize equality properties that the insertion logic doesn't know 2323 // about. See example statepoint.ll in the verifier subdirectory 2324 } 2325 2326 void Verifier::verifyFrameRecoverIndices() { 2327 for (auto &Counts : FrameEscapeInfo) { 2328 Function *F = Counts.first; 2329 unsigned EscapedObjectCount = Counts.second.first; 2330 unsigned MaxRecoveredIndex = Counts.second.second; 2331 Assert(MaxRecoveredIndex <= EscapedObjectCount, 2332 "all indices passed to llvm.localrecover must be less than the " 2333 "number of arguments passed to llvm.localescape in the parent " 2334 "function", 2335 F); 2336 } 2337 } 2338 2339 static Instruction *getSuccPad(Instruction *Terminator) { 2340 BasicBlock *UnwindDest; 2341 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 2342 UnwindDest = II->getUnwindDest(); 2343 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 2344 UnwindDest = CSI->getUnwindDest(); 2345 else 2346 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 2347 return UnwindDest->getFirstNonPHI(); 2348 } 2349 2350 void Verifier::verifySiblingFuncletUnwinds() { 2351 SmallPtrSet<Instruction *, 8> Visited; 2352 SmallPtrSet<Instruction *, 8> Active; 2353 for (const auto &Pair : SiblingFuncletInfo) { 2354 Instruction *PredPad = Pair.first; 2355 if (Visited.count(PredPad)) 2356 continue; 2357 Active.insert(PredPad); 2358 Instruction *Terminator = Pair.second; 2359 do { 2360 Instruction *SuccPad = getSuccPad(Terminator); 2361 if (Active.count(SuccPad)) { 2362 // Found a cycle; report error 2363 Instruction *CyclePad = SuccPad; 2364 SmallVector<Instruction *, 8> CycleNodes; 2365 do { 2366 CycleNodes.push_back(CyclePad); 2367 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad]; 2368 if (CycleTerminator != CyclePad) 2369 CycleNodes.push_back(CycleTerminator); 2370 CyclePad = getSuccPad(CycleTerminator); 2371 } while (CyclePad != SuccPad); 2372 Assert(false, "EH pads can't handle each other's exceptions", 2373 ArrayRef<Instruction *>(CycleNodes)); 2374 } 2375 // Don't re-walk a node we've already checked 2376 if (!Visited.insert(SuccPad).second) 2377 break; 2378 // Walk to this successor if it has a map entry. 2379 PredPad = SuccPad; 2380 auto TermI = SiblingFuncletInfo.find(PredPad); 2381 if (TermI == SiblingFuncletInfo.end()) 2382 break; 2383 Terminator = TermI->second; 2384 Active.insert(PredPad); 2385 } while (true); 2386 // Each node only has one successor, so we've walked all the active 2387 // nodes' successors. 2388 Active.clear(); 2389 } 2390 } 2391 2392 // visitFunction - Verify that a function is ok. 2393 // 2394 void Verifier::visitFunction(const Function &F) { 2395 visitGlobalValue(F); 2396 2397 // Check function arguments. 2398 FunctionType *FT = F.getFunctionType(); 2399 unsigned NumArgs = F.arg_size(); 2400 2401 Assert(&Context == &F.getContext(), 2402 "Function context does not match Module context!", &F); 2403 2404 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 2405 Assert(FT->getNumParams() == NumArgs, 2406 "# formal arguments must match # of arguments for function type!", &F, 2407 FT); 2408 Assert(F.getReturnType()->isFirstClassType() || 2409 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 2410 "Functions cannot return aggregate values!", &F); 2411 2412 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 2413 "Invalid struct return type!", &F); 2414 2415 AttributeList Attrs = F.getAttributes(); 2416 2417 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 2418 "Attribute after last parameter!", &F); 2419 2420 bool isLLVMdotName = F.getName().size() >= 5 && 2421 F.getName().substr(0, 5) == "llvm."; 2422 2423 // Check function attributes. 2424 verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName); 2425 2426 // On function declarations/definitions, we do not support the builtin 2427 // attribute. We do not check this in VerifyFunctionAttrs since that is 2428 // checking for Attributes that can/can not ever be on functions. 2429 Assert(!Attrs.hasFnAttribute(Attribute::Builtin), 2430 "Attribute 'builtin' can only be applied to a callsite.", &F); 2431 2432 // Check that this function meets the restrictions on this calling convention. 2433 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 2434 // restrictions can be lifted. 2435 switch (F.getCallingConv()) { 2436 default: 2437 case CallingConv::C: 2438 break; 2439 case CallingConv::X86_INTR: { 2440 Assert(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute::ByVal), 2441 "Calling convention parameter requires byval", &F); 2442 break; 2443 } 2444 case CallingConv::AMDGPU_KERNEL: 2445 case CallingConv::SPIR_KERNEL: 2446 Assert(F.getReturnType()->isVoidTy(), 2447 "Calling convention requires void return type", &F); 2448 LLVM_FALLTHROUGH; 2449 case CallingConv::AMDGPU_VS: 2450 case CallingConv::AMDGPU_HS: 2451 case CallingConv::AMDGPU_GS: 2452 case CallingConv::AMDGPU_PS: 2453 case CallingConv::AMDGPU_CS: 2454 Assert(!F.hasStructRetAttr(), 2455 "Calling convention does not allow sret", &F); 2456 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) { 2457 const unsigned StackAS = DL.getAllocaAddrSpace(); 2458 unsigned i = 0; 2459 for (const Argument &Arg : F.args()) { 2460 Assert(!Attrs.hasParamAttribute(i, Attribute::ByVal), 2461 "Calling convention disallows byval", &F); 2462 Assert(!Attrs.hasParamAttribute(i, Attribute::Preallocated), 2463 "Calling convention disallows preallocated", &F); 2464 Assert(!Attrs.hasParamAttribute(i, Attribute::InAlloca), 2465 "Calling convention disallows inalloca", &F); 2466 2467 if (Attrs.hasParamAttribute(i, Attribute::ByRef)) { 2468 // FIXME: Should also disallow LDS and GDS, but we don't have the enum 2469 // value here. 2470 Assert(Arg.getType()->getPointerAddressSpace() != StackAS, 2471 "Calling convention disallows stack byref", &F); 2472 } 2473 2474 ++i; 2475 } 2476 } 2477 2478 LLVM_FALLTHROUGH; 2479 case CallingConv::Fast: 2480 case CallingConv::Cold: 2481 case CallingConv::Intel_OCL_BI: 2482 case CallingConv::PTX_Kernel: 2483 case CallingConv::PTX_Device: 2484 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 2485 "perfect forwarding!", 2486 &F); 2487 break; 2488 } 2489 2490 // Check that the argument values match the function type for this function... 2491 unsigned i = 0; 2492 for (const Argument &Arg : F.args()) { 2493 Assert(Arg.getType() == FT->getParamType(i), 2494 "Argument value does not match function argument type!", &Arg, 2495 FT->getParamType(i)); 2496 Assert(Arg.getType()->isFirstClassType(), 2497 "Function arguments must have first-class types!", &Arg); 2498 if (!isLLVMdotName) { 2499 Assert(!Arg.getType()->isMetadataTy(), 2500 "Function takes metadata but isn't an intrinsic", &Arg, &F); 2501 Assert(!Arg.getType()->isTokenTy(), 2502 "Function takes token but isn't an intrinsic", &Arg, &F); 2503 Assert(!Arg.getType()->isX86_AMXTy(), 2504 "Function takes x86_amx but isn't an intrinsic", &Arg, &F); 2505 } 2506 2507 // Check that swifterror argument is only used by loads and stores. 2508 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) { 2509 verifySwiftErrorValue(&Arg); 2510 } 2511 ++i; 2512 } 2513 2514 if (!isLLVMdotName) { 2515 Assert(!F.getReturnType()->isTokenTy(), 2516 "Function returns a token but isn't an intrinsic", &F); 2517 Assert(!F.getReturnType()->isX86_AMXTy(), 2518 "Function returns a x86_amx but isn't an intrinsic", &F); 2519 } 2520 2521 // Get the function metadata attachments. 2522 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2523 F.getAllMetadata(MDs); 2524 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 2525 verifyFunctionMetadata(MDs); 2526 2527 // Check validity of the personality function 2528 if (F.hasPersonalityFn()) { 2529 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 2530 if (Per) 2531 Assert(Per->getParent() == F.getParent(), 2532 "Referencing personality function in another module!", 2533 &F, F.getParent(), Per, Per->getParent()); 2534 } 2535 2536 if (F.isMaterializable()) { 2537 // Function has a body somewhere we can't see. 2538 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 2539 MDs.empty() ? nullptr : MDs.front().second); 2540 } else if (F.isDeclaration()) { 2541 for (const auto &I : MDs) { 2542 // This is used for call site debug information. 2543 AssertDI(I.first != LLVMContext::MD_dbg || 2544 !cast<DISubprogram>(I.second)->isDistinct(), 2545 "function declaration may only have a unique !dbg attachment", 2546 &F); 2547 Assert(I.first != LLVMContext::MD_prof, 2548 "function declaration may not have a !prof attachment", &F); 2549 2550 // Verify the metadata itself. 2551 visitMDNode(*I.second, AreDebugLocsAllowed::Yes); 2552 } 2553 Assert(!F.hasPersonalityFn(), 2554 "Function declaration shouldn't have a personality routine", &F); 2555 } else { 2556 // Verify that this function (which has a body) is not named "llvm.*". It 2557 // is not legal to define intrinsics. 2558 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 2559 2560 // Check the entry node 2561 const BasicBlock *Entry = &F.getEntryBlock(); 2562 Assert(pred_empty(Entry), 2563 "Entry block to function must not have predecessors!", Entry); 2564 2565 // The address of the entry block cannot be taken, unless it is dead. 2566 if (Entry->hasAddressTaken()) { 2567 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 2568 "blockaddress may not be used with the entry block!", Entry); 2569 } 2570 2571 unsigned NumDebugAttachments = 0, NumProfAttachments = 0; 2572 // Visit metadata attachments. 2573 for (const auto &I : MDs) { 2574 // Verify that the attachment is legal. 2575 auto AllowLocs = AreDebugLocsAllowed::No; 2576 switch (I.first) { 2577 default: 2578 break; 2579 case LLVMContext::MD_dbg: { 2580 ++NumDebugAttachments; 2581 AssertDI(NumDebugAttachments == 1, 2582 "function must have a single !dbg attachment", &F, I.second); 2583 AssertDI(isa<DISubprogram>(I.second), 2584 "function !dbg attachment must be a subprogram", &F, I.second); 2585 AssertDI(cast<DISubprogram>(I.second)->isDistinct(), 2586 "function definition may only have a distinct !dbg attachment", 2587 &F); 2588 2589 auto *SP = cast<DISubprogram>(I.second); 2590 const Function *&AttachedTo = DISubprogramAttachments[SP]; 2591 AssertDI(!AttachedTo || AttachedTo == &F, 2592 "DISubprogram attached to more than one function", SP, &F); 2593 AttachedTo = &F; 2594 AllowLocs = AreDebugLocsAllowed::Yes; 2595 break; 2596 } 2597 case LLVMContext::MD_prof: 2598 ++NumProfAttachments; 2599 Assert(NumProfAttachments == 1, 2600 "function must have a single !prof attachment", &F, I.second); 2601 break; 2602 } 2603 2604 // Verify the metadata itself. 2605 visitMDNode(*I.second, AllowLocs); 2606 } 2607 } 2608 2609 // If this function is actually an intrinsic, verify that it is only used in 2610 // direct call/invokes, never having its "address taken". 2611 // Only do this if the module is materialized, otherwise we don't have all the 2612 // uses. 2613 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2614 const User *U; 2615 if (F.hasAddressTaken(&U)) 2616 Assert(false, "Invalid user of intrinsic instruction!", U); 2617 } 2618 2619 // Check intrinsics' signatures. 2620 switch (F.getIntrinsicID()) { 2621 case Intrinsic::experimental_gc_get_pointer_base: { 2622 FunctionType *FT = F.getFunctionType(); 2623 Assert(FT->getNumParams() == 1, "wrong number of parameters", F); 2624 Assert(isa<PointerType>(F.getReturnType()), 2625 "gc.get.pointer.base must return a pointer", F); 2626 Assert(FT->getParamType(0) == F.getReturnType(), 2627 "gc.get.pointer.base operand and result must be of the same type", 2628 F); 2629 break; 2630 } 2631 case Intrinsic::experimental_gc_get_pointer_offset: { 2632 FunctionType *FT = F.getFunctionType(); 2633 Assert(FT->getNumParams() == 1, "wrong number of parameters", F); 2634 Assert(isa<PointerType>(FT->getParamType(0)), 2635 "gc.get.pointer.offset operand must be a pointer", F); 2636 Assert(F.getReturnType()->isIntegerTy(), 2637 "gc.get.pointer.offset must return integer", F); 2638 break; 2639 } 2640 } 2641 2642 auto *N = F.getSubprogram(); 2643 HasDebugInfo = (N != nullptr); 2644 if (!HasDebugInfo) 2645 return; 2646 2647 // Check that all !dbg attachments lead to back to N. 2648 // 2649 // FIXME: Check this incrementally while visiting !dbg attachments. 2650 // FIXME: Only check when N is the canonical subprogram for F. 2651 SmallPtrSet<const MDNode *, 32> Seen; 2652 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) { 2653 // Be careful about using DILocation here since we might be dealing with 2654 // broken code (this is the Verifier after all). 2655 const DILocation *DL = dyn_cast_or_null<DILocation>(Node); 2656 if (!DL) 2657 return; 2658 if (!Seen.insert(DL).second) 2659 return; 2660 2661 Metadata *Parent = DL->getRawScope(); 2662 AssertDI(Parent && isa<DILocalScope>(Parent), 2663 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, 2664 Parent); 2665 2666 DILocalScope *Scope = DL->getInlinedAtScope(); 2667 Assert(Scope, "Failed to find DILocalScope", DL); 2668 2669 if (!Seen.insert(Scope).second) 2670 return; 2671 2672 DISubprogram *SP = Scope->getSubprogram(); 2673 2674 // Scope and SP could be the same MDNode and we don't want to skip 2675 // validation in that case 2676 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2677 return; 2678 2679 AssertDI(SP->describes(&F), 2680 "!dbg attachment points at wrong subprogram for function", N, &F, 2681 &I, DL, Scope, SP); 2682 }; 2683 for (auto &BB : F) 2684 for (auto &I : BB) { 2685 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode()); 2686 // The llvm.loop annotations also contain two DILocations. 2687 if (auto MD = I.getMetadata(LLVMContext::MD_loop)) 2688 for (unsigned i = 1; i < MD->getNumOperands(); ++i) 2689 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i))); 2690 if (BrokenDebugInfo) 2691 return; 2692 } 2693 } 2694 2695 // verifyBasicBlock - Verify that a basic block is well formed... 2696 // 2697 void Verifier::visitBasicBlock(BasicBlock &BB) { 2698 InstsInThisBlock.clear(); 2699 2700 // Ensure that basic blocks have terminators! 2701 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2702 2703 // Check constraints that this basic block imposes on all of the PHI nodes in 2704 // it. 2705 if (isa<PHINode>(BB.front())) { 2706 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB)); 2707 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2708 llvm::sort(Preds); 2709 for (const PHINode &PN : BB.phis()) { 2710 Assert(PN.getNumIncomingValues() == Preds.size(), 2711 "PHINode should have one entry for each predecessor of its " 2712 "parent basic block!", 2713 &PN); 2714 2715 // Get and sort all incoming values in the PHI node... 2716 Values.clear(); 2717 Values.reserve(PN.getNumIncomingValues()); 2718 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 2719 Values.push_back( 2720 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i))); 2721 llvm::sort(Values); 2722 2723 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2724 // Check to make sure that if there is more than one entry for a 2725 // particular basic block in this PHI node, that the incoming values are 2726 // all identical. 2727 // 2728 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2729 Values[i].second == Values[i - 1].second, 2730 "PHI node has multiple entries for the same basic block with " 2731 "different incoming values!", 2732 &PN, Values[i].first, Values[i].second, Values[i - 1].second); 2733 2734 // Check to make sure that the predecessors and PHI node entries are 2735 // matched up. 2736 Assert(Values[i].first == Preds[i], 2737 "PHI node entries do not match predecessors!", &PN, 2738 Values[i].first, Preds[i]); 2739 } 2740 } 2741 } 2742 2743 // Check that all instructions have their parent pointers set up correctly. 2744 for (auto &I : BB) 2745 { 2746 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2747 } 2748 } 2749 2750 void Verifier::visitTerminator(Instruction &I) { 2751 // Ensure that terminators only exist at the end of the basic block. 2752 Assert(&I == I.getParent()->getTerminator(), 2753 "Terminator found in the middle of a basic block!", I.getParent()); 2754 visitInstruction(I); 2755 } 2756 2757 void Verifier::visitBranchInst(BranchInst &BI) { 2758 if (BI.isConditional()) { 2759 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2760 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2761 } 2762 visitTerminator(BI); 2763 } 2764 2765 void Verifier::visitReturnInst(ReturnInst &RI) { 2766 Function *F = RI.getParent()->getParent(); 2767 unsigned N = RI.getNumOperands(); 2768 if (F->getReturnType()->isVoidTy()) 2769 Assert(N == 0, 2770 "Found return instr that returns non-void in Function of void " 2771 "return type!", 2772 &RI, F->getReturnType()); 2773 else 2774 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2775 "Function return type does not match operand " 2776 "type of return inst!", 2777 &RI, F->getReturnType()); 2778 2779 // Check to make sure that the return value has necessary properties for 2780 // terminators... 2781 visitTerminator(RI); 2782 } 2783 2784 void Verifier::visitSwitchInst(SwitchInst &SI) { 2785 // Check to make sure that all of the constants in the switch instruction 2786 // have the same type as the switched-on value. 2787 Type *SwitchTy = SI.getCondition()->getType(); 2788 SmallPtrSet<ConstantInt*, 32> Constants; 2789 for (auto &Case : SI.cases()) { 2790 Assert(Case.getCaseValue()->getType() == SwitchTy, 2791 "Switch constants must all be same type as switch value!", &SI); 2792 Assert(Constants.insert(Case.getCaseValue()).second, 2793 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2794 } 2795 2796 visitTerminator(SI); 2797 } 2798 2799 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2800 Assert(BI.getAddress()->getType()->isPointerTy(), 2801 "Indirectbr operand must have pointer type!", &BI); 2802 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2803 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2804 "Indirectbr destinations must all have pointer type!", &BI); 2805 2806 visitTerminator(BI); 2807 } 2808 2809 void Verifier::visitCallBrInst(CallBrInst &CBI) { 2810 Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", 2811 &CBI); 2812 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand()); 2813 Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed"); 2814 for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i) 2815 Assert(CBI.getSuccessor(i)->getType()->isLabelTy(), 2816 "Callbr successors must all have pointer type!", &CBI); 2817 for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) { 2818 Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)), 2819 "Using an unescaped label as a callbr argument!", &CBI); 2820 if (isa<BasicBlock>(CBI.getOperand(i))) 2821 for (unsigned j = i + 1; j != e; ++j) 2822 Assert(CBI.getOperand(i) != CBI.getOperand(j), 2823 "Duplicate callbr destination!", &CBI); 2824 } 2825 { 2826 SmallPtrSet<BasicBlock *, 4> ArgBBs; 2827 for (Value *V : CBI.args()) 2828 if (auto *BA = dyn_cast<BlockAddress>(V)) 2829 ArgBBs.insert(BA->getBasicBlock()); 2830 for (BasicBlock *BB : CBI.getIndirectDests()) 2831 Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI); 2832 } 2833 2834 visitTerminator(CBI); 2835 } 2836 2837 void Verifier::visitSelectInst(SelectInst &SI) { 2838 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2839 SI.getOperand(2)), 2840 "Invalid operands for select instruction!", &SI); 2841 2842 Assert(SI.getTrueValue()->getType() == SI.getType(), 2843 "Select values must have same type as select instruction!", &SI); 2844 visitInstruction(SI); 2845 } 2846 2847 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2848 /// a pass, if any exist, it's an error. 2849 /// 2850 void Verifier::visitUserOp1(Instruction &I) { 2851 Assert(false, "User-defined operators should not live outside of a pass!", &I); 2852 } 2853 2854 void Verifier::visitTruncInst(TruncInst &I) { 2855 // Get the source and destination types 2856 Type *SrcTy = I.getOperand(0)->getType(); 2857 Type *DestTy = I.getType(); 2858 2859 // Get the size of the types in bits, we'll need this later 2860 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2861 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2862 2863 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2864 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2865 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2866 "trunc source and destination must both be a vector or neither", &I); 2867 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2868 2869 visitInstruction(I); 2870 } 2871 2872 void Verifier::visitZExtInst(ZExtInst &I) { 2873 // Get the source and destination types 2874 Type *SrcTy = I.getOperand(0)->getType(); 2875 Type *DestTy = I.getType(); 2876 2877 // Get the size of the types in bits, we'll need this later 2878 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2879 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2880 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2881 "zext source and destination must both be a vector or neither", &I); 2882 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2883 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2884 2885 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2886 2887 visitInstruction(I); 2888 } 2889 2890 void Verifier::visitSExtInst(SExtInst &I) { 2891 // Get the source and destination types 2892 Type *SrcTy = I.getOperand(0)->getType(); 2893 Type *DestTy = I.getType(); 2894 2895 // Get the size of the types in bits, we'll need this later 2896 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2897 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2898 2899 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2900 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2901 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2902 "sext source and destination must both be a vector or neither", &I); 2903 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2904 2905 visitInstruction(I); 2906 } 2907 2908 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2909 // Get the source and destination types 2910 Type *SrcTy = I.getOperand(0)->getType(); 2911 Type *DestTy = I.getType(); 2912 // Get the size of the types in bits, we'll need this later 2913 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2914 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2915 2916 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2917 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2918 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2919 "fptrunc source and destination must both be a vector or neither", &I); 2920 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2921 2922 visitInstruction(I); 2923 } 2924 2925 void Verifier::visitFPExtInst(FPExtInst &I) { 2926 // Get the source and destination types 2927 Type *SrcTy = I.getOperand(0)->getType(); 2928 Type *DestTy = I.getType(); 2929 2930 // Get the size of the types in bits, we'll need this later 2931 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2932 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2933 2934 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2935 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2936 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2937 "fpext source and destination must both be a vector or neither", &I); 2938 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2939 2940 visitInstruction(I); 2941 } 2942 2943 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2944 // Get the source and destination types 2945 Type *SrcTy = I.getOperand(0)->getType(); 2946 Type *DestTy = I.getType(); 2947 2948 bool SrcVec = SrcTy->isVectorTy(); 2949 bool DstVec = DestTy->isVectorTy(); 2950 2951 Assert(SrcVec == DstVec, 2952 "UIToFP source and dest must both be vector or scalar", &I); 2953 Assert(SrcTy->isIntOrIntVectorTy(), 2954 "UIToFP source must be integer or integer vector", &I); 2955 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2956 &I); 2957 2958 if (SrcVec && DstVec) 2959 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2960 cast<VectorType>(DestTy)->getElementCount(), 2961 "UIToFP source and dest vector length mismatch", &I); 2962 2963 visitInstruction(I); 2964 } 2965 2966 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2967 // Get the source and destination types 2968 Type *SrcTy = I.getOperand(0)->getType(); 2969 Type *DestTy = I.getType(); 2970 2971 bool SrcVec = SrcTy->isVectorTy(); 2972 bool DstVec = DestTy->isVectorTy(); 2973 2974 Assert(SrcVec == DstVec, 2975 "SIToFP source and dest must both be vector or scalar", &I); 2976 Assert(SrcTy->isIntOrIntVectorTy(), 2977 "SIToFP source must be integer or integer vector", &I); 2978 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2979 &I); 2980 2981 if (SrcVec && DstVec) 2982 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2983 cast<VectorType>(DestTy)->getElementCount(), 2984 "SIToFP source and dest vector length mismatch", &I); 2985 2986 visitInstruction(I); 2987 } 2988 2989 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2990 // Get the source and destination types 2991 Type *SrcTy = I.getOperand(0)->getType(); 2992 Type *DestTy = I.getType(); 2993 2994 bool SrcVec = SrcTy->isVectorTy(); 2995 bool DstVec = DestTy->isVectorTy(); 2996 2997 Assert(SrcVec == DstVec, 2998 "FPToUI source and dest must both be vector or scalar", &I); 2999 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 3000 &I); 3001 Assert(DestTy->isIntOrIntVectorTy(), 3002 "FPToUI result must be integer or integer vector", &I); 3003 3004 if (SrcVec && DstVec) 3005 Assert(cast<VectorType>(SrcTy)->getElementCount() == 3006 cast<VectorType>(DestTy)->getElementCount(), 3007 "FPToUI source and dest vector length mismatch", &I); 3008 3009 visitInstruction(I); 3010 } 3011 3012 void Verifier::visitFPToSIInst(FPToSIInst &I) { 3013 // Get the source and destination types 3014 Type *SrcTy = I.getOperand(0)->getType(); 3015 Type *DestTy = I.getType(); 3016 3017 bool SrcVec = SrcTy->isVectorTy(); 3018 bool DstVec = DestTy->isVectorTy(); 3019 3020 Assert(SrcVec == DstVec, 3021 "FPToSI source and dest must both be vector or scalar", &I); 3022 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 3023 &I); 3024 Assert(DestTy->isIntOrIntVectorTy(), 3025 "FPToSI result must be integer or integer vector", &I); 3026 3027 if (SrcVec && DstVec) 3028 Assert(cast<VectorType>(SrcTy)->getElementCount() == 3029 cast<VectorType>(DestTy)->getElementCount(), 3030 "FPToSI source and dest vector length mismatch", &I); 3031 3032 visitInstruction(I); 3033 } 3034 3035 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 3036 // Get the source and destination types 3037 Type *SrcTy = I.getOperand(0)->getType(); 3038 Type *DestTy = I.getType(); 3039 3040 Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I); 3041 3042 Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I); 3043 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 3044 &I); 3045 3046 if (SrcTy->isVectorTy()) { 3047 auto *VSrc = cast<VectorType>(SrcTy); 3048 auto *VDest = cast<VectorType>(DestTy); 3049 Assert(VSrc->getElementCount() == VDest->getElementCount(), 3050 "PtrToInt Vector width mismatch", &I); 3051 } 3052 3053 visitInstruction(I); 3054 } 3055 3056 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 3057 // Get the source and destination types 3058 Type *SrcTy = I.getOperand(0)->getType(); 3059 Type *DestTy = I.getType(); 3060 3061 Assert(SrcTy->isIntOrIntVectorTy(), 3062 "IntToPtr source must be an integral", &I); 3063 Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I); 3064 3065 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 3066 &I); 3067 if (SrcTy->isVectorTy()) { 3068 auto *VSrc = cast<VectorType>(SrcTy); 3069 auto *VDest = cast<VectorType>(DestTy); 3070 Assert(VSrc->getElementCount() == VDest->getElementCount(), 3071 "IntToPtr Vector width mismatch", &I); 3072 } 3073 visitInstruction(I); 3074 } 3075 3076 void Verifier::visitBitCastInst(BitCastInst &I) { 3077 Assert( 3078 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 3079 "Invalid bitcast", &I); 3080 visitInstruction(I); 3081 } 3082 3083 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 3084 Type *SrcTy = I.getOperand(0)->getType(); 3085 Type *DestTy = I.getType(); 3086 3087 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 3088 &I); 3089 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 3090 &I); 3091 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 3092 "AddrSpaceCast must be between different address spaces", &I); 3093 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy)) 3094 Assert(SrcVTy->getElementCount() == 3095 cast<VectorType>(DestTy)->getElementCount(), 3096 "AddrSpaceCast vector pointer number of elements mismatch", &I); 3097 visitInstruction(I); 3098 } 3099 3100 /// visitPHINode - Ensure that a PHI node is well formed. 3101 /// 3102 void Verifier::visitPHINode(PHINode &PN) { 3103 // Ensure that the PHI nodes are all grouped together at the top of the block. 3104 // This can be tested by checking whether the instruction before this is 3105 // either nonexistent (because this is begin()) or is a PHI node. If not, 3106 // then there is some other instruction before a PHI. 3107 Assert(&PN == &PN.getParent()->front() || 3108 isa<PHINode>(--BasicBlock::iterator(&PN)), 3109 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 3110 3111 // Check that a PHI doesn't yield a Token. 3112 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 3113 3114 // Check that all of the values of the PHI node have the same type as the 3115 // result, and that the incoming blocks are really basic blocks. 3116 for (Value *IncValue : PN.incoming_values()) { 3117 Assert(PN.getType() == IncValue->getType(), 3118 "PHI node operands are not the same type as the result!", &PN); 3119 } 3120 3121 // All other PHI node constraints are checked in the visitBasicBlock method. 3122 3123 visitInstruction(PN); 3124 } 3125 3126 void Verifier::visitCallBase(CallBase &Call) { 3127 Assert(Call.getCalledOperand()->getType()->isPointerTy(), 3128 "Called function must be a pointer!", Call); 3129 PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType()); 3130 3131 Assert(FPTy->getElementType()->isFunctionTy(), 3132 "Called function is not pointer to function type!", Call); 3133 3134 Assert(FPTy->getElementType() == Call.getFunctionType(), 3135 "Called function is not the same type as the call!", Call); 3136 3137 FunctionType *FTy = Call.getFunctionType(); 3138 3139 // Verify that the correct number of arguments are being passed 3140 if (FTy->isVarArg()) 3141 Assert(Call.arg_size() >= FTy->getNumParams(), 3142 "Called function requires more parameters than were provided!", 3143 Call); 3144 else 3145 Assert(Call.arg_size() == FTy->getNumParams(), 3146 "Incorrect number of arguments passed to called function!", Call); 3147 3148 // Verify that all arguments to the call match the function type. 3149 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3150 Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i), 3151 "Call parameter type does not match function signature!", 3152 Call.getArgOperand(i), FTy->getParamType(i), Call); 3153 3154 AttributeList Attrs = Call.getAttributes(); 3155 3156 Assert(verifyAttributeCount(Attrs, Call.arg_size()), 3157 "Attribute after last parameter!", Call); 3158 3159 bool IsIntrinsic = Call.getCalledFunction() && 3160 Call.getCalledFunction()->getName().startswith("llvm."); 3161 3162 Function *Callee = 3163 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts()); 3164 3165 if (Attrs.hasFnAttribute(Attribute::Speculatable)) { 3166 // Don't allow speculatable on call sites, unless the underlying function 3167 // declaration is also speculatable. 3168 Assert(Callee && Callee->isSpeculatable(), 3169 "speculatable attribute may not apply to call sites", Call); 3170 } 3171 3172 if (Attrs.hasFnAttribute(Attribute::Preallocated)) { 3173 Assert(Call.getCalledFunction()->getIntrinsicID() == 3174 Intrinsic::call_preallocated_arg, 3175 "preallocated as a call site attribute can only be on " 3176 "llvm.call.preallocated.arg"); 3177 } 3178 3179 // Verify call attributes. 3180 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic); 3181 3182 // Conservatively check the inalloca argument. 3183 // We have a bug if we can find that there is an underlying alloca without 3184 // inalloca. 3185 if (Call.hasInAllocaArgument()) { 3186 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1); 3187 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 3188 Assert(AI->isUsedWithInAlloca(), 3189 "inalloca argument for call has mismatched alloca", AI, Call); 3190 } 3191 3192 // For each argument of the callsite, if it has the swifterror argument, 3193 // make sure the underlying alloca/parameter it comes from has a swifterror as 3194 // well. 3195 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3196 if (Call.paramHasAttr(i, Attribute::SwiftError)) { 3197 Value *SwiftErrorArg = Call.getArgOperand(i); 3198 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) { 3199 Assert(AI->isSwiftError(), 3200 "swifterror argument for call has mismatched alloca", AI, Call); 3201 continue; 3202 } 3203 auto ArgI = dyn_cast<Argument>(SwiftErrorArg); 3204 Assert(ArgI, 3205 "swifterror argument should come from an alloca or parameter", 3206 SwiftErrorArg, Call); 3207 Assert(ArgI->hasSwiftErrorAttr(), 3208 "swifterror argument for call has mismatched parameter", ArgI, 3209 Call); 3210 } 3211 3212 if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) { 3213 // Don't allow immarg on call sites, unless the underlying declaration 3214 // also has the matching immarg. 3215 Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg), 3216 "immarg may not apply only to call sites", 3217 Call.getArgOperand(i), Call); 3218 } 3219 3220 if (Call.paramHasAttr(i, Attribute::ImmArg)) { 3221 Value *ArgVal = Call.getArgOperand(i); 3222 Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal), 3223 "immarg operand has non-immediate parameter", ArgVal, Call); 3224 } 3225 3226 if (Call.paramHasAttr(i, Attribute::Preallocated)) { 3227 Value *ArgVal = Call.getArgOperand(i); 3228 bool hasOB = 3229 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0; 3230 bool isMustTail = Call.isMustTailCall(); 3231 Assert(hasOB != isMustTail, 3232 "preallocated operand either requires a preallocated bundle or " 3233 "the call to be musttail (but not both)", 3234 ArgVal, Call); 3235 } 3236 } 3237 3238 if (FTy->isVarArg()) { 3239 // FIXME? is 'nest' even legal here? 3240 bool SawNest = false; 3241 bool SawReturned = false; 3242 3243 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) { 3244 if (Attrs.hasParamAttribute(Idx, Attribute::Nest)) 3245 SawNest = true; 3246 if (Attrs.hasParamAttribute(Idx, Attribute::Returned)) 3247 SawReturned = true; 3248 } 3249 3250 // Check attributes on the varargs part. 3251 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) { 3252 Type *Ty = Call.getArgOperand(Idx)->getType(); 3253 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx); 3254 verifyParameterAttrs(ArgAttrs, Ty, &Call); 3255 3256 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 3257 Assert(!SawNest, "More than one parameter has attribute nest!", Call); 3258 SawNest = true; 3259 } 3260 3261 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 3262 Assert(!SawReturned, "More than one parameter has attribute returned!", 3263 Call); 3264 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 3265 "Incompatible argument and return types for 'returned' " 3266 "attribute", 3267 Call); 3268 SawReturned = true; 3269 } 3270 3271 // Statepoint intrinsic is vararg but the wrapped function may be not. 3272 // Allow sret here and check the wrapped function in verifyStatepoint. 3273 if (!Call.getCalledFunction() || 3274 Call.getCalledFunction()->getIntrinsicID() != 3275 Intrinsic::experimental_gc_statepoint) 3276 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 3277 "Attribute 'sret' cannot be used for vararg call arguments!", 3278 Call); 3279 3280 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) 3281 Assert(Idx == Call.arg_size() - 1, 3282 "inalloca isn't on the last argument!", Call); 3283 } 3284 } 3285 3286 // Verify that there's no metadata unless it's a direct call to an intrinsic. 3287 if (!IsIntrinsic) { 3288 for (Type *ParamTy : FTy->params()) { 3289 Assert(!ParamTy->isMetadataTy(), 3290 "Function has metadata parameter but isn't an intrinsic", Call); 3291 Assert(!ParamTy->isTokenTy(), 3292 "Function has token parameter but isn't an intrinsic", Call); 3293 } 3294 } 3295 3296 // Verify that indirect calls don't return tokens. 3297 if (!Call.getCalledFunction()) { 3298 Assert(!FTy->getReturnType()->isTokenTy(), 3299 "Return type cannot be token for indirect call!"); 3300 Assert(!FTy->getReturnType()->isX86_AMXTy(), 3301 "Return type cannot be x86_amx for indirect call!"); 3302 } 3303 3304 if (Function *F = Call.getCalledFunction()) 3305 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 3306 visitIntrinsicCall(ID, Call); 3307 3308 // Verify that a callsite has at most one "deopt", at most one "funclet", at 3309 // most one "gc-transition", at most one "cfguardtarget", 3310 // and at most one "preallocated" operand bundle. 3311 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 3312 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false, 3313 FoundPreallocatedBundle = false, FoundGCLiveBundle = false, 3314 FoundAttachedCallBundle = false; 3315 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) { 3316 OperandBundleUse BU = Call.getOperandBundleAt(i); 3317 uint32_t Tag = BU.getTagID(); 3318 if (Tag == LLVMContext::OB_deopt) { 3319 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call); 3320 FoundDeoptBundle = true; 3321 } else if (Tag == LLVMContext::OB_gc_transition) { 3322 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 3323 Call); 3324 FoundGCTransitionBundle = true; 3325 } else if (Tag == LLVMContext::OB_funclet) { 3326 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call); 3327 FoundFuncletBundle = true; 3328 Assert(BU.Inputs.size() == 1, 3329 "Expected exactly one funclet bundle operand", Call); 3330 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 3331 "Funclet bundle operands should correspond to a FuncletPadInst", 3332 Call); 3333 } else if (Tag == LLVMContext::OB_cfguardtarget) { 3334 Assert(!FoundCFGuardTargetBundle, 3335 "Multiple CFGuardTarget operand bundles", Call); 3336 FoundCFGuardTargetBundle = true; 3337 Assert(BU.Inputs.size() == 1, 3338 "Expected exactly one cfguardtarget bundle operand", Call); 3339 } else if (Tag == LLVMContext::OB_preallocated) { 3340 Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles", 3341 Call); 3342 FoundPreallocatedBundle = true; 3343 Assert(BU.Inputs.size() == 1, 3344 "Expected exactly one preallocated bundle operand", Call); 3345 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front()); 3346 Assert(Input && 3347 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup, 3348 "\"preallocated\" argument must be a token from " 3349 "llvm.call.preallocated.setup", 3350 Call); 3351 } else if (Tag == LLVMContext::OB_gc_live) { 3352 Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles", 3353 Call); 3354 FoundGCLiveBundle = true; 3355 } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) { 3356 Assert(!FoundAttachedCallBundle, 3357 "Multiple \"clang.arc.attachedcall\" operand bundles", Call); 3358 FoundAttachedCallBundle = true; 3359 } 3360 } 3361 3362 if (FoundAttachedCallBundle) 3363 Assert(FTy->getReturnType()->isPointerTy(), 3364 "a call with operand bundle \"clang.arc.attachedcall\" must call a " 3365 "function returning a pointer", 3366 Call); 3367 3368 // Verify that each inlinable callsite of a debug-info-bearing function in a 3369 // debug-info-bearing function has a debug location attached to it. Failure to 3370 // do so causes assertion failures when the inliner sets up inline scope info. 3371 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() && 3372 Call.getCalledFunction()->getSubprogram()) 3373 AssertDI(Call.getDebugLoc(), 3374 "inlinable function call in a function with " 3375 "debug info must have a !dbg location", 3376 Call); 3377 3378 visitInstruction(Call); 3379 } 3380 3381 void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs, 3382 StringRef Context) { 3383 Assert(!Attrs.contains(Attribute::InAlloca), 3384 Twine("inalloca attribute not allowed in ") + Context); 3385 Assert(!Attrs.contains(Attribute::InReg), 3386 Twine("inreg attribute not allowed in ") + Context); 3387 Assert(!Attrs.contains(Attribute::SwiftError), 3388 Twine("swifterror attribute not allowed in ") + Context); 3389 Assert(!Attrs.contains(Attribute::Preallocated), 3390 Twine("preallocated attribute not allowed in ") + Context); 3391 Assert(!Attrs.contains(Attribute::ByRef), 3392 Twine("byref attribute not allowed in ") + Context); 3393 } 3394 3395 /// Two types are "congruent" if they are identical, or if they are both pointer 3396 /// types with different pointee types and the same address space. 3397 static bool isTypeCongruent(Type *L, Type *R) { 3398 if (L == R) 3399 return true; 3400 PointerType *PL = dyn_cast<PointerType>(L); 3401 PointerType *PR = dyn_cast<PointerType>(R); 3402 if (!PL || !PR) 3403 return false; 3404 return PL->getAddressSpace() == PR->getAddressSpace(); 3405 } 3406 3407 static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) { 3408 static const Attribute::AttrKind ABIAttrs[] = { 3409 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 3410 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf, 3411 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated, 3412 Attribute::ByRef}; 3413 AttrBuilder Copy; 3414 for (auto AK : ABIAttrs) { 3415 if (Attrs.hasParamAttribute(I, AK)) 3416 Copy.addAttribute(AK); 3417 } 3418 3419 // `align` is ABI-affecting only in combination with `byval` or `byref`. 3420 if (Attrs.hasParamAttribute(I, Attribute::Alignment) && 3421 (Attrs.hasParamAttribute(I, Attribute::ByVal) || 3422 Attrs.hasParamAttribute(I, Attribute::ByRef))) 3423 Copy.addAlignmentAttr(Attrs.getParamAlignment(I)); 3424 return Copy; 3425 } 3426 3427 void Verifier::verifyMustTailCall(CallInst &CI) { 3428 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 3429 3430 Function *F = CI.getParent()->getParent(); 3431 FunctionType *CallerTy = F->getFunctionType(); 3432 FunctionType *CalleeTy = CI.getFunctionType(); 3433 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 3434 "cannot guarantee tail call due to mismatched varargs", &CI); 3435 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 3436 "cannot guarantee tail call due to mismatched return types", &CI); 3437 3438 // - The calling conventions of the caller and callee must match. 3439 Assert(F->getCallingConv() == CI.getCallingConv(), 3440 "cannot guarantee tail call due to mismatched calling conv", &CI); 3441 3442 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 3443 // or a pointer bitcast followed by a ret instruction. 3444 // - The ret instruction must return the (possibly bitcasted) value 3445 // produced by the call or void. 3446 Value *RetVal = &CI; 3447 Instruction *Next = CI.getNextNode(); 3448 3449 // Handle the optional bitcast. 3450 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 3451 Assert(BI->getOperand(0) == RetVal, 3452 "bitcast following musttail call must use the call", BI); 3453 RetVal = BI; 3454 Next = BI->getNextNode(); 3455 } 3456 3457 // Check the return. 3458 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 3459 Assert(Ret, "musttail call must precede a ret with an optional bitcast", 3460 &CI); 3461 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal || 3462 isa<UndefValue>(Ret->getReturnValue()), 3463 "musttail call result must be returned", Ret); 3464 3465 AttributeList CallerAttrs = F->getAttributes(); 3466 AttributeList CalleeAttrs = CI.getAttributes(); 3467 if (CI.getCallingConv() == CallingConv::SwiftTail || 3468 CI.getCallingConv() == CallingConv::Tail) { 3469 StringRef CCName = 3470 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc"; 3471 3472 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes 3473 // are allowed in swifttailcc call 3474 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3475 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs); 3476 SmallString<32> Context{CCName, StringRef(" musttail caller")}; 3477 verifyTailCCMustTailAttrs(ABIAttrs, Context); 3478 } 3479 for (int I = 0, E = CalleeTy->getNumParams(); I != E; ++I) { 3480 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 3481 SmallString<32> Context{CCName, StringRef(" musttail callee")}; 3482 verifyTailCCMustTailAttrs(ABIAttrs, Context); 3483 } 3484 // - Varargs functions are not allowed 3485 Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName + 3486 " tail call for varargs function"); 3487 return; 3488 } 3489 3490 // - The caller and callee prototypes must match. Pointer types of 3491 // parameters or return types may differ in pointee type, but not 3492 // address space. 3493 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) { 3494 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 3495 "cannot guarantee tail call due to mismatched parameter counts", 3496 &CI); 3497 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3498 Assert( 3499 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 3500 "cannot guarantee tail call due to mismatched parameter types", &CI); 3501 } 3502 } 3503 3504 // - All ABI-impacting function attributes, such as sret, byval, inreg, 3505 // returned, preallocated, and inalloca, must match. 3506 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3507 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 3508 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 3509 Assert(CallerABIAttrs == CalleeABIAttrs, 3510 "cannot guarantee tail call due to mismatched ABI impacting " 3511 "function attributes", 3512 &CI, CI.getOperand(I)); 3513 } 3514 } 3515 3516 void Verifier::visitCallInst(CallInst &CI) { 3517 visitCallBase(CI); 3518 3519 if (CI.isMustTailCall()) 3520 verifyMustTailCall(CI); 3521 } 3522 3523 void Verifier::visitInvokeInst(InvokeInst &II) { 3524 visitCallBase(II); 3525 3526 // Verify that the first non-PHI instruction of the unwind destination is an 3527 // exception handling instruction. 3528 Assert( 3529 II.getUnwindDest()->isEHPad(), 3530 "The unwind destination does not have an exception handling instruction!", 3531 &II); 3532 3533 visitTerminator(II); 3534 } 3535 3536 /// visitUnaryOperator - Check the argument to the unary operator. 3537 /// 3538 void Verifier::visitUnaryOperator(UnaryOperator &U) { 3539 Assert(U.getType() == U.getOperand(0)->getType(), 3540 "Unary operators must have same type for" 3541 "operands and result!", 3542 &U); 3543 3544 switch (U.getOpcode()) { 3545 // Check that floating-point arithmetic operators are only used with 3546 // floating-point operands. 3547 case Instruction::FNeg: 3548 Assert(U.getType()->isFPOrFPVectorTy(), 3549 "FNeg operator only works with float types!", &U); 3550 break; 3551 default: 3552 llvm_unreachable("Unknown UnaryOperator opcode!"); 3553 } 3554 3555 visitInstruction(U); 3556 } 3557 3558 /// visitBinaryOperator - Check that both arguments to the binary operator are 3559 /// of the same type! 3560 /// 3561 void Verifier::visitBinaryOperator(BinaryOperator &B) { 3562 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 3563 "Both operands to a binary operator are not of the same type!", &B); 3564 3565 switch (B.getOpcode()) { 3566 // Check that integer arithmetic operators are only used with 3567 // integral operands. 3568 case Instruction::Add: 3569 case Instruction::Sub: 3570 case Instruction::Mul: 3571 case Instruction::SDiv: 3572 case Instruction::UDiv: 3573 case Instruction::SRem: 3574 case Instruction::URem: 3575 Assert(B.getType()->isIntOrIntVectorTy(), 3576 "Integer arithmetic operators only work with integral types!", &B); 3577 Assert(B.getType() == B.getOperand(0)->getType(), 3578 "Integer arithmetic operators must have same type " 3579 "for operands and result!", 3580 &B); 3581 break; 3582 // Check that floating-point arithmetic operators are only used with 3583 // floating-point operands. 3584 case Instruction::FAdd: 3585 case Instruction::FSub: 3586 case Instruction::FMul: 3587 case Instruction::FDiv: 3588 case Instruction::FRem: 3589 Assert(B.getType()->isFPOrFPVectorTy(), 3590 "Floating-point arithmetic operators only work with " 3591 "floating-point types!", 3592 &B); 3593 Assert(B.getType() == B.getOperand(0)->getType(), 3594 "Floating-point arithmetic operators must have same type " 3595 "for operands and result!", 3596 &B); 3597 break; 3598 // Check that logical operators are only used with integral operands. 3599 case Instruction::And: 3600 case Instruction::Or: 3601 case Instruction::Xor: 3602 Assert(B.getType()->isIntOrIntVectorTy(), 3603 "Logical operators only work with integral types!", &B); 3604 Assert(B.getType() == B.getOperand(0)->getType(), 3605 "Logical operators must have same type for operands and result!", 3606 &B); 3607 break; 3608 case Instruction::Shl: 3609 case Instruction::LShr: 3610 case Instruction::AShr: 3611 Assert(B.getType()->isIntOrIntVectorTy(), 3612 "Shifts only work with integral types!", &B); 3613 Assert(B.getType() == B.getOperand(0)->getType(), 3614 "Shift return type must be same as operands!", &B); 3615 break; 3616 default: 3617 llvm_unreachable("Unknown BinaryOperator opcode!"); 3618 } 3619 3620 visitInstruction(B); 3621 } 3622 3623 void Verifier::visitICmpInst(ICmpInst &IC) { 3624 // Check that the operands are the same type 3625 Type *Op0Ty = IC.getOperand(0)->getType(); 3626 Type *Op1Ty = IC.getOperand(1)->getType(); 3627 Assert(Op0Ty == Op1Ty, 3628 "Both operands to ICmp instruction are not of the same type!", &IC); 3629 // Check that the operands are the right type 3630 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(), 3631 "Invalid operand types for ICmp instruction", &IC); 3632 // Check that the predicate is valid. 3633 Assert(IC.isIntPredicate(), 3634 "Invalid predicate in ICmp instruction!", &IC); 3635 3636 visitInstruction(IC); 3637 } 3638 3639 void Verifier::visitFCmpInst(FCmpInst &FC) { 3640 // Check that the operands are the same type 3641 Type *Op0Ty = FC.getOperand(0)->getType(); 3642 Type *Op1Ty = FC.getOperand(1)->getType(); 3643 Assert(Op0Ty == Op1Ty, 3644 "Both operands to FCmp instruction are not of the same type!", &FC); 3645 // Check that the operands are the right type 3646 Assert(Op0Ty->isFPOrFPVectorTy(), 3647 "Invalid operand types for FCmp instruction", &FC); 3648 // Check that the predicate is valid. 3649 Assert(FC.isFPPredicate(), 3650 "Invalid predicate in FCmp instruction!", &FC); 3651 3652 visitInstruction(FC); 3653 } 3654 3655 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 3656 Assert( 3657 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 3658 "Invalid extractelement operands!", &EI); 3659 visitInstruction(EI); 3660 } 3661 3662 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 3663 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 3664 IE.getOperand(2)), 3665 "Invalid insertelement operands!", &IE); 3666 visitInstruction(IE); 3667 } 3668 3669 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 3670 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 3671 SV.getShuffleMask()), 3672 "Invalid shufflevector operands!", &SV); 3673 visitInstruction(SV); 3674 } 3675 3676 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 3677 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 3678 3679 Assert(isa<PointerType>(TargetTy), 3680 "GEP base pointer is not a vector or a vector of pointers", &GEP); 3681 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 3682 3683 SmallVector<Value *, 16> Idxs(GEP.indices()); 3684 Assert(all_of( 3685 Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }), 3686 "GEP indexes must be integers", &GEP); 3687 Type *ElTy = 3688 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 3689 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 3690 3691 Assert(GEP.getType()->isPtrOrPtrVectorTy() && 3692 GEP.getResultElementType() == ElTy, 3693 "GEP is not of right type for indices!", &GEP, ElTy); 3694 3695 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) { 3696 // Additional checks for vector GEPs. 3697 ElementCount GEPWidth = GEPVTy->getElementCount(); 3698 if (GEP.getPointerOperandType()->isVectorTy()) 3699 Assert( 3700 GEPWidth == 3701 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(), 3702 "Vector GEP result width doesn't match operand's", &GEP); 3703 for (Value *Idx : Idxs) { 3704 Type *IndexTy = Idx->getType(); 3705 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) { 3706 ElementCount IndexWidth = IndexVTy->getElementCount(); 3707 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 3708 } 3709 Assert(IndexTy->isIntOrIntVectorTy(), 3710 "All GEP indices should be of integer type"); 3711 } 3712 } 3713 3714 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) { 3715 Assert(GEP.getAddressSpace() == PTy->getAddressSpace(), 3716 "GEP address space doesn't match type", &GEP); 3717 } 3718 3719 visitInstruction(GEP); 3720 } 3721 3722 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 3723 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 3724 } 3725 3726 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) { 3727 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) && 3728 "precondition violation"); 3729 3730 unsigned NumOperands = Range->getNumOperands(); 3731 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 3732 unsigned NumRanges = NumOperands / 2; 3733 Assert(NumRanges >= 1, "It should have at least one range!", Range); 3734 3735 ConstantRange LastRange(1, true); // Dummy initial value 3736 for (unsigned i = 0; i < NumRanges; ++i) { 3737 ConstantInt *Low = 3738 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 3739 Assert(Low, "The lower limit must be an integer!", Low); 3740 ConstantInt *High = 3741 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 3742 Assert(High, "The upper limit must be an integer!", High); 3743 Assert(High->getType() == Low->getType() && High->getType() == Ty, 3744 "Range types must match instruction type!", &I); 3745 3746 APInt HighV = High->getValue(); 3747 APInt LowV = Low->getValue(); 3748 ConstantRange CurRange(LowV, HighV); 3749 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 3750 "Range must not be empty!", Range); 3751 if (i != 0) { 3752 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 3753 "Intervals are overlapping", Range); 3754 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 3755 Range); 3756 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 3757 Range); 3758 } 3759 LastRange = ConstantRange(LowV, HighV); 3760 } 3761 if (NumRanges > 2) { 3762 APInt FirstLow = 3763 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 3764 APInt FirstHigh = 3765 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 3766 ConstantRange FirstRange(FirstLow, FirstHigh); 3767 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 3768 "Intervals are overlapping", Range); 3769 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 3770 Range); 3771 } 3772 } 3773 3774 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) { 3775 unsigned Size = DL.getTypeSizeInBits(Ty); 3776 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 3777 Assert(!(Size & (Size - 1)), 3778 "atomic memory access' operand must have a power-of-two size", Ty, I); 3779 } 3780 3781 void Verifier::visitLoadInst(LoadInst &LI) { 3782 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 3783 Assert(PTy, "Load operand must be a pointer.", &LI); 3784 Type *ElTy = LI.getType(); 3785 Assert(LI.getAlignment() <= Value::MaximumAlignment, 3786 "huge alignment values are unsupported", &LI); 3787 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 3788 if (LI.isAtomic()) { 3789 Assert(LI.getOrdering() != AtomicOrdering::Release && 3790 LI.getOrdering() != AtomicOrdering::AcquireRelease, 3791 "Load cannot have Release ordering", &LI); 3792 Assert(LI.getAlignment() != 0, 3793 "Atomic load must specify explicit alignment", &LI); 3794 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3795 "atomic load operand must have integer, pointer, or floating point " 3796 "type!", 3797 ElTy, &LI); 3798 checkAtomicMemAccessSize(ElTy, &LI); 3799 } else { 3800 Assert(LI.getSyncScopeID() == SyncScope::System, 3801 "Non-atomic load cannot have SynchronizationScope specified", &LI); 3802 } 3803 3804 visitInstruction(LI); 3805 } 3806 3807 void Verifier::visitStoreInst(StoreInst &SI) { 3808 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 3809 Assert(PTy, "Store operand must be a pointer.", &SI); 3810 Type *ElTy = SI.getOperand(0)->getType(); 3811 Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy), 3812 "Stored value type does not match pointer operand type!", &SI, ElTy); 3813 Assert(SI.getAlignment() <= Value::MaximumAlignment, 3814 "huge alignment values are unsupported", &SI); 3815 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 3816 if (SI.isAtomic()) { 3817 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 3818 SI.getOrdering() != AtomicOrdering::AcquireRelease, 3819 "Store cannot have Acquire ordering", &SI); 3820 Assert(SI.getAlignment() != 0, 3821 "Atomic store must specify explicit alignment", &SI); 3822 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3823 "atomic store operand must have integer, pointer, or floating point " 3824 "type!", 3825 ElTy, &SI); 3826 checkAtomicMemAccessSize(ElTy, &SI); 3827 } else { 3828 Assert(SI.getSyncScopeID() == SyncScope::System, 3829 "Non-atomic store cannot have SynchronizationScope specified", &SI); 3830 } 3831 visitInstruction(SI); 3832 } 3833 3834 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3835 void Verifier::verifySwiftErrorCall(CallBase &Call, 3836 const Value *SwiftErrorVal) { 3837 for (const auto &I : llvm::enumerate(Call.args())) { 3838 if (I.value() == SwiftErrorVal) { 3839 Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError), 3840 "swifterror value when used in a callsite should be marked " 3841 "with swifterror attribute", 3842 SwiftErrorVal, Call); 3843 } 3844 } 3845 } 3846 3847 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3848 // Check that swifterror value is only used by loads, stores, or as 3849 // a swifterror argument. 3850 for (const User *U : SwiftErrorVal->users()) { 3851 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3852 isa<InvokeInst>(U), 3853 "swifterror value can only be loaded and stored from, or " 3854 "as a swifterror argument!", 3855 SwiftErrorVal, U); 3856 // If it is used by a store, check it is the second operand. 3857 if (auto StoreI = dyn_cast<StoreInst>(U)) 3858 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3859 "swifterror value should be the second operand when used " 3860 "by stores", SwiftErrorVal, U); 3861 if (auto *Call = dyn_cast<CallBase>(U)) 3862 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal); 3863 } 3864 } 3865 3866 void Verifier::visitAllocaInst(AllocaInst &AI) { 3867 SmallPtrSet<Type*, 4> Visited; 3868 Assert(AI.getAllocatedType()->isSized(&Visited), 3869 "Cannot allocate unsized type", &AI); 3870 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3871 "Alloca array size must have integer type", &AI); 3872 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3873 "huge alignment values are unsupported", &AI); 3874 3875 if (AI.isSwiftError()) { 3876 verifySwiftErrorValue(&AI); 3877 } 3878 3879 visitInstruction(AI); 3880 } 3881 3882 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3883 Type *ElTy = CXI.getOperand(1)->getType(); 3884 Assert(ElTy->isIntOrPtrTy(), 3885 "cmpxchg operand must have integer or pointer type", ElTy, &CXI); 3886 checkAtomicMemAccessSize(ElTy, &CXI); 3887 visitInstruction(CXI); 3888 } 3889 3890 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3891 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3892 "atomicrmw instructions cannot be unordered.", &RMWI); 3893 auto Op = RMWI.getOperation(); 3894 Type *ElTy = RMWI.getOperand(1)->getType(); 3895 if (Op == AtomicRMWInst::Xchg) { 3896 Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " + 3897 AtomicRMWInst::getOperationName(Op) + 3898 " operand must have integer or floating point type!", 3899 &RMWI, ElTy); 3900 } else if (AtomicRMWInst::isFPOperation(Op)) { 3901 Assert(ElTy->isFloatingPointTy(), "atomicrmw " + 3902 AtomicRMWInst::getOperationName(Op) + 3903 " operand must have floating point type!", 3904 &RMWI, ElTy); 3905 } else { 3906 Assert(ElTy->isIntegerTy(), "atomicrmw " + 3907 AtomicRMWInst::getOperationName(Op) + 3908 " operand must have integer type!", 3909 &RMWI, ElTy); 3910 } 3911 checkAtomicMemAccessSize(ElTy, &RMWI); 3912 Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP, 3913 "Invalid binary operation!", &RMWI); 3914 visitInstruction(RMWI); 3915 } 3916 3917 void Verifier::visitFenceInst(FenceInst &FI) { 3918 const AtomicOrdering Ordering = FI.getOrdering(); 3919 Assert(Ordering == AtomicOrdering::Acquire || 3920 Ordering == AtomicOrdering::Release || 3921 Ordering == AtomicOrdering::AcquireRelease || 3922 Ordering == AtomicOrdering::SequentiallyConsistent, 3923 "fence instructions may only have acquire, release, acq_rel, or " 3924 "seq_cst ordering.", 3925 &FI); 3926 visitInstruction(FI); 3927 } 3928 3929 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3930 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3931 EVI.getIndices()) == EVI.getType(), 3932 "Invalid ExtractValueInst operands!", &EVI); 3933 3934 visitInstruction(EVI); 3935 } 3936 3937 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3938 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3939 IVI.getIndices()) == 3940 IVI.getOperand(1)->getType(), 3941 "Invalid InsertValueInst operands!", &IVI); 3942 3943 visitInstruction(IVI); 3944 } 3945 3946 static Value *getParentPad(Value *EHPad) { 3947 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3948 return FPI->getParentPad(); 3949 3950 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3951 } 3952 3953 void Verifier::visitEHPadPredecessors(Instruction &I) { 3954 assert(I.isEHPad()); 3955 3956 BasicBlock *BB = I.getParent(); 3957 Function *F = BB->getParent(); 3958 3959 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3960 3961 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3962 // The landingpad instruction defines its parent as a landing pad block. The 3963 // landing pad block may be branched to only by the unwind edge of an 3964 // invoke. 3965 for (BasicBlock *PredBB : predecessors(BB)) { 3966 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3967 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3968 "Block containing LandingPadInst must be jumped to " 3969 "only by the unwind edge of an invoke.", 3970 LPI); 3971 } 3972 return; 3973 } 3974 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3975 if (!pred_empty(BB)) 3976 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3977 "Block containg CatchPadInst must be jumped to " 3978 "only by its catchswitch.", 3979 CPI); 3980 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3981 "Catchswitch cannot unwind to one of its catchpads", 3982 CPI->getCatchSwitch(), CPI); 3983 return; 3984 } 3985 3986 // Verify that each pred has a legal terminator with a legal to/from EH 3987 // pad relationship. 3988 Instruction *ToPad = &I; 3989 Value *ToPadParent = getParentPad(ToPad); 3990 for (BasicBlock *PredBB : predecessors(BB)) { 3991 Instruction *TI = PredBB->getTerminator(); 3992 Value *FromPad; 3993 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3994 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3995 "EH pad must be jumped to via an unwind edge", ToPad, II); 3996 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3997 FromPad = Bundle->Inputs[0]; 3998 else 3999 FromPad = ConstantTokenNone::get(II->getContext()); 4000 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 4001 FromPad = CRI->getOperand(0); 4002 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 4003 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4004 FromPad = CSI; 4005 } else { 4006 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 4007 } 4008 4009 // The edge may exit from zero or more nested pads. 4010 SmallSet<Value *, 8> Seen; 4011 for (;; FromPad = getParentPad(FromPad)) { 4012 Assert(FromPad != ToPad, 4013 "EH pad cannot handle exceptions raised within it", FromPad, TI); 4014 if (FromPad == ToPadParent) { 4015 // This is a legal unwind edge. 4016 break; 4017 } 4018 Assert(!isa<ConstantTokenNone>(FromPad), 4019 "A single unwind edge may only enter one EH pad", TI); 4020 Assert(Seen.insert(FromPad).second, 4021 "EH pad jumps through a cycle of pads", FromPad); 4022 } 4023 } 4024 } 4025 4026 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 4027 // The landingpad instruction is ill-formed if it doesn't have any clauses and 4028 // isn't a cleanup. 4029 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 4030 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 4031 4032 visitEHPadPredecessors(LPI); 4033 4034 if (!LandingPadResultTy) 4035 LandingPadResultTy = LPI.getType(); 4036 else 4037 Assert(LandingPadResultTy == LPI.getType(), 4038 "The landingpad instruction should have a consistent result type " 4039 "inside a function.", 4040 &LPI); 4041 4042 Function *F = LPI.getParent()->getParent(); 4043 Assert(F->hasPersonalityFn(), 4044 "LandingPadInst needs to be in a function with a personality.", &LPI); 4045 4046 // The landingpad instruction must be the first non-PHI instruction in the 4047 // block. 4048 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 4049 "LandingPadInst not the first non-PHI instruction in the block.", 4050 &LPI); 4051 4052 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 4053 Constant *Clause = LPI.getClause(i); 4054 if (LPI.isCatch(i)) { 4055 Assert(isa<PointerType>(Clause->getType()), 4056 "Catch operand does not have pointer type!", &LPI); 4057 } else { 4058 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 4059 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 4060 "Filter operand is not an array of constants!", &LPI); 4061 } 4062 } 4063 4064 visitInstruction(LPI); 4065 } 4066 4067 void Verifier::visitResumeInst(ResumeInst &RI) { 4068 Assert(RI.getFunction()->hasPersonalityFn(), 4069 "ResumeInst needs to be in a function with a personality.", &RI); 4070 4071 if (!LandingPadResultTy) 4072 LandingPadResultTy = RI.getValue()->getType(); 4073 else 4074 Assert(LandingPadResultTy == RI.getValue()->getType(), 4075 "The resume instruction should have a consistent result type " 4076 "inside a function.", 4077 &RI); 4078 4079 visitTerminator(RI); 4080 } 4081 4082 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 4083 BasicBlock *BB = CPI.getParent(); 4084 4085 Function *F = BB->getParent(); 4086 Assert(F->hasPersonalityFn(), 4087 "CatchPadInst needs to be in a function with a personality.", &CPI); 4088 4089 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 4090 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 4091 CPI.getParentPad()); 4092 4093 // The catchpad instruction must be the first non-PHI instruction in the 4094 // block. 4095 Assert(BB->getFirstNonPHI() == &CPI, 4096 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 4097 4098 visitEHPadPredecessors(CPI); 4099 visitFuncletPadInst(CPI); 4100 } 4101 4102 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 4103 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 4104 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 4105 CatchReturn.getOperand(0)); 4106 4107 visitTerminator(CatchReturn); 4108 } 4109 4110 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 4111 BasicBlock *BB = CPI.getParent(); 4112 4113 Function *F = BB->getParent(); 4114 Assert(F->hasPersonalityFn(), 4115 "CleanupPadInst needs to be in a function with a personality.", &CPI); 4116 4117 // The cleanuppad instruction must be the first non-PHI instruction in the 4118 // block. 4119 Assert(BB->getFirstNonPHI() == &CPI, 4120 "CleanupPadInst not the first non-PHI instruction in the block.", 4121 &CPI); 4122 4123 auto *ParentPad = CPI.getParentPad(); 4124 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 4125 "CleanupPadInst has an invalid parent.", &CPI); 4126 4127 visitEHPadPredecessors(CPI); 4128 visitFuncletPadInst(CPI); 4129 } 4130 4131 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 4132 User *FirstUser = nullptr; 4133 Value *FirstUnwindPad = nullptr; 4134 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 4135 SmallSet<FuncletPadInst *, 8> Seen; 4136 4137 while (!Worklist.empty()) { 4138 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 4139 Assert(Seen.insert(CurrentPad).second, 4140 "FuncletPadInst must not be nested within itself", CurrentPad); 4141 Value *UnresolvedAncestorPad = nullptr; 4142 for (User *U : CurrentPad->users()) { 4143 BasicBlock *UnwindDest; 4144 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 4145 UnwindDest = CRI->getUnwindDest(); 4146 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 4147 // We allow catchswitch unwind to caller to nest 4148 // within an outer pad that unwinds somewhere else, 4149 // because catchswitch doesn't have a nounwind variant. 4150 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 4151 if (CSI->unwindsToCaller()) 4152 continue; 4153 UnwindDest = CSI->getUnwindDest(); 4154 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 4155 UnwindDest = II->getUnwindDest(); 4156 } else if (isa<CallInst>(U)) { 4157 // Calls which don't unwind may be found inside funclet 4158 // pads that unwind somewhere else. We don't *require* 4159 // such calls to be annotated nounwind. 4160 continue; 4161 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 4162 // The unwind dest for a cleanup can only be found by 4163 // recursive search. Add it to the worklist, and we'll 4164 // search for its first use that determines where it unwinds. 4165 Worklist.push_back(CPI); 4166 continue; 4167 } else { 4168 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 4169 continue; 4170 } 4171 4172 Value *UnwindPad; 4173 bool ExitsFPI; 4174 if (UnwindDest) { 4175 UnwindPad = UnwindDest->getFirstNonPHI(); 4176 if (!cast<Instruction>(UnwindPad)->isEHPad()) 4177 continue; 4178 Value *UnwindParent = getParentPad(UnwindPad); 4179 // Ignore unwind edges that don't exit CurrentPad. 4180 if (UnwindParent == CurrentPad) 4181 continue; 4182 // Determine whether the original funclet pad is exited, 4183 // and if we are scanning nested pads determine how many 4184 // of them are exited so we can stop searching their 4185 // children. 4186 Value *ExitedPad = CurrentPad; 4187 ExitsFPI = false; 4188 do { 4189 if (ExitedPad == &FPI) { 4190 ExitsFPI = true; 4191 // Now we can resolve any ancestors of CurrentPad up to 4192 // FPI, but not including FPI since we need to make sure 4193 // to check all direct users of FPI for consistency. 4194 UnresolvedAncestorPad = &FPI; 4195 break; 4196 } 4197 Value *ExitedParent = getParentPad(ExitedPad); 4198 if (ExitedParent == UnwindParent) { 4199 // ExitedPad is the ancestor-most pad which this unwind 4200 // edge exits, so we can resolve up to it, meaning that 4201 // ExitedParent is the first ancestor still unresolved. 4202 UnresolvedAncestorPad = ExitedParent; 4203 break; 4204 } 4205 ExitedPad = ExitedParent; 4206 } while (!isa<ConstantTokenNone>(ExitedPad)); 4207 } else { 4208 // Unwinding to caller exits all pads. 4209 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 4210 ExitsFPI = true; 4211 UnresolvedAncestorPad = &FPI; 4212 } 4213 4214 if (ExitsFPI) { 4215 // This unwind edge exits FPI. Make sure it agrees with other 4216 // such edges. 4217 if (FirstUser) { 4218 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 4219 "pad must have the same unwind " 4220 "dest", 4221 &FPI, U, FirstUser); 4222 } else { 4223 FirstUser = U; 4224 FirstUnwindPad = UnwindPad; 4225 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 4226 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 4227 getParentPad(UnwindPad) == getParentPad(&FPI)) 4228 SiblingFuncletInfo[&FPI] = cast<Instruction>(U); 4229 } 4230 } 4231 // Make sure we visit all uses of FPI, but for nested pads stop as 4232 // soon as we know where they unwind to. 4233 if (CurrentPad != &FPI) 4234 break; 4235 } 4236 if (UnresolvedAncestorPad) { 4237 if (CurrentPad == UnresolvedAncestorPad) { 4238 // When CurrentPad is FPI itself, we don't mark it as resolved even if 4239 // we've found an unwind edge that exits it, because we need to verify 4240 // all direct uses of FPI. 4241 assert(CurrentPad == &FPI); 4242 continue; 4243 } 4244 // Pop off the worklist any nested pads that we've found an unwind 4245 // destination for. The pads on the worklist are the uncles, 4246 // great-uncles, etc. of CurrentPad. We've found an unwind destination 4247 // for all ancestors of CurrentPad up to but not including 4248 // UnresolvedAncestorPad. 4249 Value *ResolvedPad = CurrentPad; 4250 while (!Worklist.empty()) { 4251 Value *UnclePad = Worklist.back(); 4252 Value *AncestorPad = getParentPad(UnclePad); 4253 // Walk ResolvedPad up the ancestor list until we either find the 4254 // uncle's parent or the last resolved ancestor. 4255 while (ResolvedPad != AncestorPad) { 4256 Value *ResolvedParent = getParentPad(ResolvedPad); 4257 if (ResolvedParent == UnresolvedAncestorPad) { 4258 break; 4259 } 4260 ResolvedPad = ResolvedParent; 4261 } 4262 // If the resolved ancestor search didn't find the uncle's parent, 4263 // then the uncle is not yet resolved. 4264 if (ResolvedPad != AncestorPad) 4265 break; 4266 // This uncle is resolved, so pop it from the worklist. 4267 Worklist.pop_back(); 4268 } 4269 } 4270 } 4271 4272 if (FirstUnwindPad) { 4273 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 4274 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 4275 Value *SwitchUnwindPad; 4276 if (SwitchUnwindDest) 4277 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 4278 else 4279 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 4280 Assert(SwitchUnwindPad == FirstUnwindPad, 4281 "Unwind edges out of a catch must have the same unwind dest as " 4282 "the parent catchswitch", 4283 &FPI, FirstUser, CatchSwitch); 4284 } 4285 } 4286 4287 visitInstruction(FPI); 4288 } 4289 4290 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 4291 BasicBlock *BB = CatchSwitch.getParent(); 4292 4293 Function *F = BB->getParent(); 4294 Assert(F->hasPersonalityFn(), 4295 "CatchSwitchInst needs to be in a function with a personality.", 4296 &CatchSwitch); 4297 4298 // The catchswitch instruction must be the first non-PHI instruction in the 4299 // block. 4300 Assert(BB->getFirstNonPHI() == &CatchSwitch, 4301 "CatchSwitchInst not the first non-PHI instruction in the block.", 4302 &CatchSwitch); 4303 4304 auto *ParentPad = CatchSwitch.getParentPad(); 4305 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 4306 "CatchSwitchInst has an invalid parent.", ParentPad); 4307 4308 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 4309 Instruction *I = UnwindDest->getFirstNonPHI(); 4310 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4311 "CatchSwitchInst must unwind to an EH block which is not a " 4312 "landingpad.", 4313 &CatchSwitch); 4314 4315 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 4316 if (getParentPad(I) == ParentPad) 4317 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 4318 } 4319 4320 Assert(CatchSwitch.getNumHandlers() != 0, 4321 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 4322 4323 for (BasicBlock *Handler : CatchSwitch.handlers()) { 4324 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 4325 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 4326 } 4327 4328 visitEHPadPredecessors(CatchSwitch); 4329 visitTerminator(CatchSwitch); 4330 } 4331 4332 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 4333 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 4334 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 4335 CRI.getOperand(0)); 4336 4337 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 4338 Instruction *I = UnwindDest->getFirstNonPHI(); 4339 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4340 "CleanupReturnInst must unwind to an EH block which is not a " 4341 "landingpad.", 4342 &CRI); 4343 } 4344 4345 visitTerminator(CRI); 4346 } 4347 4348 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 4349 Instruction *Op = cast<Instruction>(I.getOperand(i)); 4350 // If the we have an invalid invoke, don't try to compute the dominance. 4351 // We already reject it in the invoke specific checks and the dominance 4352 // computation doesn't handle multiple edges. 4353 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 4354 if (II->getNormalDest() == II->getUnwindDest()) 4355 return; 4356 } 4357 4358 // Quick check whether the def has already been encountered in the same block. 4359 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI 4360 // uses are defined to happen on the incoming edge, not at the instruction. 4361 // 4362 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 4363 // wrapping an SSA value, assert that we've already encountered it. See 4364 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 4365 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 4366 return; 4367 4368 const Use &U = I.getOperandUse(i); 4369 Assert(DT.dominates(Op, U), 4370 "Instruction does not dominate all uses!", Op, &I); 4371 } 4372 4373 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 4374 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 4375 "apply only to pointer types", &I); 4376 Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)), 4377 "dereferenceable, dereferenceable_or_null apply only to load" 4378 " and inttoptr instructions, use attributes for calls or invokes", &I); 4379 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 4380 "take one operand!", &I); 4381 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 4382 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 4383 "dereferenceable_or_null metadata value must be an i64!", &I); 4384 } 4385 4386 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) { 4387 Assert(MD->getNumOperands() >= 2, 4388 "!prof annotations should have no less than 2 operands", MD); 4389 4390 // Check first operand. 4391 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD); 4392 Assert(isa<MDString>(MD->getOperand(0)), 4393 "expected string with name of the !prof annotation", MD); 4394 MDString *MDS = cast<MDString>(MD->getOperand(0)); 4395 StringRef ProfName = MDS->getString(); 4396 4397 // Check consistency of !prof branch_weights metadata. 4398 if (ProfName.equals("branch_weights")) { 4399 if (isa<InvokeInst>(&I)) { 4400 Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3, 4401 "Wrong number of InvokeInst branch_weights operands", MD); 4402 } else { 4403 unsigned ExpectedNumOperands = 0; 4404 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 4405 ExpectedNumOperands = BI->getNumSuccessors(); 4406 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 4407 ExpectedNumOperands = SI->getNumSuccessors(); 4408 else if (isa<CallInst>(&I)) 4409 ExpectedNumOperands = 1; 4410 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 4411 ExpectedNumOperands = IBI->getNumDestinations(); 4412 else if (isa<SelectInst>(&I)) 4413 ExpectedNumOperands = 2; 4414 else 4415 CheckFailed("!prof branch_weights are not allowed for this instruction", 4416 MD); 4417 4418 Assert(MD->getNumOperands() == 1 + ExpectedNumOperands, 4419 "Wrong number of operands", MD); 4420 } 4421 for (unsigned i = 1; i < MD->getNumOperands(); ++i) { 4422 auto &MDO = MD->getOperand(i); 4423 Assert(MDO, "second operand should not be null", MD); 4424 Assert(mdconst::dyn_extract<ConstantInt>(MDO), 4425 "!prof brunch_weights operand is not a const int"); 4426 } 4427 } 4428 } 4429 4430 void Verifier::visitAnnotationMetadata(MDNode *Annotation) { 4431 Assert(isa<MDTuple>(Annotation), "annotation must be a tuple"); 4432 Assert(Annotation->getNumOperands() >= 1, 4433 "annotation must have at least one operand"); 4434 for (const MDOperand &Op : Annotation->operands()) 4435 Assert(isa<MDString>(Op.get()), "operands must be strings"); 4436 } 4437 4438 /// verifyInstruction - Verify that an instruction is well formed. 4439 /// 4440 void Verifier::visitInstruction(Instruction &I) { 4441 BasicBlock *BB = I.getParent(); 4442 Assert(BB, "Instruction not embedded in basic block!", &I); 4443 4444 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 4445 for (User *U : I.users()) { 4446 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 4447 "Only PHI nodes may reference their own value!", &I); 4448 } 4449 } 4450 4451 // Check that void typed values don't have names 4452 Assert(!I.getType()->isVoidTy() || !I.hasName(), 4453 "Instruction has a name, but provides a void value!", &I); 4454 4455 // Check that the return value of the instruction is either void or a legal 4456 // value type. 4457 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 4458 "Instruction returns a non-scalar type!", &I); 4459 4460 // Check that the instruction doesn't produce metadata. Calls are already 4461 // checked against the callee type. 4462 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 4463 "Invalid use of metadata!", &I); 4464 4465 // Check that all uses of the instruction, if they are instructions 4466 // themselves, actually have parent basic blocks. If the use is not an 4467 // instruction, it is an error! 4468 for (Use &U : I.uses()) { 4469 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 4470 Assert(Used->getParent() != nullptr, 4471 "Instruction referencing" 4472 " instruction not embedded in a basic block!", 4473 &I, Used); 4474 else { 4475 CheckFailed("Use of instruction is not an instruction!", U); 4476 return; 4477 } 4478 } 4479 4480 // Get a pointer to the call base of the instruction if it is some form of 4481 // call. 4482 const CallBase *CBI = dyn_cast<CallBase>(&I); 4483 4484 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 4485 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 4486 4487 // Check to make sure that only first-class-values are operands to 4488 // instructions. 4489 if (!I.getOperand(i)->getType()->isFirstClassType()) { 4490 Assert(false, "Instruction operands must be first-class values!", &I); 4491 } 4492 4493 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 4494 // Check to make sure that the "address of" an intrinsic function is never 4495 // taken. 4496 Assert(!F->isIntrinsic() || 4497 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)), 4498 "Cannot take the address of an intrinsic!", &I); 4499 Assert( 4500 !F->isIntrinsic() || isa<CallInst>(I) || 4501 F->getIntrinsicID() == Intrinsic::donothing || 4502 F->getIntrinsicID() == Intrinsic::seh_try_begin || 4503 F->getIntrinsicID() == Intrinsic::seh_try_end || 4504 F->getIntrinsicID() == Intrinsic::seh_scope_begin || 4505 F->getIntrinsicID() == Intrinsic::seh_scope_end || 4506 F->getIntrinsicID() == Intrinsic::coro_resume || 4507 F->getIntrinsicID() == Intrinsic::coro_destroy || 4508 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 4509 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 4510 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint || 4511 F->getIntrinsicID() == Intrinsic::wasm_rethrow, 4512 "Cannot invoke an intrinsic other than donothing, patchpoint, " 4513 "statepoint, coro_resume or coro_destroy", 4514 &I); 4515 Assert(F->getParent() == &M, "Referencing function in another module!", 4516 &I, &M, F, F->getParent()); 4517 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 4518 Assert(OpBB->getParent() == BB->getParent(), 4519 "Referring to a basic block in another function!", &I); 4520 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 4521 Assert(OpArg->getParent() == BB->getParent(), 4522 "Referring to an argument in another function!", &I); 4523 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 4524 Assert(GV->getParent() == &M, "Referencing global in another module!", &I, 4525 &M, GV, GV->getParent()); 4526 } else if (isa<Instruction>(I.getOperand(i))) { 4527 verifyDominatesUse(I, i); 4528 } else if (isa<InlineAsm>(I.getOperand(i))) { 4529 Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i), 4530 "Cannot take the address of an inline asm!", &I); 4531 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 4532 if (CE->getType()->isPtrOrPtrVectorTy()) { 4533 // If we have a ConstantExpr pointer, we need to see if it came from an 4534 // illegal bitcast. 4535 visitConstantExprsRecursively(CE); 4536 } 4537 } 4538 } 4539 4540 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 4541 Assert(I.getType()->isFPOrFPVectorTy(), 4542 "fpmath requires a floating point result!", &I); 4543 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 4544 if (ConstantFP *CFP0 = 4545 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 4546 const APFloat &Accuracy = CFP0->getValueAPF(); 4547 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(), 4548 "fpmath accuracy must have float type", &I); 4549 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 4550 "fpmath accuracy not a positive number!", &I); 4551 } else { 4552 Assert(false, "invalid fpmath accuracy!", &I); 4553 } 4554 } 4555 4556 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 4557 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 4558 "Ranges are only for loads, calls and invokes!", &I); 4559 visitRangeMetadata(I, Range, I.getType()); 4560 } 4561 4562 if (I.getMetadata(LLVMContext::MD_nonnull)) { 4563 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 4564 &I); 4565 Assert(isa<LoadInst>(I), 4566 "nonnull applies only to load instructions, use attributes" 4567 " for calls or invokes", 4568 &I); 4569 } 4570 4571 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 4572 visitDereferenceableMetadata(I, MD); 4573 4574 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 4575 visitDereferenceableMetadata(I, MD); 4576 4577 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) 4578 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA); 4579 4580 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 4581 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 4582 &I); 4583 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 4584 "use attributes for calls or invokes", &I); 4585 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 4586 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 4587 Assert(CI && CI->getType()->isIntegerTy(64), 4588 "align metadata value must be an i64!", &I); 4589 uint64_t Align = CI->getZExtValue(); 4590 Assert(isPowerOf2_64(Align), 4591 "align metadata value must be a power of 2!", &I); 4592 Assert(Align <= Value::MaximumAlignment, 4593 "alignment is larger that implementation defined limit", &I); 4594 } 4595 4596 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof)) 4597 visitProfMetadata(I, MD); 4598 4599 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation)) 4600 visitAnnotationMetadata(Annotation); 4601 4602 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 4603 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 4604 visitMDNode(*N, AreDebugLocsAllowed::Yes); 4605 } 4606 4607 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) { 4608 verifyFragmentExpression(*DII); 4609 verifyNotEntryValue(*DII); 4610 } 4611 4612 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 4613 I.getAllMetadata(MDs); 4614 for (auto Attachment : MDs) { 4615 unsigned Kind = Attachment.first; 4616 auto AllowLocs = 4617 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop) 4618 ? AreDebugLocsAllowed::Yes 4619 : AreDebugLocsAllowed::No; 4620 visitMDNode(*Attachment.second, AllowLocs); 4621 } 4622 4623 InstsInThisBlock.insert(&I); 4624 } 4625 4626 /// Allow intrinsics to be verified in different ways. 4627 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) { 4628 Function *IF = Call.getCalledFunction(); 4629 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 4630 IF); 4631 4632 // Verify that the intrinsic prototype lines up with what the .td files 4633 // describe. 4634 FunctionType *IFTy = IF->getFunctionType(); 4635 bool IsVarArg = IFTy->isVarArg(); 4636 4637 SmallVector<Intrinsic::IITDescriptor, 8> Table; 4638 getIntrinsicInfoTableEntries(ID, Table); 4639 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 4640 4641 // Walk the descriptors to extract overloaded types. 4642 SmallVector<Type *, 4> ArgTys; 4643 Intrinsic::MatchIntrinsicTypesResult Res = 4644 Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys); 4645 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet, 4646 "Intrinsic has incorrect return type!", IF); 4647 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg, 4648 "Intrinsic has incorrect argument type!", IF); 4649 4650 // Verify if the intrinsic call matches the vararg property. 4651 if (IsVarArg) 4652 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4653 "Intrinsic was not defined with variable arguments!", IF); 4654 else 4655 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4656 "Callsite was not defined with variable arguments!", IF); 4657 4658 // All descriptors should be absorbed by now. 4659 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 4660 4661 // Now that we have the intrinsic ID and the actual argument types (and we 4662 // know they are legal for the intrinsic!) get the intrinsic name through the 4663 // usual means. This allows us to verify the mangling of argument types into 4664 // the name. 4665 const std::string ExpectedName = 4666 Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy); 4667 Assert(ExpectedName == IF->getName(), 4668 "Intrinsic name not mangled correctly for type arguments! " 4669 "Should be: " + 4670 ExpectedName, 4671 IF); 4672 4673 // If the intrinsic takes MDNode arguments, verify that they are either global 4674 // or are local to *this* function. 4675 for (Value *V : Call.args()) { 4676 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 4677 visitMetadataAsValue(*MD, Call.getCaller()); 4678 if (auto *Const = dyn_cast<Constant>(V)) 4679 Assert(!Const->getType()->isX86_AMXTy(), 4680 "const x86_amx is not allowed in argument!"); 4681 } 4682 4683 switch (ID) { 4684 default: 4685 break; 4686 case Intrinsic::assume: { 4687 for (auto &Elem : Call.bundle_op_infos()) { 4688 Assert(Elem.Tag->getKey() == "ignore" || 4689 Attribute::isExistingAttribute(Elem.Tag->getKey()), 4690 "tags must be valid attribute names"); 4691 Attribute::AttrKind Kind = 4692 Attribute::getAttrKindFromName(Elem.Tag->getKey()); 4693 unsigned ArgCount = Elem.End - Elem.Begin; 4694 if (Kind == Attribute::Alignment) { 4695 Assert(ArgCount <= 3 && ArgCount >= 2, 4696 "alignment assumptions should have 2 or 3 arguments"); 4697 Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(), 4698 "first argument should be a pointer"); 4699 Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(), 4700 "second argument should be an integer"); 4701 if (ArgCount == 3) 4702 Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(), 4703 "third argument should be an integer if present"); 4704 return; 4705 } 4706 Assert(ArgCount <= 2, "to many arguments"); 4707 if (Kind == Attribute::None) 4708 break; 4709 if (Attribute::doesAttrKindHaveArgument(Kind)) { 4710 Assert(ArgCount == 2, "this attribute should have 2 arguments"); 4711 Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)), 4712 "the second argument should be a constant integral value"); 4713 } else if (isFuncOnlyAttr(Kind)) { 4714 Assert((ArgCount) == 0, "this attribute has no argument"); 4715 } else if (!isFuncOrArgAttr(Kind)) { 4716 Assert((ArgCount) == 1, "this attribute should have one argument"); 4717 } 4718 } 4719 break; 4720 } 4721 case Intrinsic::coro_id: { 4722 auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts(); 4723 if (isa<ConstantPointerNull>(InfoArg)) 4724 break; 4725 auto *GV = dyn_cast<GlobalVariable>(InfoArg); 4726 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(), 4727 "info argument of llvm.coro.id must refer to an initialized " 4728 "constant"); 4729 Constant *Init = GV->getInitializer(); 4730 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init), 4731 "info argument of llvm.coro.id must refer to either a struct or " 4732 "an array"); 4733 break; 4734 } 4735 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \ 4736 case Intrinsic::INTRINSIC: 4737 #include "llvm/IR/ConstrainedOps.def" 4738 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call)); 4739 break; 4740 case Intrinsic::dbg_declare: // llvm.dbg.declare 4741 Assert(isa<MetadataAsValue>(Call.getArgOperand(0)), 4742 "invalid llvm.dbg.declare intrinsic call 1", Call); 4743 visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call)); 4744 break; 4745 case Intrinsic::dbg_addr: // llvm.dbg.addr 4746 visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call)); 4747 break; 4748 case Intrinsic::dbg_value: // llvm.dbg.value 4749 visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call)); 4750 break; 4751 case Intrinsic::dbg_label: // llvm.dbg.label 4752 visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call)); 4753 break; 4754 case Intrinsic::memcpy: 4755 case Intrinsic::memcpy_inline: 4756 case Intrinsic::memmove: 4757 case Intrinsic::memset: { 4758 const auto *MI = cast<MemIntrinsic>(&Call); 4759 auto IsValidAlignment = [&](unsigned Alignment) -> bool { 4760 return Alignment == 0 || isPowerOf2_32(Alignment); 4761 }; 4762 Assert(IsValidAlignment(MI->getDestAlignment()), 4763 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2", 4764 Call); 4765 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) { 4766 Assert(IsValidAlignment(MTI->getSourceAlignment()), 4767 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2", 4768 Call); 4769 } 4770 4771 break; 4772 } 4773 case Intrinsic::memcpy_element_unordered_atomic: 4774 case Intrinsic::memmove_element_unordered_atomic: 4775 case Intrinsic::memset_element_unordered_atomic: { 4776 const auto *AMI = cast<AtomicMemIntrinsic>(&Call); 4777 4778 ConstantInt *ElementSizeCI = 4779 cast<ConstantInt>(AMI->getRawElementSizeInBytes()); 4780 const APInt &ElementSizeVal = ElementSizeCI->getValue(); 4781 Assert(ElementSizeVal.isPowerOf2(), 4782 "element size of the element-wise atomic memory intrinsic " 4783 "must be a power of 2", 4784 Call); 4785 4786 auto IsValidAlignment = [&](uint64_t Alignment) { 4787 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment); 4788 }; 4789 uint64_t DstAlignment = AMI->getDestAlignment(); 4790 Assert(IsValidAlignment(DstAlignment), 4791 "incorrect alignment of the destination argument", Call); 4792 if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) { 4793 uint64_t SrcAlignment = AMT->getSourceAlignment(); 4794 Assert(IsValidAlignment(SrcAlignment), 4795 "incorrect alignment of the source argument", Call); 4796 } 4797 break; 4798 } 4799 case Intrinsic::call_preallocated_setup: { 4800 auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 4801 Assert(NumArgs != nullptr, 4802 "llvm.call.preallocated.setup argument must be a constant"); 4803 bool FoundCall = false; 4804 for (User *U : Call.users()) { 4805 auto *UseCall = dyn_cast<CallBase>(U); 4806 Assert(UseCall != nullptr, 4807 "Uses of llvm.call.preallocated.setup must be calls"); 4808 const Function *Fn = UseCall->getCalledFunction(); 4809 if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) { 4810 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1)); 4811 Assert(AllocArgIndex != nullptr, 4812 "llvm.call.preallocated.alloc arg index must be a constant"); 4813 auto AllocArgIndexInt = AllocArgIndex->getValue(); 4814 Assert(AllocArgIndexInt.sge(0) && 4815 AllocArgIndexInt.slt(NumArgs->getValue()), 4816 "llvm.call.preallocated.alloc arg index must be between 0 and " 4817 "corresponding " 4818 "llvm.call.preallocated.setup's argument count"); 4819 } else if (Fn && Fn->getIntrinsicID() == 4820 Intrinsic::call_preallocated_teardown) { 4821 // nothing to do 4822 } else { 4823 Assert(!FoundCall, "Can have at most one call corresponding to a " 4824 "llvm.call.preallocated.setup"); 4825 FoundCall = true; 4826 size_t NumPreallocatedArgs = 0; 4827 for (unsigned i = 0; i < UseCall->getNumArgOperands(); i++) { 4828 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) { 4829 ++NumPreallocatedArgs; 4830 } 4831 } 4832 Assert(NumPreallocatedArgs != 0, 4833 "cannot use preallocated intrinsics on a call without " 4834 "preallocated arguments"); 4835 Assert(NumArgs->equalsInt(NumPreallocatedArgs), 4836 "llvm.call.preallocated.setup arg size must be equal to number " 4837 "of preallocated arguments " 4838 "at call site", 4839 Call, *UseCall); 4840 // getOperandBundle() cannot be called if more than one of the operand 4841 // bundle exists. There is already a check elsewhere for this, so skip 4842 // here if we see more than one. 4843 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) > 4844 1) { 4845 return; 4846 } 4847 auto PreallocatedBundle = 4848 UseCall->getOperandBundle(LLVMContext::OB_preallocated); 4849 Assert(PreallocatedBundle, 4850 "Use of llvm.call.preallocated.setup outside intrinsics " 4851 "must be in \"preallocated\" operand bundle"); 4852 Assert(PreallocatedBundle->Inputs.front().get() == &Call, 4853 "preallocated bundle must have token from corresponding " 4854 "llvm.call.preallocated.setup"); 4855 } 4856 } 4857 break; 4858 } 4859 case Intrinsic::call_preallocated_arg: { 4860 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4861 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4862 Intrinsic::call_preallocated_setup, 4863 "llvm.call.preallocated.arg token argument must be a " 4864 "llvm.call.preallocated.setup"); 4865 Assert(Call.hasFnAttr(Attribute::Preallocated), 4866 "llvm.call.preallocated.arg must be called with a \"preallocated\" " 4867 "call site attribute"); 4868 break; 4869 } 4870 case Intrinsic::call_preallocated_teardown: { 4871 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4872 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4873 Intrinsic::call_preallocated_setup, 4874 "llvm.call.preallocated.teardown token argument must be a " 4875 "llvm.call.preallocated.setup"); 4876 break; 4877 } 4878 case Intrinsic::gcroot: 4879 case Intrinsic::gcwrite: 4880 case Intrinsic::gcread: 4881 if (ID == Intrinsic::gcroot) { 4882 AllocaInst *AI = 4883 dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts()); 4884 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call); 4885 Assert(isa<Constant>(Call.getArgOperand(1)), 4886 "llvm.gcroot parameter #2 must be a constant.", Call); 4887 if (!AI->getAllocatedType()->isPointerTy()) { 4888 Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)), 4889 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4890 "or argument #2 must be a non-null constant.", 4891 Call); 4892 } 4893 } 4894 4895 Assert(Call.getParent()->getParent()->hasGC(), 4896 "Enclosing function does not use GC.", Call); 4897 break; 4898 case Intrinsic::init_trampoline: 4899 Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()), 4900 "llvm.init_trampoline parameter #2 must resolve to a function.", 4901 Call); 4902 break; 4903 case Intrinsic::prefetch: 4904 Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 && 4905 cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4, 4906 "invalid arguments to llvm.prefetch", Call); 4907 break; 4908 case Intrinsic::stackprotector: 4909 Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()), 4910 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call); 4911 break; 4912 case Intrinsic::localescape: { 4913 BasicBlock *BB = Call.getParent(); 4914 Assert(BB == &BB->getParent()->front(), 4915 "llvm.localescape used outside of entry block", Call); 4916 Assert(!SawFrameEscape, 4917 "multiple calls to llvm.localescape in one function", Call); 4918 for (Value *Arg : Call.args()) { 4919 if (isa<ConstantPointerNull>(Arg)) 4920 continue; // Null values are allowed as placeholders. 4921 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4922 Assert(AI && AI->isStaticAlloca(), 4923 "llvm.localescape only accepts static allocas", Call); 4924 } 4925 FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands(); 4926 SawFrameEscape = true; 4927 break; 4928 } 4929 case Intrinsic::localrecover: { 4930 Value *FnArg = Call.getArgOperand(0)->stripPointerCasts(); 4931 Function *Fn = dyn_cast<Function>(FnArg); 4932 Assert(Fn && !Fn->isDeclaration(), 4933 "llvm.localrecover first " 4934 "argument must be function defined in this module", 4935 Call); 4936 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2)); 4937 auto &Entry = FrameEscapeInfo[Fn]; 4938 Entry.second = unsigned( 4939 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4940 break; 4941 } 4942 4943 case Intrinsic::experimental_gc_statepoint: 4944 if (auto *CI = dyn_cast<CallInst>(&Call)) 4945 Assert(!CI->isInlineAsm(), 4946 "gc.statepoint support for inline assembly unimplemented", CI); 4947 Assert(Call.getParent()->getParent()->hasGC(), 4948 "Enclosing function does not use GC.", Call); 4949 4950 verifyStatepoint(Call); 4951 break; 4952 case Intrinsic::experimental_gc_result: { 4953 Assert(Call.getParent()->getParent()->hasGC(), 4954 "Enclosing function does not use GC.", Call); 4955 // Are we tied to a statepoint properly? 4956 const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0)); 4957 const Function *StatepointFn = 4958 StatepointCall ? StatepointCall->getCalledFunction() : nullptr; 4959 Assert(StatepointFn && StatepointFn->isDeclaration() && 4960 StatepointFn->getIntrinsicID() == 4961 Intrinsic::experimental_gc_statepoint, 4962 "gc.result operand #1 must be from a statepoint", Call, 4963 Call.getArgOperand(0)); 4964 4965 // Assert that result type matches wrapped callee. 4966 const Value *Target = StatepointCall->getArgOperand(2); 4967 auto *PT = cast<PointerType>(Target->getType()); 4968 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4969 Assert(Call.getType() == TargetFuncType->getReturnType(), 4970 "gc.result result type does not match wrapped callee", Call); 4971 break; 4972 } 4973 case Intrinsic::experimental_gc_relocate: { 4974 Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call); 4975 4976 Assert(isa<PointerType>(Call.getType()->getScalarType()), 4977 "gc.relocate must return a pointer or a vector of pointers", Call); 4978 4979 // Check that this relocate is correctly tied to the statepoint 4980 4981 // This is case for relocate on the unwinding path of an invoke statepoint 4982 if (LandingPadInst *LandingPad = 4983 dyn_cast<LandingPadInst>(Call.getArgOperand(0))) { 4984 4985 const BasicBlock *InvokeBB = 4986 LandingPad->getParent()->getUniquePredecessor(); 4987 4988 // Landingpad relocates should have only one predecessor with invoke 4989 // statepoint terminator 4990 Assert(InvokeBB, "safepoints should have unique landingpads", 4991 LandingPad->getParent()); 4992 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4993 InvokeBB); 4994 Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()), 4995 "gc relocate should be linked to a statepoint", InvokeBB); 4996 } else { 4997 // In all other cases relocate should be tied to the statepoint directly. 4998 // This covers relocates on a normal return path of invoke statepoint and 4999 // relocates of a call statepoint. 5000 auto Token = Call.getArgOperand(0); 5001 Assert(isa<GCStatepointInst>(Token), 5002 "gc relocate is incorrectly tied to the statepoint", Call, Token); 5003 } 5004 5005 // Verify rest of the relocate arguments. 5006 const CallBase &StatepointCall = 5007 *cast<GCRelocateInst>(Call).getStatepoint(); 5008 5009 // Both the base and derived must be piped through the safepoint. 5010 Value *Base = Call.getArgOperand(1); 5011 Assert(isa<ConstantInt>(Base), 5012 "gc.relocate operand #2 must be integer offset", Call); 5013 5014 Value *Derived = Call.getArgOperand(2); 5015 Assert(isa<ConstantInt>(Derived), 5016 "gc.relocate operand #3 must be integer offset", Call); 5017 5018 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 5019 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 5020 5021 // Check the bounds 5022 if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) { 5023 Assert(BaseIndex < Opt->Inputs.size(), 5024 "gc.relocate: statepoint base index out of bounds", Call); 5025 Assert(DerivedIndex < Opt->Inputs.size(), 5026 "gc.relocate: statepoint derived index out of bounds", Call); 5027 } 5028 5029 // Relocated value must be either a pointer type or vector-of-pointer type, 5030 // but gc_relocate does not need to return the same pointer type as the 5031 // relocated pointer. It can be casted to the correct type later if it's 5032 // desired. However, they must have the same address space and 'vectorness' 5033 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call); 5034 Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(), 5035 "gc.relocate: relocated value must be a gc pointer", Call); 5036 5037 auto ResultType = Call.getType(); 5038 auto DerivedType = Relocate.getDerivedPtr()->getType(); 5039 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 5040 "gc.relocate: vector relocates to vector and pointer to pointer", 5041 Call); 5042 Assert( 5043 ResultType->getPointerAddressSpace() == 5044 DerivedType->getPointerAddressSpace(), 5045 "gc.relocate: relocating a pointer shouldn't change its address space", 5046 Call); 5047 break; 5048 } 5049 case Intrinsic::eh_exceptioncode: 5050 case Intrinsic::eh_exceptionpointer: { 5051 Assert(isa<CatchPadInst>(Call.getArgOperand(0)), 5052 "eh.exceptionpointer argument must be a catchpad", Call); 5053 break; 5054 } 5055 case Intrinsic::get_active_lane_mask: { 5056 Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a " 5057 "vector", Call); 5058 auto *ElemTy = Call.getType()->getScalarType(); 5059 Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not " 5060 "i1", Call); 5061 break; 5062 } 5063 case Intrinsic::masked_load: { 5064 Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector", 5065 Call); 5066 5067 Value *Ptr = Call.getArgOperand(0); 5068 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1)); 5069 Value *Mask = Call.getArgOperand(2); 5070 Value *PassThru = Call.getArgOperand(3); 5071 Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector", 5072 Call); 5073 Assert(Alignment->getValue().isPowerOf2(), 5074 "masked_load: alignment must be a power of 2", Call); 5075 5076 // DataTy is the overloaded type 5077 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 5078 Assert(DataTy == Call.getType(), 5079 "masked_load: return must match pointer type", Call); 5080 Assert(PassThru->getType() == DataTy, 5081 "masked_load: pass through and data type must match", Call); 5082 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 5083 cast<VectorType>(DataTy)->getElementCount(), 5084 "masked_load: vector mask must be same length as data", Call); 5085 break; 5086 } 5087 case Intrinsic::masked_store: { 5088 Value *Val = Call.getArgOperand(0); 5089 Value *Ptr = Call.getArgOperand(1); 5090 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2)); 5091 Value *Mask = Call.getArgOperand(3); 5092 Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector", 5093 Call); 5094 Assert(Alignment->getValue().isPowerOf2(), 5095 "masked_store: alignment must be a power of 2", Call); 5096 5097 // DataTy is the overloaded type 5098 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 5099 Assert(DataTy == Val->getType(), 5100 "masked_store: storee must match pointer type", Call); 5101 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 5102 cast<VectorType>(DataTy)->getElementCount(), 5103 "masked_store: vector mask must be same length as data", Call); 5104 break; 5105 } 5106 5107 case Intrinsic::masked_gather: { 5108 const APInt &Alignment = 5109 cast<ConstantInt>(Call.getArgOperand(1))->getValue(); 5110 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 5111 "masked_gather: alignment must be 0 or a power of 2", Call); 5112 break; 5113 } 5114 case Intrinsic::masked_scatter: { 5115 const APInt &Alignment = 5116 cast<ConstantInt>(Call.getArgOperand(2))->getValue(); 5117 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 5118 "masked_scatter: alignment must be 0 or a power of 2", Call); 5119 break; 5120 } 5121 5122 case Intrinsic::experimental_guard: { 5123 Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call); 5124 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 5125 "experimental_guard must have exactly one " 5126 "\"deopt\" operand bundle"); 5127 break; 5128 } 5129 5130 case Intrinsic::experimental_deoptimize: { 5131 Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked", 5132 Call); 5133 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 5134 "experimental_deoptimize must have exactly one " 5135 "\"deopt\" operand bundle"); 5136 Assert(Call.getType() == Call.getFunction()->getReturnType(), 5137 "experimental_deoptimize return type must match caller return type"); 5138 5139 if (isa<CallInst>(Call)) { 5140 auto *RI = dyn_cast<ReturnInst>(Call.getNextNode()); 5141 Assert(RI, 5142 "calls to experimental_deoptimize must be followed by a return"); 5143 5144 if (!Call.getType()->isVoidTy() && RI) 5145 Assert(RI->getReturnValue() == &Call, 5146 "calls to experimental_deoptimize must be followed by a return " 5147 "of the value computed by experimental_deoptimize"); 5148 } 5149 5150 break; 5151 } 5152 case Intrinsic::vector_reduce_and: 5153 case Intrinsic::vector_reduce_or: 5154 case Intrinsic::vector_reduce_xor: 5155 case Intrinsic::vector_reduce_add: 5156 case Intrinsic::vector_reduce_mul: 5157 case Intrinsic::vector_reduce_smax: 5158 case Intrinsic::vector_reduce_smin: 5159 case Intrinsic::vector_reduce_umax: 5160 case Intrinsic::vector_reduce_umin: { 5161 Type *ArgTy = Call.getArgOperand(0)->getType(); 5162 Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(), 5163 "Intrinsic has incorrect argument type!"); 5164 break; 5165 } 5166 case Intrinsic::vector_reduce_fmax: 5167 case Intrinsic::vector_reduce_fmin: { 5168 Type *ArgTy = Call.getArgOperand(0)->getType(); 5169 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(), 5170 "Intrinsic has incorrect argument type!"); 5171 break; 5172 } 5173 case Intrinsic::vector_reduce_fadd: 5174 case Intrinsic::vector_reduce_fmul: { 5175 // Unlike the other reductions, the first argument is a start value. The 5176 // second argument is the vector to be reduced. 5177 Type *ArgTy = Call.getArgOperand(1)->getType(); 5178 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(), 5179 "Intrinsic has incorrect argument type!"); 5180 break; 5181 } 5182 case Intrinsic::smul_fix: 5183 case Intrinsic::smul_fix_sat: 5184 case Intrinsic::umul_fix: 5185 case Intrinsic::umul_fix_sat: 5186 case Intrinsic::sdiv_fix: 5187 case Intrinsic::sdiv_fix_sat: 5188 case Intrinsic::udiv_fix: 5189 case Intrinsic::udiv_fix_sat: { 5190 Value *Op1 = Call.getArgOperand(0); 5191 Value *Op2 = Call.getArgOperand(1); 5192 Assert(Op1->getType()->isIntOrIntVectorTy(), 5193 "first operand of [us][mul|div]_fix[_sat] must be an int type or " 5194 "vector of ints"); 5195 Assert(Op2->getType()->isIntOrIntVectorTy(), 5196 "second operand of [us][mul|div]_fix[_sat] must be an int type or " 5197 "vector of ints"); 5198 5199 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2)); 5200 Assert(Op3->getType()->getBitWidth() <= 32, 5201 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits"); 5202 5203 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat || 5204 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) { 5205 Assert( 5206 Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(), 5207 "the scale of s[mul|div]_fix[_sat] must be less than the width of " 5208 "the operands"); 5209 } else { 5210 Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(), 5211 "the scale of u[mul|div]_fix[_sat] must be less than or equal " 5212 "to the width of the operands"); 5213 } 5214 break; 5215 } 5216 case Intrinsic::lround: 5217 case Intrinsic::llround: 5218 case Intrinsic::lrint: 5219 case Intrinsic::llrint: { 5220 Type *ValTy = Call.getArgOperand(0)->getType(); 5221 Type *ResultTy = Call.getType(); 5222 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5223 "Intrinsic does not support vectors", &Call); 5224 break; 5225 } 5226 case Intrinsic::bswap: { 5227 Type *Ty = Call.getType(); 5228 unsigned Size = Ty->getScalarSizeInBits(); 5229 Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call); 5230 break; 5231 } 5232 case Intrinsic::invariant_start: { 5233 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 5234 Assert(InvariantSize && 5235 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()), 5236 "invariant_start parameter must be -1, 0 or a positive number", 5237 &Call); 5238 break; 5239 } 5240 case Intrinsic::matrix_multiply: 5241 case Intrinsic::matrix_transpose: 5242 case Intrinsic::matrix_column_major_load: 5243 case Intrinsic::matrix_column_major_store: { 5244 Function *IF = Call.getCalledFunction(); 5245 ConstantInt *Stride = nullptr; 5246 ConstantInt *NumRows; 5247 ConstantInt *NumColumns; 5248 VectorType *ResultTy; 5249 Type *Op0ElemTy = nullptr; 5250 Type *Op1ElemTy = nullptr; 5251 switch (ID) { 5252 case Intrinsic::matrix_multiply: 5253 NumRows = cast<ConstantInt>(Call.getArgOperand(2)); 5254 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5255 ResultTy = cast<VectorType>(Call.getType()); 5256 Op0ElemTy = 5257 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5258 Op1ElemTy = 5259 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType(); 5260 break; 5261 case Intrinsic::matrix_transpose: 5262 NumRows = cast<ConstantInt>(Call.getArgOperand(1)); 5263 NumColumns = cast<ConstantInt>(Call.getArgOperand(2)); 5264 ResultTy = cast<VectorType>(Call.getType()); 5265 Op0ElemTy = 5266 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5267 break; 5268 case Intrinsic::matrix_column_major_load: 5269 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1)); 5270 NumRows = cast<ConstantInt>(Call.getArgOperand(3)); 5271 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5272 ResultTy = cast<VectorType>(Call.getType()); 5273 Op0ElemTy = 5274 cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType(); 5275 break; 5276 case Intrinsic::matrix_column_major_store: 5277 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2)); 5278 NumRows = cast<ConstantInt>(Call.getArgOperand(4)); 5279 NumColumns = cast<ConstantInt>(Call.getArgOperand(5)); 5280 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5281 Op0ElemTy = 5282 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5283 Op1ElemTy = 5284 cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType(); 5285 break; 5286 default: 5287 llvm_unreachable("unexpected intrinsic"); 5288 } 5289 5290 Assert(ResultTy->getElementType()->isIntegerTy() || 5291 ResultTy->getElementType()->isFloatingPointTy(), 5292 "Result type must be an integer or floating-point type!", IF); 5293 5294 Assert(ResultTy->getElementType() == Op0ElemTy, 5295 "Vector element type mismatch of the result and first operand " 5296 "vector!", IF); 5297 5298 if (Op1ElemTy) 5299 Assert(ResultTy->getElementType() == Op1ElemTy, 5300 "Vector element type mismatch of the result and second operand " 5301 "vector!", IF); 5302 5303 Assert(cast<FixedVectorType>(ResultTy)->getNumElements() == 5304 NumRows->getZExtValue() * NumColumns->getZExtValue(), 5305 "Result of a matrix operation does not fit in the returned vector!"); 5306 5307 if (Stride) 5308 Assert(Stride->getZExtValue() >= NumRows->getZExtValue(), 5309 "Stride must be greater or equal than the number of rows!", IF); 5310 5311 break; 5312 } 5313 case Intrinsic::experimental_stepvector: { 5314 VectorType *VecTy = dyn_cast<VectorType>(Call.getType()); 5315 Assert(VecTy && VecTy->getScalarType()->isIntegerTy() && 5316 VecTy->getScalarSizeInBits() >= 8, 5317 "experimental_stepvector only supported for vectors of integers " 5318 "with a bitwidth of at least 8.", 5319 &Call); 5320 break; 5321 } 5322 case Intrinsic::experimental_vector_insert: { 5323 VectorType *VecTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5324 VectorType *SubVecTy = cast<VectorType>(Call.getArgOperand(1)->getType()); 5325 5326 Assert(VecTy->getElementType() == SubVecTy->getElementType(), 5327 "experimental_vector_insert parameters must have the same element " 5328 "type.", 5329 &Call); 5330 break; 5331 } 5332 case Intrinsic::experimental_vector_extract: { 5333 VectorType *ResultTy = cast<VectorType>(Call.getType()); 5334 VectorType *VecTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5335 5336 Assert(ResultTy->getElementType() == VecTy->getElementType(), 5337 "experimental_vector_extract result must have the same element " 5338 "type as the input vector.", 5339 &Call); 5340 break; 5341 } 5342 case Intrinsic::experimental_noalias_scope_decl: { 5343 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call)); 5344 break; 5345 } 5346 }; 5347 } 5348 5349 /// Carefully grab the subprogram from a local scope. 5350 /// 5351 /// This carefully grabs the subprogram from a local scope, avoiding the 5352 /// built-in assertions that would typically fire. 5353 static DISubprogram *getSubprogram(Metadata *LocalScope) { 5354 if (!LocalScope) 5355 return nullptr; 5356 5357 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 5358 return SP; 5359 5360 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 5361 return getSubprogram(LB->getRawScope()); 5362 5363 // Just return null; broken scope chains are checked elsewhere. 5364 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 5365 return nullptr; 5366 } 5367 5368 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) { 5369 unsigned NumOperands; 5370 bool HasRoundingMD; 5371 switch (FPI.getIntrinsicID()) { 5372 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 5373 case Intrinsic::INTRINSIC: \ 5374 NumOperands = NARG; \ 5375 HasRoundingMD = ROUND_MODE; \ 5376 break; 5377 #include "llvm/IR/ConstrainedOps.def" 5378 default: 5379 llvm_unreachable("Invalid constrained FP intrinsic!"); 5380 } 5381 NumOperands += (1 + HasRoundingMD); 5382 // Compare intrinsics carry an extra predicate metadata operand. 5383 if (isa<ConstrainedFPCmpIntrinsic>(FPI)) 5384 NumOperands += 1; 5385 Assert((FPI.getNumArgOperands() == NumOperands), 5386 "invalid arguments for constrained FP intrinsic", &FPI); 5387 5388 switch (FPI.getIntrinsicID()) { 5389 case Intrinsic::experimental_constrained_lrint: 5390 case Intrinsic::experimental_constrained_llrint: { 5391 Type *ValTy = FPI.getArgOperand(0)->getType(); 5392 Type *ResultTy = FPI.getType(); 5393 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5394 "Intrinsic does not support vectors", &FPI); 5395 } 5396 break; 5397 5398 case Intrinsic::experimental_constrained_lround: 5399 case Intrinsic::experimental_constrained_llround: { 5400 Type *ValTy = FPI.getArgOperand(0)->getType(); 5401 Type *ResultTy = FPI.getType(); 5402 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5403 "Intrinsic does not support vectors", &FPI); 5404 break; 5405 } 5406 5407 case Intrinsic::experimental_constrained_fcmp: 5408 case Intrinsic::experimental_constrained_fcmps: { 5409 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate(); 5410 Assert(CmpInst::isFPPredicate(Pred), 5411 "invalid predicate for constrained FP comparison intrinsic", &FPI); 5412 break; 5413 } 5414 5415 case Intrinsic::experimental_constrained_fptosi: 5416 case Intrinsic::experimental_constrained_fptoui: { 5417 Value *Operand = FPI.getArgOperand(0); 5418 uint64_t NumSrcElem = 0; 5419 Assert(Operand->getType()->isFPOrFPVectorTy(), 5420 "Intrinsic first argument must be floating point", &FPI); 5421 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5422 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5423 } 5424 5425 Operand = &FPI; 5426 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5427 "Intrinsic first argument and result disagree on vector use", &FPI); 5428 Assert(Operand->getType()->isIntOrIntVectorTy(), 5429 "Intrinsic result must be an integer", &FPI); 5430 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5431 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5432 "Intrinsic first argument and result vector lengths must be equal", 5433 &FPI); 5434 } 5435 } 5436 break; 5437 5438 case Intrinsic::experimental_constrained_sitofp: 5439 case Intrinsic::experimental_constrained_uitofp: { 5440 Value *Operand = FPI.getArgOperand(0); 5441 uint64_t NumSrcElem = 0; 5442 Assert(Operand->getType()->isIntOrIntVectorTy(), 5443 "Intrinsic first argument must be integer", &FPI); 5444 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5445 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5446 } 5447 5448 Operand = &FPI; 5449 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5450 "Intrinsic first argument and result disagree on vector use", &FPI); 5451 Assert(Operand->getType()->isFPOrFPVectorTy(), 5452 "Intrinsic result must be a floating point", &FPI); 5453 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5454 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5455 "Intrinsic first argument and result vector lengths must be equal", 5456 &FPI); 5457 } 5458 } break; 5459 5460 case Intrinsic::experimental_constrained_fptrunc: 5461 case Intrinsic::experimental_constrained_fpext: { 5462 Value *Operand = FPI.getArgOperand(0); 5463 Type *OperandTy = Operand->getType(); 5464 Value *Result = &FPI; 5465 Type *ResultTy = Result->getType(); 5466 Assert(OperandTy->isFPOrFPVectorTy(), 5467 "Intrinsic first argument must be FP or FP vector", &FPI); 5468 Assert(ResultTy->isFPOrFPVectorTy(), 5469 "Intrinsic result must be FP or FP vector", &FPI); 5470 Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(), 5471 "Intrinsic first argument and result disagree on vector use", &FPI); 5472 if (OperandTy->isVectorTy()) { 5473 Assert(cast<FixedVectorType>(OperandTy)->getNumElements() == 5474 cast<FixedVectorType>(ResultTy)->getNumElements(), 5475 "Intrinsic first argument and result vector lengths must be equal", 5476 &FPI); 5477 } 5478 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) { 5479 Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(), 5480 "Intrinsic first argument's type must be larger than result type", 5481 &FPI); 5482 } else { 5483 Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(), 5484 "Intrinsic first argument's type must be smaller than result type", 5485 &FPI); 5486 } 5487 } 5488 break; 5489 5490 default: 5491 break; 5492 } 5493 5494 // If a non-metadata argument is passed in a metadata slot then the 5495 // error will be caught earlier when the incorrect argument doesn't 5496 // match the specification in the intrinsic call table. Thus, no 5497 // argument type check is needed here. 5498 5499 Assert(FPI.getExceptionBehavior().hasValue(), 5500 "invalid exception behavior argument", &FPI); 5501 if (HasRoundingMD) { 5502 Assert(FPI.getRoundingMode().hasValue(), 5503 "invalid rounding mode argument", &FPI); 5504 } 5505 } 5506 5507 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) { 5508 auto *MD = DII.getRawLocation(); 5509 AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) || 5510 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 5511 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 5512 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 5513 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 5514 DII.getRawVariable()); 5515 AssertDI(isa<DIExpression>(DII.getRawExpression()), 5516 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 5517 DII.getRawExpression()); 5518 5519 // Ignore broken !dbg attachments; they're checked elsewhere. 5520 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 5521 if (!isa<DILocation>(N)) 5522 return; 5523 5524 BasicBlock *BB = DII.getParent(); 5525 Function *F = BB ? BB->getParent() : nullptr; 5526 5527 // The scopes for variables and !dbg attachments must agree. 5528 DILocalVariable *Var = DII.getVariable(); 5529 DILocation *Loc = DII.getDebugLoc(); 5530 AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5531 &DII, BB, F); 5532 5533 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 5534 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5535 if (!VarSP || !LocSP) 5536 return; // Broken scope chains are checked elsewhere. 5537 5538 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5539 " variable and !dbg attachment", 5540 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 5541 Loc->getScope()->getSubprogram()); 5542 5543 // This check is redundant with one in visitLocalVariable(). 5544 AssertDI(isType(Var->getRawType()), "invalid type ref", Var, 5545 Var->getRawType()); 5546 verifyFnArgs(DII); 5547 } 5548 5549 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) { 5550 AssertDI(isa<DILabel>(DLI.getRawLabel()), 5551 "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI, 5552 DLI.getRawLabel()); 5553 5554 // Ignore broken !dbg attachments; they're checked elsewhere. 5555 if (MDNode *N = DLI.getDebugLoc().getAsMDNode()) 5556 if (!isa<DILocation>(N)) 5557 return; 5558 5559 BasicBlock *BB = DLI.getParent(); 5560 Function *F = BB ? BB->getParent() : nullptr; 5561 5562 // The scopes for variables and !dbg attachments must agree. 5563 DILabel *Label = DLI.getLabel(); 5564 DILocation *Loc = DLI.getDebugLoc(); 5565 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5566 &DLI, BB, F); 5567 5568 DISubprogram *LabelSP = getSubprogram(Label->getRawScope()); 5569 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5570 if (!LabelSP || !LocSP) 5571 return; 5572 5573 AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5574 " label and !dbg attachment", 5575 &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc, 5576 Loc->getScope()->getSubprogram()); 5577 } 5578 5579 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) { 5580 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable()); 5581 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5582 5583 // We don't know whether this intrinsic verified correctly. 5584 if (!V || !E || !E->isValid()) 5585 return; 5586 5587 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression. 5588 auto Fragment = E->getFragmentInfo(); 5589 if (!Fragment) 5590 return; 5591 5592 // The frontend helps out GDB by emitting the members of local anonymous 5593 // unions as artificial local variables with shared storage. When SROA splits 5594 // the storage for artificial local variables that are smaller than the entire 5595 // union, the overhang piece will be outside of the allotted space for the 5596 // variable and this check fails. 5597 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 5598 if (V->isArtificial()) 5599 return; 5600 5601 verifyFragmentExpression(*V, *Fragment, &I); 5602 } 5603 5604 template <typename ValueOrMetadata> 5605 void Verifier::verifyFragmentExpression(const DIVariable &V, 5606 DIExpression::FragmentInfo Fragment, 5607 ValueOrMetadata *Desc) { 5608 // If there's no size, the type is broken, but that should be checked 5609 // elsewhere. 5610 auto VarSize = V.getSizeInBits(); 5611 if (!VarSize) 5612 return; 5613 5614 unsigned FragSize = Fragment.SizeInBits; 5615 unsigned FragOffset = Fragment.OffsetInBits; 5616 AssertDI(FragSize + FragOffset <= *VarSize, 5617 "fragment is larger than or outside of variable", Desc, &V); 5618 AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V); 5619 } 5620 5621 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) { 5622 // This function does not take the scope of noninlined function arguments into 5623 // account. Don't run it if current function is nodebug, because it may 5624 // contain inlined debug intrinsics. 5625 if (!HasDebugInfo) 5626 return; 5627 5628 // For performance reasons only check non-inlined ones. 5629 if (I.getDebugLoc()->getInlinedAt()) 5630 return; 5631 5632 DILocalVariable *Var = I.getVariable(); 5633 AssertDI(Var, "dbg intrinsic without variable"); 5634 5635 unsigned ArgNo = Var->getArg(); 5636 if (!ArgNo) 5637 return; 5638 5639 // Verify there are no duplicate function argument debug info entries. 5640 // These will cause hard-to-debug assertions in the DWARF backend. 5641 if (DebugFnArgs.size() < ArgNo) 5642 DebugFnArgs.resize(ArgNo, nullptr); 5643 5644 auto *Prev = DebugFnArgs[ArgNo - 1]; 5645 DebugFnArgs[ArgNo - 1] = Var; 5646 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I, 5647 Prev, Var); 5648 } 5649 5650 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) { 5651 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5652 5653 // We don't know whether this intrinsic verified correctly. 5654 if (!E || !E->isValid()) 5655 return; 5656 5657 AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I); 5658 } 5659 5660 void Verifier::verifyCompileUnits() { 5661 // When more than one Module is imported into the same context, such as during 5662 // an LTO build before linking the modules, ODR type uniquing may cause types 5663 // to point to a different CU. This check does not make sense in this case. 5664 if (M.getContext().isODRUniquingDebugTypes()) 5665 return; 5666 auto *CUs = M.getNamedMetadata("llvm.dbg.cu"); 5667 SmallPtrSet<const Metadata *, 2> Listed; 5668 if (CUs) 5669 Listed.insert(CUs->op_begin(), CUs->op_end()); 5670 for (auto *CU : CUVisited) 5671 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU); 5672 CUVisited.clear(); 5673 } 5674 5675 void Verifier::verifyDeoptimizeCallingConvs() { 5676 if (DeoptimizeDeclarations.empty()) 5677 return; 5678 5679 const Function *First = DeoptimizeDeclarations[0]; 5680 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 5681 Assert(First->getCallingConv() == F->getCallingConv(), 5682 "All llvm.experimental.deoptimize declarations must have the same " 5683 "calling convention", 5684 First, F); 5685 } 5686 } 5687 5688 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) { 5689 bool HasSource = F.getSource().hasValue(); 5690 if (!HasSourceDebugInfo.count(&U)) 5691 HasSourceDebugInfo[&U] = HasSource; 5692 AssertDI(HasSource == HasSourceDebugInfo[&U], 5693 "inconsistent use of embedded source"); 5694 } 5695 5696 void Verifier::verifyNoAliasScopeDecl() { 5697 if (NoAliasScopeDecls.empty()) 5698 return; 5699 5700 // only a single scope must be declared at a time. 5701 for (auto *II : NoAliasScopeDecls) { 5702 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl && 5703 "Not a llvm.experimental.noalias.scope.decl ?"); 5704 const auto *ScopeListMV = dyn_cast<MetadataAsValue>( 5705 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5706 Assert(ScopeListMV != nullptr, 5707 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue " 5708 "argument", 5709 II); 5710 5711 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata()); 5712 Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", 5713 II); 5714 Assert(ScopeListMD->getNumOperands() == 1, 5715 "!id.scope.list must point to a list with a single scope", II); 5716 } 5717 5718 // Only check the domination rule when requested. Once all passes have been 5719 // adapted this option can go away. 5720 if (!VerifyNoAliasScopeDomination) 5721 return; 5722 5723 // Now sort the intrinsics based on the scope MDNode so that declarations of 5724 // the same scopes are next to each other. 5725 auto GetScope = [](IntrinsicInst *II) { 5726 const auto *ScopeListMV = cast<MetadataAsValue>( 5727 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5728 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0); 5729 }; 5730 5731 // We are sorting on MDNode pointers here. For valid input IR this is ok. 5732 // TODO: Sort on Metadata ID to avoid non-deterministic error messages. 5733 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) { 5734 return GetScope(Lhs) < GetScope(Rhs); 5735 }; 5736 5737 llvm::sort(NoAliasScopeDecls, Compare); 5738 5739 // Go over the intrinsics and check that for the same scope, they are not 5740 // dominating each other. 5741 auto ItCurrent = NoAliasScopeDecls.begin(); 5742 while (ItCurrent != NoAliasScopeDecls.end()) { 5743 auto CurScope = GetScope(*ItCurrent); 5744 auto ItNext = ItCurrent; 5745 do { 5746 ++ItNext; 5747 } while (ItNext != NoAliasScopeDecls.end() && 5748 GetScope(*ItNext) == CurScope); 5749 5750 // [ItCurrent, ItNext) represents the declarations for the same scope. 5751 // Ensure they are not dominating each other.. but only if it is not too 5752 // expensive. 5753 if (ItNext - ItCurrent < 32) 5754 for (auto *I : llvm::make_range(ItCurrent, ItNext)) 5755 for (auto *J : llvm::make_range(ItCurrent, ItNext)) 5756 if (I != J) 5757 Assert(!DT.dominates(I, J), 5758 "llvm.experimental.noalias.scope.decl dominates another one " 5759 "with the same scope", 5760 I); 5761 ItCurrent = ItNext; 5762 } 5763 } 5764 5765 //===----------------------------------------------------------------------===// 5766 // Implement the public interfaces to this file... 5767 //===----------------------------------------------------------------------===// 5768 5769 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 5770 Function &F = const_cast<Function &>(f); 5771 5772 // Don't use a raw_null_ostream. Printing IR is expensive. 5773 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent()); 5774 5775 // Note that this function's return value is inverted from what you would 5776 // expect of a function called "verify". 5777 return !V.verify(F); 5778 } 5779 5780 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 5781 bool *BrokenDebugInfo) { 5782 // Don't use a raw_null_ostream. Printing IR is expensive. 5783 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M); 5784 5785 bool Broken = false; 5786 for (const Function &F : M) 5787 Broken |= !V.verify(F); 5788 5789 Broken |= !V.verify(); 5790 if (BrokenDebugInfo) 5791 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 5792 // Note that this function's return value is inverted from what you would 5793 // expect of a function called "verify". 5794 return Broken; 5795 } 5796 5797 namespace { 5798 5799 struct VerifierLegacyPass : public FunctionPass { 5800 static char ID; 5801 5802 std::unique_ptr<Verifier> V; 5803 bool FatalErrors = true; 5804 5805 VerifierLegacyPass() : FunctionPass(ID) { 5806 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5807 } 5808 explicit VerifierLegacyPass(bool FatalErrors) 5809 : FunctionPass(ID), 5810 FatalErrors(FatalErrors) { 5811 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5812 } 5813 5814 bool doInitialization(Module &M) override { 5815 V = std::make_unique<Verifier>( 5816 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M); 5817 return false; 5818 } 5819 5820 bool runOnFunction(Function &F) override { 5821 if (!V->verify(F) && FatalErrors) { 5822 errs() << "in function " << F.getName() << '\n'; 5823 report_fatal_error("Broken function found, compilation aborted!"); 5824 } 5825 return false; 5826 } 5827 5828 bool doFinalization(Module &M) override { 5829 bool HasErrors = false; 5830 for (Function &F : M) 5831 if (F.isDeclaration()) 5832 HasErrors |= !V->verify(F); 5833 5834 HasErrors |= !V->verify(); 5835 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo())) 5836 report_fatal_error("Broken module found, compilation aborted!"); 5837 return false; 5838 } 5839 5840 void getAnalysisUsage(AnalysisUsage &AU) const override { 5841 AU.setPreservesAll(); 5842 } 5843 }; 5844 5845 } // end anonymous namespace 5846 5847 /// Helper to issue failure from the TBAA verification 5848 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) { 5849 if (Diagnostic) 5850 return Diagnostic->CheckFailed(Args...); 5851 } 5852 5853 #define AssertTBAA(C, ...) \ 5854 do { \ 5855 if (!(C)) { \ 5856 CheckFailed(__VA_ARGS__); \ 5857 return false; \ 5858 } \ 5859 } while (false) 5860 5861 /// Verify that \p BaseNode can be used as the "base type" in the struct-path 5862 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a 5863 /// struct-type node describing an aggregate data structure (like a struct). 5864 TBAAVerifier::TBAABaseNodeSummary 5865 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode, 5866 bool IsNewFormat) { 5867 if (BaseNode->getNumOperands() < 2) { 5868 CheckFailed("Base nodes must have at least two operands", &I, BaseNode); 5869 return {true, ~0u}; 5870 } 5871 5872 auto Itr = TBAABaseNodes.find(BaseNode); 5873 if (Itr != TBAABaseNodes.end()) 5874 return Itr->second; 5875 5876 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat); 5877 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result}); 5878 (void)InsertResult; 5879 assert(InsertResult.second && "We just checked!"); 5880 return Result; 5881 } 5882 5883 TBAAVerifier::TBAABaseNodeSummary 5884 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode, 5885 bool IsNewFormat) { 5886 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u}; 5887 5888 if (BaseNode->getNumOperands() == 2) { 5889 // Scalar nodes can only be accessed at offset 0. 5890 return isValidScalarTBAANode(BaseNode) 5891 ? TBAAVerifier::TBAABaseNodeSummary({false, 0}) 5892 : InvalidNode; 5893 } 5894 5895 if (IsNewFormat) { 5896 if (BaseNode->getNumOperands() % 3 != 0) { 5897 CheckFailed("Access tag nodes must have the number of operands that is a " 5898 "multiple of 3!", BaseNode); 5899 return InvalidNode; 5900 } 5901 } else { 5902 if (BaseNode->getNumOperands() % 2 != 1) { 5903 CheckFailed("Struct tag nodes must have an odd number of operands!", 5904 BaseNode); 5905 return InvalidNode; 5906 } 5907 } 5908 5909 // Check the type size field. 5910 if (IsNewFormat) { 5911 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5912 BaseNode->getOperand(1)); 5913 if (!TypeSizeNode) { 5914 CheckFailed("Type size nodes must be constants!", &I, BaseNode); 5915 return InvalidNode; 5916 } 5917 } 5918 5919 // Check the type name field. In the new format it can be anything. 5920 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) { 5921 CheckFailed("Struct tag nodes have a string as their first operand", 5922 BaseNode); 5923 return InvalidNode; 5924 } 5925 5926 bool Failed = false; 5927 5928 Optional<APInt> PrevOffset; 5929 unsigned BitWidth = ~0u; 5930 5931 // We've already checked that BaseNode is not a degenerate root node with one 5932 // operand in \c verifyTBAABaseNode, so this loop should run at least once. 5933 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 5934 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 5935 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 5936 Idx += NumOpsPerField) { 5937 const MDOperand &FieldTy = BaseNode->getOperand(Idx); 5938 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1); 5939 if (!isa<MDNode>(FieldTy)) { 5940 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode); 5941 Failed = true; 5942 continue; 5943 } 5944 5945 auto *OffsetEntryCI = 5946 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset); 5947 if (!OffsetEntryCI) { 5948 CheckFailed("Offset entries must be constants!", &I, BaseNode); 5949 Failed = true; 5950 continue; 5951 } 5952 5953 if (BitWidth == ~0u) 5954 BitWidth = OffsetEntryCI->getBitWidth(); 5955 5956 if (OffsetEntryCI->getBitWidth() != BitWidth) { 5957 CheckFailed( 5958 "Bitwidth between the offsets and struct type entries must match", &I, 5959 BaseNode); 5960 Failed = true; 5961 continue; 5962 } 5963 5964 // NB! As far as I can tell, we generate a non-strictly increasing offset 5965 // sequence only from structs that have zero size bit fields. When 5966 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we 5967 // pick the field lexically the latest in struct type metadata node. This 5968 // mirrors the actual behavior of the alias analysis implementation. 5969 bool IsAscending = 5970 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue()); 5971 5972 if (!IsAscending) { 5973 CheckFailed("Offsets must be increasing!", &I, BaseNode); 5974 Failed = true; 5975 } 5976 5977 PrevOffset = OffsetEntryCI->getValue(); 5978 5979 if (IsNewFormat) { 5980 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5981 BaseNode->getOperand(Idx + 2)); 5982 if (!MemberSizeNode) { 5983 CheckFailed("Member size entries must be constants!", &I, BaseNode); 5984 Failed = true; 5985 continue; 5986 } 5987 } 5988 } 5989 5990 return Failed ? InvalidNode 5991 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth); 5992 } 5993 5994 static bool IsRootTBAANode(const MDNode *MD) { 5995 return MD->getNumOperands() < 2; 5996 } 5997 5998 static bool IsScalarTBAANodeImpl(const MDNode *MD, 5999 SmallPtrSetImpl<const MDNode *> &Visited) { 6000 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3) 6001 return false; 6002 6003 if (!isa<MDString>(MD->getOperand(0))) 6004 return false; 6005 6006 if (MD->getNumOperands() == 3) { 6007 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 6008 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0)))) 6009 return false; 6010 } 6011 6012 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 6013 return Parent && Visited.insert(Parent).second && 6014 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited)); 6015 } 6016 6017 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) { 6018 auto ResultIt = TBAAScalarNodes.find(MD); 6019 if (ResultIt != TBAAScalarNodes.end()) 6020 return ResultIt->second; 6021 6022 SmallPtrSet<const MDNode *, 4> Visited; 6023 bool Result = IsScalarTBAANodeImpl(MD, Visited); 6024 auto InsertResult = TBAAScalarNodes.insert({MD, Result}); 6025 (void)InsertResult; 6026 assert(InsertResult.second && "Just checked!"); 6027 6028 return Result; 6029 } 6030 6031 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p 6032 /// Offset in place to be the offset within the field node returned. 6033 /// 6034 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode. 6035 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I, 6036 const MDNode *BaseNode, 6037 APInt &Offset, 6038 bool IsNewFormat) { 6039 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!"); 6040 6041 // Scalar nodes have only one possible "field" -- their parent in the access 6042 // hierarchy. Offset must be zero at this point, but our caller is supposed 6043 // to Assert that. 6044 if (BaseNode->getNumOperands() == 2) 6045 return cast<MDNode>(BaseNode->getOperand(1)); 6046 6047 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 6048 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 6049 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 6050 Idx += NumOpsPerField) { 6051 auto *OffsetEntryCI = 6052 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1)); 6053 if (OffsetEntryCI->getValue().ugt(Offset)) { 6054 if (Idx == FirstFieldOpNo) { 6055 CheckFailed("Could not find TBAA parent in struct type node", &I, 6056 BaseNode, &Offset); 6057 return nullptr; 6058 } 6059 6060 unsigned PrevIdx = Idx - NumOpsPerField; 6061 auto *PrevOffsetEntryCI = 6062 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1)); 6063 Offset -= PrevOffsetEntryCI->getValue(); 6064 return cast<MDNode>(BaseNode->getOperand(PrevIdx)); 6065 } 6066 } 6067 6068 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField; 6069 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>( 6070 BaseNode->getOperand(LastIdx + 1)); 6071 Offset -= LastOffsetEntryCI->getValue(); 6072 return cast<MDNode>(BaseNode->getOperand(LastIdx)); 6073 } 6074 6075 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) { 6076 if (!Type || Type->getNumOperands() < 3) 6077 return false; 6078 6079 // In the new format type nodes shall have a reference to the parent type as 6080 // its first operand. 6081 MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0)); 6082 if (!Parent) 6083 return false; 6084 6085 return true; 6086 } 6087 6088 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) { 6089 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 6090 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) || 6091 isa<AtomicCmpXchgInst>(I), 6092 "This instruction shall not have a TBAA access tag!", &I); 6093 6094 bool IsStructPathTBAA = 6095 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 6096 6097 AssertTBAA( 6098 IsStructPathTBAA, 6099 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I); 6100 6101 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0)); 6102 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 6103 6104 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType); 6105 6106 if (IsNewFormat) { 6107 AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5, 6108 "Access tag metadata must have either 4 or 5 operands", &I, MD); 6109 } else { 6110 AssertTBAA(MD->getNumOperands() < 5, 6111 "Struct tag metadata must have either 3 or 4 operands", &I, MD); 6112 } 6113 6114 // Check the access size field. 6115 if (IsNewFormat) { 6116 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 6117 MD->getOperand(3)); 6118 AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD); 6119 } 6120 6121 // Check the immutability flag. 6122 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3; 6123 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) { 6124 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>( 6125 MD->getOperand(ImmutabilityFlagOpNo)); 6126 AssertTBAA(IsImmutableCI, 6127 "Immutability tag on struct tag metadata must be a constant", 6128 &I, MD); 6129 AssertTBAA( 6130 IsImmutableCI->isZero() || IsImmutableCI->isOne(), 6131 "Immutability part of the struct tag metadata must be either 0 or 1", 6132 &I, MD); 6133 } 6134 6135 AssertTBAA(BaseNode && AccessType, 6136 "Malformed struct tag metadata: base and access-type " 6137 "should be non-null and point to Metadata nodes", 6138 &I, MD, BaseNode, AccessType); 6139 6140 if (!IsNewFormat) { 6141 AssertTBAA(isValidScalarTBAANode(AccessType), 6142 "Access type node must be a valid scalar type", &I, MD, 6143 AccessType); 6144 } 6145 6146 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2)); 6147 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD); 6148 6149 APInt Offset = OffsetCI->getValue(); 6150 bool SeenAccessTypeInPath = false; 6151 6152 SmallPtrSet<MDNode *, 4> StructPath; 6153 6154 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode); 6155 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, 6156 IsNewFormat)) { 6157 if (!StructPath.insert(BaseNode).second) { 6158 CheckFailed("Cycle detected in struct path", &I, MD); 6159 return false; 6160 } 6161 6162 bool Invalid; 6163 unsigned BaseNodeBitWidth; 6164 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode, 6165 IsNewFormat); 6166 6167 // If the base node is invalid in itself, then we've already printed all the 6168 // errors we wanted to print. 6169 if (Invalid) 6170 return false; 6171 6172 SeenAccessTypeInPath |= BaseNode == AccessType; 6173 6174 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType) 6175 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access", 6176 &I, MD, &Offset); 6177 6178 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() || 6179 (BaseNodeBitWidth == 0 && Offset == 0) || 6180 (IsNewFormat && BaseNodeBitWidth == ~0u), 6181 "Access bit-width not the same as description bit-width", &I, MD, 6182 BaseNodeBitWidth, Offset.getBitWidth()); 6183 6184 if (IsNewFormat && SeenAccessTypeInPath) 6185 break; 6186 } 6187 6188 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", 6189 &I, MD); 6190 return true; 6191 } 6192 6193 char VerifierLegacyPass::ID = 0; 6194 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 6195 6196 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 6197 return new VerifierLegacyPass(FatalErrors); 6198 } 6199 6200 AnalysisKey VerifierAnalysis::Key; 6201 VerifierAnalysis::Result VerifierAnalysis::run(Module &M, 6202 ModuleAnalysisManager &) { 6203 Result Res; 6204 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 6205 return Res; 6206 } 6207 6208 VerifierAnalysis::Result VerifierAnalysis::run(Function &F, 6209 FunctionAnalysisManager &) { 6210 return { llvm::verifyFunction(F, &dbgs()), false }; 6211 } 6212 6213 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 6214 auto Res = AM.getResult<VerifierAnalysis>(M); 6215 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken)) 6216 report_fatal_error("Broken module found, compilation aborted!"); 6217 6218 return PreservedAnalyses::all(); 6219 } 6220 6221 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 6222 auto res = AM.getResult<VerifierAnalysis>(F); 6223 if (res.IRBroken && FatalErrors) 6224 report_fatal_error("Broken function found, compilation aborted!"); 6225 6226 return PreservedAnalyses::all(); 6227 } 6228