1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===// 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 pass statically checks for common and easily-identified constructs 10 // which produce undefined or likely unintended behavior in LLVM IR. 11 // 12 // It is not a guarantee of correctness, in two ways. First, it isn't 13 // comprehensive. There are checks which could be done statically which are 14 // not yet implemented. Some of these are indicated by TODO comments, but 15 // those aren't comprehensive either. Second, many conditions cannot be 16 // checked statically. This pass does no dynamic instrumentation, so it 17 // can't check for all possible problems. 18 // 19 // Another limitation is that it assumes all code will be executed. A store 20 // through a null pointer in a basic block which is never reached is harmless, 21 // but this pass will warn about it anyway. This is the main reason why most 22 // of these checks live here instead of in the Verifier pass. 23 // 24 // Optimization passes may make conditions that this pass checks for more or 25 // less obvious. If an optimization pass appears to be introducing a warning, 26 // it may be that the optimization pass is merely exposing an existing 27 // condition in the code. 28 // 29 // This code may be run before instcombine. In many cases, instcombine checks 30 // for the same kinds of things and turns instructions with undefined behavior 31 // into unreachable (or equivalent). Because of this, this pass makes some 32 // effort to look through bitcasts and so on. 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "llvm/Analysis/Lint.h" 37 #include "llvm/ADT/APInt.h" 38 #include "llvm/ADT/ArrayRef.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/AliasAnalysis.h" 42 #include "llvm/Analysis/AssumptionCache.h" 43 #include "llvm/Analysis/ConstantFolding.h" 44 #include "llvm/Analysis/InstructionSimplify.h" 45 #include "llvm/Analysis/Loads.h" 46 #include "llvm/Analysis/MemoryLocation.h" 47 #include "llvm/Analysis/Passes.h" 48 #include "llvm/Analysis/TargetLibraryInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/IR/Argument.h" 51 #include "llvm/IR/BasicBlock.h" 52 #include "llvm/IR/Constant.h" 53 #include "llvm/IR/Constants.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/DerivedTypes.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/Function.h" 58 #include "llvm/IR/GlobalVariable.h" 59 #include "llvm/IR/InstVisitor.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/LegacyPassManager.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/PassManager.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/IR/Value.h" 69 #include "llvm/InitializePasses.h" 70 #include "llvm/Pass.h" 71 #include "llvm/Support/Casting.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Support/raw_ostream.h" 76 #include <cassert> 77 #include <cstdint> 78 #include <iterator> 79 #include <string> 80 81 using namespace llvm; 82 83 namespace { 84 namespace MemRef { 85 static const unsigned Read = 1; 86 static const unsigned Write = 2; 87 static const unsigned Callee = 4; 88 static const unsigned Branchee = 8; 89 } // end namespace MemRef 90 91 class Lint : public InstVisitor<Lint> { 92 friend class InstVisitor<Lint>; 93 94 void visitFunction(Function &F); 95 96 void visitCallBase(CallBase &CB); 97 void visitMemoryReference(Instruction &I, const MemoryLocation &Loc, 98 MaybeAlign Alignment, Type *Ty, unsigned Flags); 99 void visitEHBeginCatch(IntrinsicInst *II); 100 void visitEHEndCatch(IntrinsicInst *II); 101 102 void visitReturnInst(ReturnInst &I); 103 void visitLoadInst(LoadInst &I); 104 void visitStoreInst(StoreInst &I); 105 void visitXor(BinaryOperator &I); 106 void visitSub(BinaryOperator &I); 107 void visitLShr(BinaryOperator &I); 108 void visitAShr(BinaryOperator &I); 109 void visitShl(BinaryOperator &I); 110 void visitSDiv(BinaryOperator &I); 111 void visitUDiv(BinaryOperator &I); 112 void visitSRem(BinaryOperator &I); 113 void visitURem(BinaryOperator &I); 114 void visitAllocaInst(AllocaInst &I); 115 void visitVAArgInst(VAArgInst &I); 116 void visitIndirectBrInst(IndirectBrInst &I); 117 void visitExtractElementInst(ExtractElementInst &I); 118 void visitInsertElementInst(InsertElementInst &I); 119 void visitUnreachableInst(UnreachableInst &I); 120 121 Value *findValue(Value *V, bool OffsetOk) const; 122 Value *findValueImpl(Value *V, bool OffsetOk, 123 SmallPtrSetImpl<Value *> &Visited) const; 124 125 public: 126 Module *Mod; 127 const DataLayout *DL; 128 AliasAnalysis *AA; 129 AssumptionCache *AC; 130 DominatorTree *DT; 131 TargetLibraryInfo *TLI; 132 133 std::string Messages; 134 raw_string_ostream MessagesStr; 135 136 Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA, 137 AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI) 138 : Mod(Mod), DL(DL), AA(AA), AC(AC), DT(DT), TLI(TLI), 139 MessagesStr(Messages) {} 140 141 void WriteValues(ArrayRef<const Value *> Vs) { 142 for (const Value *V : Vs) { 143 if (!V) 144 continue; 145 if (isa<Instruction>(V)) { 146 MessagesStr << *V << '\n'; 147 } else { 148 V->printAsOperand(MessagesStr, true, Mod); 149 MessagesStr << '\n'; 150 } 151 } 152 } 153 154 /// A check failed, so printout out the condition and the message. 155 /// 156 /// This provides a nice place to put a breakpoint if you want to see why 157 /// something is not correct. 158 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; } 159 160 /// A check failed (with values to print). 161 /// 162 /// This calls the Message-only version so that the above is easier to set 163 /// a breakpoint on. 164 template <typename T1, typename... Ts> 165 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 166 CheckFailed(Message); 167 WriteValues({V1, Vs...}); 168 } 169 }; 170 } // end anonymous namespace 171 172 // Assert - We know that cond should be true, if not print an error message. 173 #define Assert(C, ...) \ 174 do { \ 175 if (!(C)) { \ 176 CheckFailed(__VA_ARGS__); \ 177 return; \ 178 } \ 179 } while (false) 180 181 void Lint::visitFunction(Function &F) { 182 // This isn't undefined behavior, it's just a little unusual, and it's a 183 // fairly common mistake to neglect to name a function. 184 Assert(F.hasName() || F.hasLocalLinkage(), 185 "Unusual: Unnamed function with non-local linkage", &F); 186 187 // TODO: Check for irreducible control flow. 188 } 189 190 void Lint::visitCallBase(CallBase &I) { 191 Value *Callee = I.getCalledOperand(); 192 193 visitMemoryReference(I, MemoryLocation::getAfter(Callee), None, nullptr, 194 MemRef::Callee); 195 196 if (Function *F = dyn_cast<Function>(findValue(Callee, 197 /*OffsetOk=*/false))) { 198 Assert(I.getCallingConv() == F->getCallingConv(), 199 "Undefined behavior: Caller and callee calling convention differ", 200 &I); 201 202 FunctionType *FT = F->getFunctionType(); 203 unsigned NumActualArgs = I.arg_size(); 204 205 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs 206 : FT->getNumParams() == NumActualArgs, 207 "Undefined behavior: Call argument count mismatches callee " 208 "argument count", 209 &I); 210 211 Assert(FT->getReturnType() == I.getType(), 212 "Undefined behavior: Call return type mismatches " 213 "callee return type", 214 &I); 215 216 // Check argument types (in case the callee was casted) and attributes. 217 // TODO: Verify that caller and callee attributes are compatible. 218 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end(); 219 auto AI = I.arg_begin(), AE = I.arg_end(); 220 for (; AI != AE; ++AI) { 221 Value *Actual = *AI; 222 if (PI != PE) { 223 Argument *Formal = &*PI++; 224 Assert(Formal->getType() == Actual->getType(), 225 "Undefined behavior: Call argument type mismatches " 226 "callee parameter type", 227 &I); 228 229 // Check that noalias arguments don't alias other arguments. This is 230 // not fully precise because we don't know the sizes of the dereferenced 231 // memory regions. 232 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) { 233 AttributeList PAL = I.getAttributes(); 234 unsigned ArgNo = 0; 235 for (auto BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) { 236 // Skip ByVal arguments since they will be memcpy'd to the callee's 237 // stack so we're not really passing the pointer anyway. 238 if (PAL.hasParamAttribute(ArgNo, Attribute::ByVal)) 239 continue; 240 // If both arguments are readonly, they have no dependence. 241 if (Formal->onlyReadsMemory() && I.onlyReadsMemory(ArgNo)) 242 continue; 243 if (AI != BI && (*BI)->getType()->isPointerTy()) { 244 AliasResult Result = AA->alias(*AI, *BI); 245 Assert(Result != MustAlias && Result != PartialAlias, 246 "Unusual: noalias argument aliases another argument", &I); 247 } 248 } 249 } 250 251 // Check that an sret argument points to valid memory. 252 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) { 253 Type *Ty = Formal->getParamStructRetType(); 254 MemoryLocation Loc( 255 Actual, LocationSize::precise(DL->getTypeStoreSize(Ty))); 256 visitMemoryReference(I, Loc, DL->getABITypeAlign(Ty), Ty, 257 MemRef::Read | MemRef::Write); 258 } 259 } 260 } 261 } 262 263 if (const auto *CI = dyn_cast<CallInst>(&I)) { 264 if (CI->isTailCall()) { 265 const AttributeList &PAL = CI->getAttributes(); 266 unsigned ArgNo = 0; 267 for (Value *Arg : I.args()) { 268 // Skip ByVal arguments since they will be memcpy'd to the callee's 269 // stack anyway. 270 if (PAL.hasParamAttribute(ArgNo++, Attribute::ByVal)) 271 continue; 272 Value *Obj = findValue(Arg, /*OffsetOk=*/true); 273 Assert(!isa<AllocaInst>(Obj), 274 "Undefined behavior: Call with \"tail\" keyword references " 275 "alloca", 276 &I); 277 } 278 } 279 } 280 281 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) 282 switch (II->getIntrinsicID()) { 283 default: 284 break; 285 286 // TODO: Check more intrinsics 287 288 case Intrinsic::memcpy: { 289 MemCpyInst *MCI = cast<MemCpyInst>(&I); 290 visitMemoryReference(I, MemoryLocation::getForDest(MCI), 291 MCI->getDestAlign(), nullptr, MemRef::Write); 292 visitMemoryReference(I, MemoryLocation::getForSource(MCI), 293 MCI->getSourceAlign(), nullptr, MemRef::Read); 294 295 // Check that the memcpy arguments don't overlap. The AliasAnalysis API 296 // isn't expressive enough for what we really want to do. Known partial 297 // overlap is not distinguished from the case where nothing is known. 298 auto Size = LocationSize::afterPointer(); 299 if (const ConstantInt *Len = 300 dyn_cast<ConstantInt>(findValue(MCI->getLength(), 301 /*OffsetOk=*/false))) 302 if (Len->getValue().isIntN(32)) 303 Size = LocationSize::precise(Len->getValue().getZExtValue()); 304 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) != 305 MustAlias, 306 "Undefined behavior: memcpy source and destination overlap", &I); 307 break; 308 } 309 case Intrinsic::memcpy_inline: { 310 MemCpyInlineInst *MCII = cast<MemCpyInlineInst>(&I); 311 const uint64_t Size = MCII->getLength()->getValue().getLimitedValue(); 312 visitMemoryReference(I, MemoryLocation::getForDest(MCII), 313 MCII->getDestAlign(), nullptr, MemRef::Write); 314 visitMemoryReference(I, MemoryLocation::getForSource(MCII), 315 MCII->getSourceAlign(), nullptr, MemRef::Read); 316 317 // Check that the memcpy arguments don't overlap. The AliasAnalysis API 318 // isn't expressive enough for what we really want to do. Known partial 319 // overlap is not distinguished from the case where nothing is known. 320 const LocationSize LS = LocationSize::precise(Size); 321 Assert(AA->alias(MCII->getSource(), LS, MCII->getDest(), LS) != MustAlias, 322 "Undefined behavior: memcpy source and destination overlap", &I); 323 break; 324 } 325 case Intrinsic::memmove: { 326 MemMoveInst *MMI = cast<MemMoveInst>(&I); 327 visitMemoryReference(I, MemoryLocation::getForDest(MMI), 328 MMI->getDestAlign(), nullptr, MemRef::Write); 329 visitMemoryReference(I, MemoryLocation::getForSource(MMI), 330 MMI->getSourceAlign(), nullptr, MemRef::Read); 331 break; 332 } 333 case Intrinsic::memset: { 334 MemSetInst *MSI = cast<MemSetInst>(&I); 335 visitMemoryReference(I, MemoryLocation::getForDest(MSI), 336 MSI->getDestAlign(), nullptr, MemRef::Write); 337 break; 338 } 339 340 case Intrinsic::vastart: 341 Assert(I.getParent()->getParent()->isVarArg(), 342 "Undefined behavior: va_start called in a non-varargs function", 343 &I); 344 345 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None, 346 nullptr, MemRef::Read | MemRef::Write); 347 break; 348 case Intrinsic::vacopy: 349 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None, 350 nullptr, MemRef::Write); 351 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 1, TLI), None, 352 nullptr, MemRef::Read); 353 break; 354 case Intrinsic::vaend: 355 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None, 356 nullptr, MemRef::Read | MemRef::Write); 357 break; 358 359 case Intrinsic::stackrestore: 360 // Stackrestore doesn't read or write memory, but it sets the 361 // stack pointer, which the compiler may read from or write to 362 // at any time, so check it for both readability and writeability. 363 visitMemoryReference(I, MemoryLocation::getForArgument(&I, 0, TLI), None, 364 nullptr, MemRef::Read | MemRef::Write); 365 break; 366 case Intrinsic::get_active_lane_mask: 367 if (auto *TripCount = dyn_cast<ConstantInt>(I.getArgOperand(1))) 368 Assert(!TripCount->isZero(), "get_active_lane_mask: operand #2 " 369 "must be greater than 0", &I); 370 break; 371 } 372 } 373 374 void Lint::visitReturnInst(ReturnInst &I) { 375 Function *F = I.getParent()->getParent(); 376 Assert(!F->doesNotReturn(), 377 "Unusual: Return statement in function with noreturn attribute", &I); 378 379 if (Value *V = I.getReturnValue()) { 380 Value *Obj = findValue(V, /*OffsetOk=*/true); 381 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I); 382 } 383 } 384 385 // TODO: Check that the reference is in bounds. 386 // TODO: Check readnone/readonly function attributes. 387 void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc, 388 MaybeAlign Align, Type *Ty, unsigned Flags) { 389 // If no memory is being referenced, it doesn't matter if the pointer 390 // is valid. 391 if (Loc.Size.isZero()) 392 return; 393 394 Value *Ptr = const_cast<Value *>(Loc.Ptr); 395 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true); 396 Assert(!isa<ConstantPointerNull>(UnderlyingObject), 397 "Undefined behavior: Null pointer dereference", &I); 398 Assert(!isa<UndefValue>(UnderlyingObject), 399 "Undefined behavior: Undef pointer dereference", &I); 400 Assert(!isa<ConstantInt>(UnderlyingObject) || 401 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(), 402 "Unusual: All-ones pointer dereference", &I); 403 Assert(!isa<ConstantInt>(UnderlyingObject) || 404 !cast<ConstantInt>(UnderlyingObject)->isOne(), 405 "Unusual: Address one pointer dereference", &I); 406 407 if (Flags & MemRef::Write) { 408 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject)) 409 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory", 410 &I); 411 Assert(!isa<Function>(UnderlyingObject) && 412 !isa<BlockAddress>(UnderlyingObject), 413 "Undefined behavior: Write to text section", &I); 414 } 415 if (Flags & MemRef::Read) { 416 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body", 417 &I); 418 Assert(!isa<BlockAddress>(UnderlyingObject), 419 "Undefined behavior: Load from block address", &I); 420 } 421 if (Flags & MemRef::Callee) { 422 Assert(!isa<BlockAddress>(UnderlyingObject), 423 "Undefined behavior: Call to block address", &I); 424 } 425 if (Flags & MemRef::Branchee) { 426 Assert(!isa<Constant>(UnderlyingObject) || 427 isa<BlockAddress>(UnderlyingObject), 428 "Undefined behavior: Branch to non-blockaddress", &I); 429 } 430 431 // Check for buffer overflows and misalignment. 432 // Only handles memory references that read/write something simple like an 433 // alloca instruction or a global variable. 434 int64_t Offset = 0; 435 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) { 436 // OK, so the access is to a constant offset from Ptr. Check that Ptr is 437 // something we can handle and if so extract the size of this base object 438 // along with its alignment. 439 uint64_t BaseSize = MemoryLocation::UnknownSize; 440 MaybeAlign BaseAlign; 441 442 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) { 443 Type *ATy = AI->getAllocatedType(); 444 if (!AI->isArrayAllocation() && ATy->isSized()) 445 BaseSize = DL->getTypeAllocSize(ATy); 446 BaseAlign = AI->getAlign(); 447 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { 448 // If the global may be defined differently in another compilation unit 449 // then don't warn about funky memory accesses. 450 if (GV->hasDefinitiveInitializer()) { 451 Type *GTy = GV->getValueType(); 452 if (GTy->isSized()) 453 BaseSize = DL->getTypeAllocSize(GTy); 454 BaseAlign = GV->getAlign(); 455 if (!BaseAlign && GTy->isSized()) 456 BaseAlign = DL->getABITypeAlign(GTy); 457 } 458 } 459 460 // Accesses from before the start or after the end of the object are not 461 // defined. 462 Assert(!Loc.Size.hasValue() || BaseSize == MemoryLocation::UnknownSize || 463 (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize), 464 "Undefined behavior: Buffer overflow", &I); 465 466 // Accesses that say that the memory is more aligned than it is are not 467 // defined. 468 if (!Align && Ty && Ty->isSized()) 469 Align = DL->getABITypeAlign(Ty); 470 if (BaseAlign && Align) 471 Assert(*Align <= commonAlignment(*BaseAlign, Offset), 472 "Undefined behavior: Memory reference address is misaligned", &I); 473 } 474 } 475 476 void Lint::visitLoadInst(LoadInst &I) { 477 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), I.getType(), 478 MemRef::Read); 479 } 480 481 void Lint::visitStoreInst(StoreInst &I) { 482 visitMemoryReference(I, MemoryLocation::get(&I), I.getAlign(), 483 I.getOperand(0)->getType(), MemRef::Write); 484 } 485 486 void Lint::visitXor(BinaryOperator &I) { 487 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)), 488 "Undefined result: xor(undef, undef)", &I); 489 } 490 491 void Lint::visitSub(BinaryOperator &I) { 492 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)), 493 "Undefined result: sub(undef, undef)", &I); 494 } 495 496 void Lint::visitLShr(BinaryOperator &I) { 497 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1), 498 /*OffsetOk=*/false))) 499 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 500 "Undefined result: Shift count out of range", &I); 501 } 502 503 void Lint::visitAShr(BinaryOperator &I) { 504 if (ConstantInt *CI = 505 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) 506 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 507 "Undefined result: Shift count out of range", &I); 508 } 509 510 void Lint::visitShl(BinaryOperator &I) { 511 if (ConstantInt *CI = 512 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) 513 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 514 "Undefined result: Shift count out of range", &I); 515 } 516 517 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, 518 AssumptionCache *AC) { 519 // Assume undef could be zero. 520 if (isa<UndefValue>(V)) 521 return true; 522 523 VectorType *VecTy = dyn_cast<VectorType>(V->getType()); 524 if (!VecTy) { 525 KnownBits Known = 526 computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT); 527 return Known.isZero(); 528 } 529 530 // Per-component check doesn't work with zeroinitializer 531 Constant *C = dyn_cast<Constant>(V); 532 if (!C) 533 return false; 534 535 if (C->isZeroValue()) 536 return true; 537 538 // For a vector, KnownZero will only be true if all values are zero, so check 539 // this per component 540 for (unsigned I = 0, N = cast<FixedVectorType>(VecTy)->getNumElements(); 541 I != N; ++I) { 542 Constant *Elem = C->getAggregateElement(I); 543 if (isa<UndefValue>(Elem)) 544 return true; 545 546 KnownBits Known = computeKnownBits(Elem, DL); 547 if (Known.isZero()) 548 return true; 549 } 550 551 return false; 552 } 553 554 void Lint::visitSDiv(BinaryOperator &I) { 555 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), 556 "Undefined behavior: Division by zero", &I); 557 } 558 559 void Lint::visitUDiv(BinaryOperator &I) { 560 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), 561 "Undefined behavior: Division by zero", &I); 562 } 563 564 void Lint::visitSRem(BinaryOperator &I) { 565 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), 566 "Undefined behavior: Division by zero", &I); 567 } 568 569 void Lint::visitURem(BinaryOperator &I) { 570 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC), 571 "Undefined behavior: Division by zero", &I); 572 } 573 574 void Lint::visitAllocaInst(AllocaInst &I) { 575 if (isa<ConstantInt>(I.getArraySize())) 576 // This isn't undefined behavior, it's just an obvious pessimization. 577 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(), 578 "Pessimization: Static alloca outside of entry block", &I); 579 580 // TODO: Check for an unusual size (MSB set?) 581 } 582 583 void Lint::visitVAArgInst(VAArgInst &I) { 584 visitMemoryReference(I, MemoryLocation::get(&I), None, nullptr, 585 MemRef::Read | MemRef::Write); 586 } 587 588 void Lint::visitIndirectBrInst(IndirectBrInst &I) { 589 visitMemoryReference(I, MemoryLocation::getAfter(I.getAddress()), None, 590 nullptr, MemRef::Branchee); 591 592 Assert(I.getNumDestinations() != 0, 593 "Undefined behavior: indirectbr with no destinations", &I); 594 } 595 596 void Lint::visitExtractElementInst(ExtractElementInst &I) { 597 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(), 598 /*OffsetOk=*/false))) 599 Assert( 600 CI->getValue().ult( 601 cast<FixedVectorType>(I.getVectorOperandType())->getNumElements()), 602 "Undefined result: extractelement index out of range", &I); 603 } 604 605 void Lint::visitInsertElementInst(InsertElementInst &I) { 606 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2), 607 /*OffsetOk=*/false))) 608 Assert(CI->getValue().ult( 609 cast<FixedVectorType>(I.getType())->getNumElements()), 610 "Undefined result: insertelement index out of range", &I); 611 } 612 613 void Lint::visitUnreachableInst(UnreachableInst &I) { 614 // This isn't undefined behavior, it's merely suspicious. 615 Assert(&I == &I.getParent()->front() || 616 std::prev(I.getIterator())->mayHaveSideEffects(), 617 "Unusual: unreachable immediately preceded by instruction without " 618 "side effects", 619 &I); 620 } 621 622 /// findValue - Look through bitcasts and simple memory reference patterns 623 /// to identify an equivalent, but more informative, value. If OffsetOk 624 /// is true, look through getelementptrs with non-zero offsets too. 625 /// 626 /// Most analysis passes don't require this logic, because instcombine 627 /// will simplify most of these kinds of things away. But it's a goal of 628 /// this Lint pass to be useful even on non-optimized IR. 629 Value *Lint::findValue(Value *V, bool OffsetOk) const { 630 SmallPtrSet<Value *, 4> Visited; 631 return findValueImpl(V, OffsetOk, Visited); 632 } 633 634 /// findValueImpl - Implementation helper for findValue. 635 Value *Lint::findValueImpl(Value *V, bool OffsetOk, 636 SmallPtrSetImpl<Value *> &Visited) const { 637 // Detect self-referential values. 638 if (!Visited.insert(V).second) 639 return UndefValue::get(V->getType()); 640 641 // TODO: Look through sext or zext cast, when the result is known to 642 // be interpreted as signed or unsigned, respectively. 643 // TODO: Look through eliminable cast pairs. 644 // TODO: Look through calls with unique return values. 645 // TODO: Look through vector insert/extract/shuffle. 646 V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts(); 647 if (LoadInst *L = dyn_cast<LoadInst>(V)) { 648 BasicBlock::iterator BBI = L->getIterator(); 649 BasicBlock *BB = L->getParent(); 650 SmallPtrSet<BasicBlock *, 4> VisitedBlocks; 651 for (;;) { 652 if (!VisitedBlocks.insert(BB).second) 653 break; 654 if (Value *U = 655 FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA)) 656 return findValueImpl(U, OffsetOk, Visited); 657 if (BBI != BB->begin()) 658 break; 659 BB = BB->getUniquePredecessor(); 660 if (!BB) 661 break; 662 BBI = BB->end(); 663 } 664 } else if (PHINode *PN = dyn_cast<PHINode>(V)) { 665 if (Value *W = PN->hasConstantValue()) 666 return findValueImpl(W, OffsetOk, Visited); 667 } else if (CastInst *CI = dyn_cast<CastInst>(V)) { 668 if (CI->isNoopCast(*DL)) 669 return findValueImpl(CI->getOperand(0), OffsetOk, Visited); 670 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) { 671 if (Value *W = 672 FindInsertedValue(Ex->getAggregateOperand(), Ex->getIndices())) 673 if (W != V) 674 return findValueImpl(W, OffsetOk, Visited); 675 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 676 // Same as above, but for ConstantExpr instead of Instruction. 677 if (Instruction::isCast(CE->getOpcode())) { 678 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()), 679 CE->getOperand(0)->getType(), CE->getType(), 680 *DL)) 681 return findValueImpl(CE->getOperand(0), OffsetOk, Visited); 682 } else if (CE->getOpcode() == Instruction::ExtractValue) { 683 ArrayRef<unsigned> Indices = CE->getIndices(); 684 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices)) 685 if (W != V) 686 return findValueImpl(W, OffsetOk, Visited); 687 } 688 } 689 690 // As a last resort, try SimplifyInstruction or constant folding. 691 if (Instruction *Inst = dyn_cast<Instruction>(V)) { 692 if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC})) 693 return findValueImpl(W, OffsetOk, Visited); 694 } else if (auto *C = dyn_cast<Constant>(V)) { 695 Value *W = ConstantFoldConstant(C, *DL, TLI); 696 if (W != V) 697 return findValueImpl(W, OffsetOk, Visited); 698 } 699 700 return V; 701 } 702 703 PreservedAnalyses LintPass::run(Function &F, FunctionAnalysisManager &AM) { 704 auto *Mod = F.getParent(); 705 auto *DL = &F.getParent()->getDataLayout(); 706 auto *AA = &AM.getResult<AAManager>(F); 707 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 708 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 709 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(F); 710 Lint L(Mod, DL, AA, AC, DT, TLI); 711 L.visit(F); 712 dbgs() << L.MessagesStr.str(); 713 return PreservedAnalyses::all(); 714 } 715 716 class LintLegacyPass : public FunctionPass { 717 public: 718 static char ID; // Pass identification, replacement for typeid 719 LintLegacyPass() : FunctionPass(ID) { 720 initializeLintLegacyPassPass(*PassRegistry::getPassRegistry()); 721 } 722 723 bool runOnFunction(Function &F) override; 724 725 void getAnalysisUsage(AnalysisUsage &AU) const override { 726 AU.setPreservesAll(); 727 AU.addRequired<AAResultsWrapperPass>(); 728 AU.addRequired<AssumptionCacheTracker>(); 729 AU.addRequired<TargetLibraryInfoWrapperPass>(); 730 AU.addRequired<DominatorTreeWrapperPass>(); 731 } 732 void print(raw_ostream &O, const Module *M) const override {} 733 }; 734 735 char LintLegacyPass::ID = 0; 736 INITIALIZE_PASS_BEGIN(LintLegacyPass, "lint", "Statically lint-checks LLVM IR", 737 false, true) 738 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 739 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 740 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 741 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 742 INITIALIZE_PASS_END(LintLegacyPass, "lint", "Statically lint-checks LLVM IR", 743 false, true) 744 745 bool LintLegacyPass::runOnFunction(Function &F) { 746 auto *Mod = F.getParent(); 747 auto *DL = &F.getParent()->getDataLayout(); 748 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 749 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 750 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 751 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 752 Lint L(Mod, DL, AA, AC, DT, TLI); 753 L.visit(F); 754 dbgs() << L.MessagesStr.str(); 755 return false; 756 } 757 758 //===----------------------------------------------------------------------===// 759 // Implement the public interfaces to this file... 760 //===----------------------------------------------------------------------===// 761 762 FunctionPass *llvm::createLintLegacyPassPass() { return new LintLegacyPass(); } 763 764 /// lintFunction - Check a function for errors, printing messages on stderr. 765 /// 766 void llvm::lintFunction(const Function &f) { 767 Function &F = const_cast<Function &>(f); 768 assert(!F.isDeclaration() && "Cannot lint external functions"); 769 770 legacy::FunctionPassManager FPM(F.getParent()); 771 auto *V = new LintLegacyPass(); 772 FPM.add(V); 773 FPM.run(F); 774 } 775 776 /// lintModule - Check a module for errors, printing messages on stderr. 777 /// 778 void llvm::lintModule(const Module &M) { 779 legacy::PassManager PM; 780 auto *V = new LintLegacyPass(); 781 PM.add(V); 782 PM.run(const_cast<Module &>(M)); 783 } 784