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