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