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