1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass statically checks for common and easily-identified constructs
11 // which produce undefined or likely unintended behavior in LLVM IR.
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.
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.
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.
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.
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Analysis/Passes.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/Analysis/InstructionSimplify.h"
39 #include "llvm/Analysis/ConstantFolding.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Analysis/Lint.h"
42 #include "llvm/Analysis/Loads.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Assembly/Writer.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Pass.h"
47 #include "llvm/PassManager.h"
48 #include "llvm/IntrinsicInst.h"
49 #include "llvm/Function.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/InstVisitor.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/ADT/STLExtras.h"
59 static unsigned Read = 1;
60 static unsigned Write = 2;
61 static unsigned Callee = 4;
62 static unsigned Branchee = 8;
65 class Lint : public FunctionPass, public InstVisitor<Lint> {
66 friend class InstVisitor<Lint>;
68 void visitFunction(Function &F);
70 void visitCallSite(CallSite CS);
71 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
72 const Type *Ty, unsigned Flags);
74 void visitCallInst(CallInst &I);
75 void visitInvokeInst(InvokeInst &I);
76 void visitReturnInst(ReturnInst &I);
77 void visitLoadInst(LoadInst &I);
78 void visitStoreInst(StoreInst &I);
79 void visitXor(BinaryOperator &I);
80 void visitSub(BinaryOperator &I);
81 void visitLShr(BinaryOperator &I);
82 void visitAShr(BinaryOperator &I);
83 void visitShl(BinaryOperator &I);
84 void visitSDiv(BinaryOperator &I);
85 void visitUDiv(BinaryOperator &I);
86 void visitSRem(BinaryOperator &I);
87 void visitURem(BinaryOperator &I);
88 void visitAllocaInst(AllocaInst &I);
89 void visitVAArgInst(VAArgInst &I);
90 void visitIndirectBrInst(IndirectBrInst &I);
91 void visitExtractElementInst(ExtractElementInst &I);
92 void visitInsertElementInst(InsertElementInst &I);
93 void visitUnreachableInst(UnreachableInst &I);
95 Value *findValue(Value *V, bool OffsetOk) const;
103 std::string Messages;
104 raw_string_ostream MessagesStr;
106 static char ID; // Pass identification, replacement for typeid
107 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
109 virtual bool runOnFunction(Function &F);
111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.setPreservesAll();
113 AU.addRequired<AliasAnalysis>();
114 AU.addRequired<DominatorTree>();
116 virtual void print(raw_ostream &O, const Module *M) const {}
118 void WriteValue(const Value *V) {
120 if (isa<Instruction>(V)) {
121 MessagesStr << *V << '\n';
123 WriteAsOperand(MessagesStr, V, true, Mod);
128 void WriteType(const Type *T) {
131 WriteTypeSymbolic(MessagesStr, T, Mod);
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";
147 void CheckFailed(const Twine &Message, const Value *V1,
148 const Type *T2, const Value *V3 = 0) {
149 MessagesStr << Message.str() << "\n";
155 void CheckFailed(const Twine &Message, const Type *T1,
156 const Type *T2 = 0, const Type *T3 = 0) {
157 MessagesStr << Message.str() << "\n";
166 static RegisterPass<Lint>
167 X("lint", "Statically lint-checks LLVM IR", false, true);
169 // Assert - We know that cond should be true, if not print an error message.
170 #define Assert(C, M) \
171 do { if (!(C)) { CheckFailed(M); return; } } while (0)
172 #define Assert1(C, M, V1) \
173 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
174 #define Assert2(C, M, V1, V2) \
175 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
176 #define Assert3(C, M, V1, V2, V3) \
177 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
178 #define Assert4(C, M, V1, V2, V3, V4) \
179 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
181 // Lint::run - This is the main Analysis entry point for a
184 bool Lint::runOnFunction(Function &F) {
186 AA = &getAnalysis<AliasAnalysis>();
187 DT = &getAnalysis<DominatorTree>();
188 TD = getAnalysisIfAvailable<TargetData>();
190 dbgs() << MessagesStr.str();
195 void Lint::visitFunction(Function &F) {
196 // This isn't undefined behavior, it's just a little unusual, and it's a
197 // fairly common mistake to neglect to name a function.
198 Assert1(F.hasName() || F.hasLocalLinkage(),
199 "Unusual: Unnamed function with non-local linkage", &F);
202 void Lint::visitCallSite(CallSite CS) {
203 Instruction &I = *CS.getInstruction();
204 Value *Callee = CS.getCalledValue();
206 visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
208 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
209 Assert1(CS.getCallingConv() == F->getCallingConv(),
210 "Undefined behavior: Caller and callee calling convention differ",
213 const FunctionType *FT = F->getFunctionType();
214 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
216 Assert1(FT->isVarArg() ?
217 FT->getNumParams() <= NumActualArgs :
218 FT->getNumParams() == NumActualArgs,
219 "Undefined behavior: Call argument count mismatches callee "
220 "argument count", &I);
222 // TODO: Check argument types (in case the callee was casted)
224 // TODO: Check ABI-significant attributes.
226 // TODO: Check noalias attribute.
228 // TODO: Check sret attribute.
231 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
232 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
234 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
235 Assert1(!isa<AllocaInst>(Obj),
236 "Undefined behavior: Call with \"tail\" keyword references "
241 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
242 switch (II->getIntrinsicID()) {
245 // TODO: Check more intrinsics
247 case Intrinsic::memcpy: {
248 MemCpyInst *MCI = cast<MemCpyInst>(&I);
249 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
251 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
254 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
255 // isn't expressive enough for what we really want to do. Known partial
256 // overlap is not distinguished from the case where nothing is known.
258 if (const ConstantInt *Len =
259 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
260 /*OffsetOk=*/false)))
261 if (Len->getValue().isIntN(32))
262 Size = Len->getValue().getZExtValue();
263 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
264 AliasAnalysis::MustAlias,
265 "Undefined behavior: memcpy source and destination overlap", &I);
268 case Intrinsic::memmove: {
269 MemMoveInst *MMI = cast<MemMoveInst>(&I);
270 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
272 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
276 case Intrinsic::memset: {
277 MemSetInst *MSI = cast<MemSetInst>(&I);
278 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
283 case Intrinsic::vastart:
284 Assert1(I.getParent()->getParent()->isVarArg(),
285 "Undefined behavior: va_start called in a non-varargs function",
288 visitMemoryReference(I, CS.getArgument(0), 0, 0,
289 MemRef::Read | MemRef::Write);
291 case Intrinsic::vacopy:
292 visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
293 visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
295 case Intrinsic::vaend:
296 visitMemoryReference(I, CS.getArgument(0), 0, 0,
297 MemRef::Read | MemRef::Write);
300 case Intrinsic::stackrestore:
301 // Stackrestore doesn't read or write memory, but it sets the
302 // stack pointer, which the compiler may read from or write to
303 // at any time, so check it for both readability and writeability.
304 visitMemoryReference(I, CS.getArgument(0), 0, 0,
305 MemRef::Read | MemRef::Write);
310 void Lint::visitCallInst(CallInst &I) {
311 return visitCallSite(&I);
314 void Lint::visitInvokeInst(InvokeInst &I) {
315 return visitCallSite(&I);
318 void Lint::visitReturnInst(ReturnInst &I) {
319 Function *F = I.getParent()->getParent();
320 Assert1(!F->doesNotReturn(),
321 "Unusual: Return statement in function with noreturn attribute",
324 if (Value *V = I.getReturnValue()) {
325 Value *Obj = findValue(V, /*OffsetOk=*/true);
326 Assert1(!isa<AllocaInst>(Obj),
327 "Unusual: Returning alloca value", &I);
331 // TODO: Add a length argument and check that the reference is in bounds
332 void Lint::visitMemoryReference(Instruction &I,
333 Value *Ptr, unsigned Align, const Type *Ty,
335 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
336 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
337 "Undefined behavior: Null pointer dereference", &I);
338 Assert1(!isa<UndefValue>(UnderlyingObject),
339 "Undefined behavior: Undef pointer dereference", &I);
341 if (Flags & MemRef::Write) {
342 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
343 Assert1(!GV->isConstant(),
344 "Undefined behavior: Write to read-only memory", &I);
345 Assert1(!isa<Function>(UnderlyingObject) &&
346 !isa<BlockAddress>(UnderlyingObject),
347 "Undefined behavior: Write to text section", &I);
349 if (Flags & MemRef::Read) {
350 Assert1(!isa<Function>(UnderlyingObject),
351 "Unusual: Load from function body", &I);
352 Assert1(!isa<BlockAddress>(UnderlyingObject),
353 "Undefined behavior: Load from block address", &I);
355 if (Flags & MemRef::Callee) {
356 Assert1(!isa<BlockAddress>(UnderlyingObject),
357 "Undefined behavior: Call to block address", &I);
359 if (Flags & MemRef::Branchee) {
360 Assert1(!isa<Constant>(UnderlyingObject) ||
361 isa<BlockAddress>(UnderlyingObject),
362 "Undefined behavior: Branch to non-blockaddress", &I);
366 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
369 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
370 APInt Mask = APInt::getAllOnesValue(BitWidth),
371 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
372 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
373 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
374 "Undefined behavior: Memory reference address is misaligned", &I);
379 void Lint::visitLoadInst(LoadInst &I) {
380 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
384 void Lint::visitStoreInst(StoreInst &I) {
385 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
386 I.getOperand(0)->getType(), MemRef::Write);
389 void Lint::visitXor(BinaryOperator &I) {
390 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
391 !isa<UndefValue>(I.getOperand(1)),
392 "Undefined result: xor(undef, undef)", &I);
395 void Lint::visitSub(BinaryOperator &I) {
396 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
397 !isa<UndefValue>(I.getOperand(1)),
398 "Undefined result: sub(undef, undef)", &I);
401 void Lint::visitLShr(BinaryOperator &I) {
402 if (ConstantInt *CI =
403 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
404 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
405 "Undefined result: Shift count out of range", &I);
408 void Lint::visitAShr(BinaryOperator &I) {
409 if (ConstantInt *CI =
410 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
411 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
412 "Undefined result: Shift count out of range", &I);
415 void Lint::visitShl(BinaryOperator &I) {
416 if (ConstantInt *CI =
417 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
418 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
419 "Undefined result: Shift count out of range", &I);
422 static bool isZero(Value *V, TargetData *TD) {
423 // Assume undef could be zero.
424 if (isa<UndefValue>(V)) return true;
426 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
427 APInt Mask = APInt::getAllOnesValue(BitWidth),
428 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
429 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
430 return KnownZero.isAllOnesValue();
433 void Lint::visitSDiv(BinaryOperator &I) {
434 Assert1(!isZero(I.getOperand(1), TD),
435 "Undefined behavior: Division by zero", &I);
438 void Lint::visitUDiv(BinaryOperator &I) {
439 Assert1(!isZero(I.getOperand(1), TD),
440 "Undefined behavior: Division by zero", &I);
443 void Lint::visitSRem(BinaryOperator &I) {
444 Assert1(!isZero(I.getOperand(1), TD),
445 "Undefined behavior: Division by zero", &I);
448 void Lint::visitURem(BinaryOperator &I) {
449 Assert1(!isZero(I.getOperand(1), TD),
450 "Undefined behavior: Division by zero", &I);
453 void Lint::visitAllocaInst(AllocaInst &I) {
454 if (isa<ConstantInt>(I.getArraySize()))
455 // This isn't undefined behavior, it's just an obvious pessimization.
456 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
457 "Pessimization: Static alloca outside of entry block", &I);
460 void Lint::visitVAArgInst(VAArgInst &I) {
461 visitMemoryReference(I, I.getOperand(0), 0, 0,
462 MemRef::Read | MemRef::Write);
465 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
466 visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
469 void Lint::visitExtractElementInst(ExtractElementInst &I) {
470 if (ConstantInt *CI =
471 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
472 /*OffsetOk=*/false)))
473 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
474 "Undefined result: extractelement index out of range", &I);
477 void Lint::visitInsertElementInst(InsertElementInst &I) {
478 if (ConstantInt *CI =
479 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
480 /*OffsetOk=*/false)))
481 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
482 "Undefined result: insertelement index out of range", &I);
485 void Lint::visitUnreachableInst(UnreachableInst &I) {
486 // This isn't undefined behavior, it's merely suspicious.
487 Assert1(&I == I.getParent()->begin() ||
488 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
489 "Unusual: unreachable immediately preceded by instruction without "
493 /// findValue - Look through bitcasts and simple memory reference patterns
494 /// to identify an equivalent, but more informative, value. If OffsetOk
495 /// is true, look through getelementptrs with non-zero offsets too.
497 /// Most analysis passes don't require this logic, because instcombine
498 /// will simplify most of these kinds of things away. But it's a goal of
499 /// this Lint pass to be useful even on non-optimized IR.
500 Value *Lint::findValue(Value *V, bool OffsetOk) const {
501 // TODO: Look through sext or zext cast, when the result is known to
502 // be interpreted as signed or unsigned, respectively.
503 // TODO: Look through calls with unique return values.
504 // TODO: Look through vector insert/extract/shuffle.
505 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
506 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
507 BasicBlock::iterator BBI = L;
508 BasicBlock *BB = L->getParent();
510 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
512 return findValue(U, OffsetOk);
513 BB = L->getParent()->getUniquePredecessor();
517 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
518 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
519 Type::getInt64Ty(V->getContext())))
520 return findValue(CI->getOperand(0), OffsetOk);
521 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
522 if (Value *W = PN->hasConstantValue(DT))
523 return findValue(W, OffsetOk);
524 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
525 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
529 return findValue(W, OffsetOk);
532 // As a last resort, try SimplifyInstruction or constant folding.
533 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
534 if (Value *W = SimplifyInstruction(Inst, TD))
536 return findValue(W, OffsetOk);
537 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
538 if (Value *W = ConstantFoldConstantExpression(CE, TD))
540 return findValue(W, OffsetOk);
546 //===----------------------------------------------------------------------===//
547 // Implement the public interfaces to this file...
548 //===----------------------------------------------------------------------===//
550 FunctionPass *llvm::createLintPass() {
554 /// lintFunction - Check a function for errors, printing messages on stderr.
556 void llvm::lintFunction(const Function &f) {
557 Function &F = const_cast<Function&>(f);
558 assert(!F.isDeclaration() && "Cannot lint external functions");
560 FunctionPassManager FPM(F.getParent());
561 Lint *V = new Lint();
566 /// lintModule - Check a module for errors, printing messages on stderr.
568 void llvm::lintModule(const Module &M) {
570 Lint *V = new Lint();
572 PM.run(const_cast<Module&>(M));