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