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