1//===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass statically checks for common and easily-identified constructs 11// which produce undefined or likely unintended behavior in LLVM IR. 12// 13// It is not a guarantee of correctness, in two ways. First, it isn't 14// comprehensive. There are checks which could be done statically which are 15// not yet implemented. Some of these are indicated by TODO comments, but 16// those aren't comprehensive either. Second, many conditions cannot be 17// checked statically. This pass does no dynamic instrumentation, so it 18// can't check for all possible problems. 19// 20// Another limitation is that it assumes all code will be executed. A store 21// through a null pointer in a basic block which is never reached is harmless, 22// but this pass will warn about it anyway. This is the main reason why most 23// of these checks live here instead of in the Verifier pass. 24// 25// Optimization passes may make conditions that this pass checks for more or 26// less obvious. If an optimization pass appears to be introducing a warning, 27// it may be that the optimization pass is merely exposing an existing 28// condition in the code. 29// 30// This code may be run before instcombine. In many cases, instcombine checks 31// for the same kinds of things and turns instructions with undefined behavior 32// into unreachable (or equivalent). Because of this, this pass makes some 33// effort to look through bitcasts and so on. 34// 35//===----------------------------------------------------------------------===// 36 37#include "llvm/Analysis/Passes.h" 38#include "llvm/Analysis/AliasAnalysis.h" 39#include "llvm/Analysis/InstructionSimplify.h" 40#include "llvm/Analysis/ConstantFolding.h" 41#include "llvm/Analysis/Dominators.h" 42#include "llvm/Analysis/Lint.h" 43#include "llvm/Analysis/Loads.h" 44#include "llvm/Analysis/ValueTracking.h" 45#include "llvm/Assembly/Writer.h" 46#include "llvm/Target/TargetData.h" 47#include "llvm/Pass.h" 48#include "llvm/PassManager.h" 49#include "llvm/IntrinsicInst.h" 50#include "llvm/Function.h" 51#include "llvm/Support/CallSite.h" 52#include "llvm/Support/Debug.h" 53#include "llvm/Support/InstVisitor.h" 54#include "llvm/Support/raw_ostream.h" 55#include "llvm/ADT/STLExtras.h" 56using namespace llvm; 57 58namespace { 59 namespace MemRef { 60 static unsigned Read = 1; 61 static unsigned Write = 2; 62 static unsigned Callee = 4; 63 static unsigned Branchee = 8; 64 } 65 66 class Lint : public FunctionPass, public InstVisitor<Lint> { 67 friend class InstVisitor<Lint>; 68 69 void visitFunction(Function &F); 70 71 void visitCallSite(CallSite CS); 72 void visitMemoryReference(Instruction &I, Value *Ptr, 73 uint64_t Size, unsigned Align, 74 Type *Ty, unsigned Flags); 75 76 void visitCallInst(CallInst &I); 77 void visitInvokeInst(InvokeInst &I); 78 void visitReturnInst(ReturnInst &I); 79 void visitLoadInst(LoadInst &I); 80 void visitStoreInst(StoreInst &I); 81 void visitXor(BinaryOperator &I); 82 void visitSub(BinaryOperator &I); 83 void visitLShr(BinaryOperator &I); 84 void visitAShr(BinaryOperator &I); 85 void visitShl(BinaryOperator &I); 86 void visitSDiv(BinaryOperator &I); 87 void visitUDiv(BinaryOperator &I); 88 void visitSRem(BinaryOperator &I); 89 void visitURem(BinaryOperator &I); 90 void visitAllocaInst(AllocaInst &I); 91 void visitVAArgInst(VAArgInst &I); 92 void visitIndirectBrInst(IndirectBrInst &I); 93 void visitExtractElementInst(ExtractElementInst &I); 94 void visitInsertElementInst(InsertElementInst &I); 95 void visitUnreachableInst(UnreachableInst &I); 96 97 Value *findValue(Value *V, bool OffsetOk) const; 98 Value *findValueImpl(Value *V, bool OffsetOk, 99 SmallPtrSet<Value *, 4> &Visited) const; 100 101 public: 102 Module *Mod; 103 AliasAnalysis *AA; 104 DominatorTree *DT; 105 TargetData *TD; 106 107 std::string Messages; 108 raw_string_ostream MessagesStr; 109 110 static char ID; // Pass identification, replacement for typeid 111 Lint() : FunctionPass(ID), MessagesStr(Messages) { 112 initializeLintPass(*PassRegistry::getPassRegistry()); 113 } 114 115 virtual bool runOnFunction(Function &F); 116 117 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 118 AU.setPreservesAll(); 119 AU.addRequired<AliasAnalysis>(); 120 AU.addRequired<DominatorTree>(); 121 } 122 virtual void print(raw_ostream &O, const Module *M) const {} 123 124 void WriteValue(const Value *V) { 125 if (!V) return; 126 if (isa<Instruction>(V)) { 127 MessagesStr << *V << '\n'; 128 } else { 129 WriteAsOperand(MessagesStr, V, true, Mod); 130 MessagesStr << '\n'; 131 } 132 } 133 134 // CheckFailed - A check failed, so print out the condition and the message 135 // that failed. This provides a nice place to put a breakpoint if you want 136 // to see why something is not correct. 137 void CheckFailed(const Twine &Message, 138 const Value *V1 = 0, const Value *V2 = 0, 139 const Value *V3 = 0, const Value *V4 = 0) { 140 MessagesStr << Message.str() << "\n"; 141 WriteValue(V1); 142 WriteValue(V2); 143 WriteValue(V3); 144 WriteValue(V4); 145 } 146 }; 147} 148 149char Lint::ID = 0; 150INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR", 151 false, true) 152INITIALIZE_PASS_DEPENDENCY(DominatorTree) 153INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 154INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR", 155 false, true) 156 157// Assert - We know that cond should be true, if not print an error message. 158#define Assert(C, M) \ 159 do { if (!(C)) { CheckFailed(M); return; } } while (0) 160#define Assert1(C, M, V1) \ 161 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) 162#define Assert2(C, M, V1, V2) \ 163 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) 164#define Assert3(C, M, V1, V2, V3) \ 165 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0) 166#define Assert4(C, M, V1, V2, V3, V4) \ 167 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0) 168 169// Lint::run - This is the main Analysis entry point for a 170// function. 171// 172bool Lint::runOnFunction(Function &F) { 173 Mod = F.getParent(); 174 AA = &getAnalysis<AliasAnalysis>(); 175 DT = &getAnalysis<DominatorTree>(); 176 TD = getAnalysisIfAvailable<TargetData>(); 177 visit(F); 178 dbgs() << MessagesStr.str(); 179 Messages.clear(); 180 return false; 181} 182 183void Lint::visitFunction(Function &F) { 184 // This isn't undefined behavior, it's just a little unusual, and it's a 185 // fairly common mistake to neglect to name a function. 186 Assert1(F.hasName() || F.hasLocalLinkage(), 187 "Unusual: Unnamed function with non-local linkage", &F); 188 189 // TODO: Check for irreducible control flow. 190} 191 192void Lint::visitCallSite(CallSite CS) { 193 Instruction &I = *CS.getInstruction(); 194 Value *Callee = CS.getCalledValue(); 195 196 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize, 197 0, 0, MemRef::Callee); 198 199 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) { 200 Assert1(CS.getCallingConv() == F->getCallingConv(), 201 "Undefined behavior: Caller and callee calling convention differ", 202 &I); 203 204 FunctionType *FT = F->getFunctionType(); 205 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin()); 206 207 Assert1(FT->isVarArg() ? 208 FT->getNumParams() <= NumActualArgs : 209 FT->getNumParams() == NumActualArgs, 210 "Undefined behavior: Call argument count mismatches callee " 211 "argument count", &I); 212 213 Assert1(FT->getReturnType() == I.getType(), 214 "Undefined behavior: Call return type mismatches " 215 "callee return type", &I); 216 217 // Check argument types (in case the callee was casted) and attributes. 218 // TODO: Verify that caller and callee attributes are compatible. 219 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end(); 220 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end(); 221 for (; AI != AE; ++AI) { 222 Value *Actual = *AI; 223 if (PI != PE) { 224 Argument *Formal = PI++; 225 Assert1(Formal->getType() == Actual->getType(), 226 "Undefined behavior: Call argument type mismatches " 227 "callee parameter type", &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 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) 234 if (AI != BI && (*BI)->getType()->isPointerTy()) { 235 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI); 236 Assert1(Result != AliasAnalysis::MustAlias && 237 Result != AliasAnalysis::PartialAlias, 238 "Unusual: noalias argument aliases another argument", &I); 239 } 240 241 // Check that an sret argument points to valid memory. 242 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) { 243 Type *Ty = 244 cast<PointerType>(Formal->getType())->getElementType(); 245 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty), 246 TD ? TD->getABITypeAlignment(Ty) : 0, 247 Ty, MemRef::Read | MemRef::Write); 248 } 249 } 250 } 251 } 252 253 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall()) 254 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end(); 255 AI != AE; ++AI) { 256 Value *Obj = findValue(*AI, /*OffsetOk=*/true); 257 Assert1(!isa<AllocaInst>(Obj), 258 "Undefined behavior: Call with \"tail\" keyword references " 259 "alloca", &I); 260 } 261 262 263 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) 264 switch (II->getIntrinsicID()) { 265 default: break; 266 267 // TODO: Check more intrinsics 268 269 case Intrinsic::memcpy: { 270 MemCpyInst *MCI = cast<MemCpyInst>(&I); 271 // TODO: If the size is known, use it. 272 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize, 273 MCI->getAlignment(), 0, 274 MemRef::Write); 275 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize, 276 MCI->getAlignment(), 0, 277 MemRef::Read); 278 279 // Check that the memcpy arguments don't overlap. The AliasAnalysis API 280 // isn't expressive enough for what we really want to do. Known partial 281 // overlap is not distinguished from the case where nothing is known. 282 uint64_t Size = 0; 283 if (const ConstantInt *Len = 284 dyn_cast<ConstantInt>(findValue(MCI->getLength(), 285 /*OffsetOk=*/false))) 286 if (Len->getValue().isIntN(32)) 287 Size = Len->getValue().getZExtValue(); 288 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) != 289 AliasAnalysis::MustAlias, 290 "Undefined behavior: memcpy source and destination overlap", &I); 291 break; 292 } 293 case Intrinsic::memmove: { 294 MemMoveInst *MMI = cast<MemMoveInst>(&I); 295 // TODO: If the size is known, use it. 296 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize, 297 MMI->getAlignment(), 0, 298 MemRef::Write); 299 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize, 300 MMI->getAlignment(), 0, 301 MemRef::Read); 302 break; 303 } 304 case Intrinsic::memset: { 305 MemSetInst *MSI = cast<MemSetInst>(&I); 306 // TODO: If the size is known, use it. 307 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize, 308 MSI->getAlignment(), 0, 309 MemRef::Write); 310 break; 311 } 312 313 case Intrinsic::vastart: 314 Assert1(I.getParent()->getParent()->isVarArg(), 315 "Undefined behavior: va_start called in a non-varargs function", 316 &I); 317 318 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize, 319 0, 0, MemRef::Read | MemRef::Write); 320 break; 321 case Intrinsic::vacopy: 322 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize, 323 0, 0, MemRef::Write); 324 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize, 325 0, 0, MemRef::Read); 326 break; 327 case Intrinsic::vaend: 328 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize, 329 0, 0, MemRef::Read | MemRef::Write); 330 break; 331 332 case Intrinsic::stackrestore: 333 // Stackrestore doesn't read or write memory, but it sets the 334 // stack pointer, which the compiler may read from or write to 335 // at any time, so check it for both readability and writeability. 336 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize, 337 0, 0, MemRef::Read | MemRef::Write); 338 break; 339 } 340} 341 342void Lint::visitCallInst(CallInst &I) { 343 return visitCallSite(&I); 344} 345 346void Lint::visitInvokeInst(InvokeInst &I) { 347 return visitCallSite(&I); 348} 349 350void Lint::visitReturnInst(ReturnInst &I) { 351 Function *F = I.getParent()->getParent(); 352 Assert1(!F->doesNotReturn(), 353 "Unusual: Return statement in function with noreturn attribute", 354 &I); 355 356 if (Value *V = I.getReturnValue()) { 357 Value *Obj = findValue(V, /*OffsetOk=*/true); 358 Assert1(!isa<AllocaInst>(Obj), 359 "Unusual: Returning alloca value", &I); 360 } 361} 362 363// TODO: Check that the reference is in bounds. 364// TODO: Check readnone/readonly function attributes. 365void Lint::visitMemoryReference(Instruction &I, 366 Value *Ptr, uint64_t Size, unsigned Align, 367 Type *Ty, unsigned Flags) { 368 // If no memory is being referenced, it doesn't matter if the pointer 369 // is valid. 370 if (Size == 0) 371 return; 372 373 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true); 374 Assert1(!isa<ConstantPointerNull>(UnderlyingObject), 375 "Undefined behavior: Null pointer dereference", &I); 376 Assert1(!isa<UndefValue>(UnderlyingObject), 377 "Undefined behavior: Undef pointer dereference", &I); 378 Assert1(!isa<ConstantInt>(UnderlyingObject) || 379 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(), 380 "Unusual: All-ones pointer dereference", &I); 381 Assert1(!isa<ConstantInt>(UnderlyingObject) || 382 !cast<ConstantInt>(UnderlyingObject)->isOne(), 383 "Unusual: Address one pointer dereference", &I); 384 385 if (Flags & MemRef::Write) { 386 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject)) 387 Assert1(!GV->isConstant(), 388 "Undefined behavior: Write to read-only memory", &I); 389 Assert1(!isa<Function>(UnderlyingObject) && 390 !isa<BlockAddress>(UnderlyingObject), 391 "Undefined behavior: Write to text section", &I); 392 } 393 if (Flags & MemRef::Read) { 394 Assert1(!isa<Function>(UnderlyingObject), 395 "Unusual: Load from function body", &I); 396 Assert1(!isa<BlockAddress>(UnderlyingObject), 397 "Undefined behavior: Load from block address", &I); 398 } 399 if (Flags & MemRef::Callee) { 400 Assert1(!isa<BlockAddress>(UnderlyingObject), 401 "Undefined behavior: Call to block address", &I); 402 } 403 if (Flags & MemRef::Branchee) { 404 Assert1(!isa<Constant>(UnderlyingObject) || 405 isa<BlockAddress>(UnderlyingObject), 406 "Undefined behavior: Branch to non-blockaddress", &I); 407 } 408 409 if (TD) { 410 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty); 411 412 if (Align != 0) { 413 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType()); 414 APInt Mask = APInt::getAllOnesValue(BitWidth), 415 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 416 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD); 417 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))), 418 "Undefined behavior: Memory reference address is misaligned", &I); 419 } 420 } 421} 422 423void Lint::visitLoadInst(LoadInst &I) { 424 visitMemoryReference(I, I.getPointerOperand(), 425 AA->getTypeStoreSize(I.getType()), I.getAlignment(), 426 I.getType(), MemRef::Read); 427} 428 429void Lint::visitStoreInst(StoreInst &I) { 430 visitMemoryReference(I, I.getPointerOperand(), 431 AA->getTypeStoreSize(I.getOperand(0)->getType()), 432 I.getAlignment(), 433 I.getOperand(0)->getType(), MemRef::Write); 434} 435 436void Lint::visitXor(BinaryOperator &I) { 437 Assert1(!isa<UndefValue>(I.getOperand(0)) || 438 !isa<UndefValue>(I.getOperand(1)), 439 "Undefined result: xor(undef, undef)", &I); 440} 441 442void Lint::visitSub(BinaryOperator &I) { 443 Assert1(!isa<UndefValue>(I.getOperand(0)) || 444 !isa<UndefValue>(I.getOperand(1)), 445 "Undefined result: sub(undef, undef)", &I); 446} 447 448void Lint::visitLShr(BinaryOperator &I) { 449 if (ConstantInt *CI = 450 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) 451 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 452 "Undefined result: Shift count out of range", &I); 453} 454 455void Lint::visitAShr(BinaryOperator &I) { 456 if (ConstantInt *CI = 457 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) 458 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 459 "Undefined result: Shift count out of range", &I); 460} 461 462void Lint::visitShl(BinaryOperator &I) { 463 if (ConstantInt *CI = 464 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false))) 465 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()), 466 "Undefined result: Shift count out of range", &I); 467} 468 469static bool isZero(Value *V, TargetData *TD) { 470 // Assume undef could be zero. 471 if (isa<UndefValue>(V)) return true; 472 473 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); 474 APInt Mask = APInt::getAllOnesValue(BitWidth), 475 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 476 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD); 477 return KnownZero.isAllOnesValue(); 478} 479 480void Lint::visitSDiv(BinaryOperator &I) { 481 Assert1(!isZero(I.getOperand(1), TD), 482 "Undefined behavior: Division by zero", &I); 483} 484 485void Lint::visitUDiv(BinaryOperator &I) { 486 Assert1(!isZero(I.getOperand(1), TD), 487 "Undefined behavior: Division by zero", &I); 488} 489 490void Lint::visitSRem(BinaryOperator &I) { 491 Assert1(!isZero(I.getOperand(1), TD), 492 "Undefined behavior: Division by zero", &I); 493} 494 495void Lint::visitURem(BinaryOperator &I) { 496 Assert1(!isZero(I.getOperand(1), TD), 497 "Undefined behavior: Division by zero", &I); 498} 499 500void Lint::visitAllocaInst(AllocaInst &I) { 501 if (isa<ConstantInt>(I.getArraySize())) 502 // This isn't undefined behavior, it's just an obvious pessimization. 503 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(), 504 "Pessimization: Static alloca outside of entry block", &I); 505 506 // TODO: Check for an unusual size (MSB set?) 507} 508 509void Lint::visitVAArgInst(VAArgInst &I) { 510 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0, 0, 511 MemRef::Read | MemRef::Write); 512} 513 514void Lint::visitIndirectBrInst(IndirectBrInst &I) { 515 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0, 0, 516 MemRef::Branchee); 517 518 Assert1(I.getNumDestinations() != 0, 519 "Undefined behavior: indirectbr with no destinations", &I); 520} 521 522void Lint::visitExtractElementInst(ExtractElementInst &I) { 523 if (ConstantInt *CI = 524 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(), 525 /*OffsetOk=*/false))) 526 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()), 527 "Undefined result: extractelement index out of range", &I); 528} 529 530void Lint::visitInsertElementInst(InsertElementInst &I) { 531 if (ConstantInt *CI = 532 dyn_cast<ConstantInt>(findValue(I.getOperand(2), 533 /*OffsetOk=*/false))) 534 Assert1(CI->getValue().ult(I.getType()->getNumElements()), 535 "Undefined result: insertelement index out of range", &I); 536} 537 538void Lint::visitUnreachableInst(UnreachableInst &I) { 539 // This isn't undefined behavior, it's merely suspicious. 540 Assert1(&I == I.getParent()->begin() || 541 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(), 542 "Unusual: unreachable immediately preceded by instruction without " 543 "side effects", &I); 544} 545 546/// findValue - Look through bitcasts and simple memory reference patterns 547/// to identify an equivalent, but more informative, value. If OffsetOk 548/// is true, look through getelementptrs with non-zero offsets too. 549/// 550/// Most analysis passes don't require this logic, because instcombine 551/// will simplify most of these kinds of things away. But it's a goal of 552/// this Lint pass to be useful even on non-optimized IR. 553Value *Lint::findValue(Value *V, bool OffsetOk) const { 554 SmallPtrSet<Value *, 4> Visited; 555 return findValueImpl(V, OffsetOk, Visited); 556} 557 558/// findValueImpl - Implementation helper for findValue. 559Value *Lint::findValueImpl(Value *V, bool OffsetOk, 560 SmallPtrSet<Value *, 4> &Visited) const { 561 // Detect self-referential values. 562 if (!Visited.insert(V)) 563 return UndefValue::get(V->getType()); 564 565 // TODO: Look through sext or zext cast, when the result is known to 566 // be interpreted as signed or unsigned, respectively. 567 // TODO: Look through eliminable cast pairs. 568 // TODO: Look through calls with unique return values. 569 // TODO: Look through vector insert/extract/shuffle. 570 V = OffsetOk ? GetUnderlyingObject(V, TD) : V->stripPointerCasts(); 571 if (LoadInst *L = dyn_cast<LoadInst>(V)) { 572 BasicBlock::iterator BBI = L; 573 BasicBlock *BB = L->getParent(); 574 SmallPtrSet<BasicBlock *, 4> VisitedBlocks; 575 for (;;) { 576 if (!VisitedBlocks.insert(BB)) break; 577 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(), 578 BB, BBI, 6, AA)) 579 return findValueImpl(U, OffsetOk, Visited); 580 if (BBI != BB->begin()) break; 581 BB = BB->getUniquePredecessor(); 582 if (!BB) break; 583 BBI = BB->end(); 584 } 585 } else if (PHINode *PN = dyn_cast<PHINode>(V)) { 586 if (Value *W = PN->hasConstantValue()) 587 if (W != V) 588 return findValueImpl(W, OffsetOk, Visited); 589 } else if (CastInst *CI = dyn_cast<CastInst>(V)) { 590 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) : 591 Type::getInt64Ty(V->getContext()))) 592 return findValueImpl(CI->getOperand(0), OffsetOk, Visited); 593 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) { 594 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(), 595 Ex->getIndices())) 596 if (W != V) 597 return findValueImpl(W, OffsetOk, Visited); 598 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 599 // Same as above, but for ConstantExpr instead of Instruction. 600 if (Instruction::isCast(CE->getOpcode())) { 601 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()), 602 CE->getOperand(0)->getType(), 603 CE->getType(), 604 TD ? TD->getIntPtrType(V->getContext()) : 605 Type::getInt64Ty(V->getContext()))) 606 return findValueImpl(CE->getOperand(0), OffsetOk, Visited); 607 } else if (CE->getOpcode() == Instruction::ExtractValue) { 608 ArrayRef<unsigned> Indices = CE->getIndices(); 609 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices)) 610 if (W != V) 611 return findValueImpl(W, OffsetOk, Visited); 612 } 613 } 614 615 // As a last resort, try SimplifyInstruction or constant folding. 616 if (Instruction *Inst = dyn_cast<Instruction>(V)) { 617 if (Value *W = SimplifyInstruction(Inst, TD, DT)) 618 return findValueImpl(W, OffsetOk, Visited); 619 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 620 if (Value *W = ConstantFoldConstantExpression(CE, TD)) 621 if (W != V) 622 return findValueImpl(W, OffsetOk, Visited); 623 } 624 625 return V; 626} 627 628//===----------------------------------------------------------------------===// 629// Implement the public interfaces to this file... 630//===----------------------------------------------------------------------===// 631 632FunctionPass *llvm::createLintPass() { 633 return new Lint(); 634} 635 636/// lintFunction - Check a function for errors, printing messages on stderr. 637/// 638void llvm::lintFunction(const Function &f) { 639 Function &F = const_cast<Function&>(f); 640 assert(!F.isDeclaration() && "Cannot lint external functions"); 641 642 FunctionPassManager FPM(F.getParent()); 643 Lint *V = new Lint(); 644 FPM.add(V); 645 FPM.run(F); 646} 647 648/// lintModule - Check a module for errors, printing messages on stderr. 649/// 650void llvm::lintModule(const Module &M) { 651 PassManager PM; 652 Lint *V = new Lint(); 653 PM.add(V); 654 PM.run(const_cast<Module&>(M)); 655} 656