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