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