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