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