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/Lint.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/Assembly/Writer.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Pass.h"
43 #include "llvm/PassManager.h"
44 #include "llvm/IntrinsicInst.h"
45 #include "llvm/Function.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/ADT/STLExtras.h"
55 static unsigned Read = 1;
56 static unsigned Write = 2;
57 static unsigned Callee = 4;
58 static unsigned Branchee = 8;
61 class Lint : public FunctionPass, public InstVisitor<Lint> {
62 friend class InstVisitor<Lint>;
64 void visitFunction(Function &F);
66 void visitCallSite(CallSite CS);
67 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
68 const Type *Ty, unsigned Flags);
70 void visitCallInst(CallInst &I);
71 void visitInvokeInst(InvokeInst &I);
72 void visitReturnInst(ReturnInst &I);
73 void visitLoadInst(LoadInst &I);
74 void visitStoreInst(StoreInst &I);
75 void visitXor(BinaryOperator &I);
76 void visitSub(BinaryOperator &I);
77 void visitLShr(BinaryOperator &I);
78 void visitAShr(BinaryOperator &I);
79 void visitShl(BinaryOperator &I);
80 void visitSDiv(BinaryOperator &I);
81 void visitUDiv(BinaryOperator &I);
82 void visitSRem(BinaryOperator &I);
83 void visitURem(BinaryOperator &I);
84 void visitAllocaInst(AllocaInst &I);
85 void visitVAArgInst(VAArgInst &I);
86 void visitIndirectBrInst(IndirectBrInst &I);
87 void visitExtractElementInst(ExtractElementInst &I);
88 void visitInsertElementInst(InsertElementInst &I);
89 void visitUnreachableInst(UnreachableInst &I);
97 raw_string_ostream MessagesStr;
99 static char ID; // Pass identification, replacement for typeid
100 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
102 virtual bool runOnFunction(Function &F);
104 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
105 AU.setPreservesAll();
106 AU.addRequired<AliasAnalysis>();
108 virtual void print(raw_ostream &O, const Module *M) const {}
110 void WriteValue(const Value *V) {
112 if (isa<Instruction>(V)) {
113 MessagesStr << *V << '\n';
115 WriteAsOperand(MessagesStr, V, true, Mod);
120 void WriteType(const Type *T) {
123 WriteTypeSymbolic(MessagesStr, T, Mod);
126 // CheckFailed - A check failed, so print out the condition and the message
127 // that failed. This provides a nice place to put a breakpoint if you want
128 // to see why something is not correct.
129 void CheckFailed(const Twine &Message,
130 const Value *V1 = 0, const Value *V2 = 0,
131 const Value *V3 = 0, const Value *V4 = 0) {
132 MessagesStr << Message.str() << "\n";
139 void CheckFailed(const Twine &Message, const Value *V1,
140 const Type *T2, const Value *V3 = 0) {
141 MessagesStr << Message.str() << "\n";
147 void CheckFailed(const Twine &Message, const Type *T1,
148 const Type *T2 = 0, const Type *T3 = 0) {
149 MessagesStr << Message.str() << "\n";
158 static RegisterPass<Lint>
159 X("lint", "Statically lint-checks LLVM IR", false, true);
161 // Assert - We know that cond should be true, if not print an error message.
162 #define Assert(C, M) \
163 do { if (!(C)) { CheckFailed(M); return; } } while (0)
164 #define Assert1(C, M, V1) \
165 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
166 #define Assert2(C, M, V1, V2) \
167 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
168 #define Assert3(C, M, V1, V2, V3) \
169 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
170 #define Assert4(C, M, V1, V2, V3, V4) \
171 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
173 // Lint::run - This is the main Analysis entry point for a
176 bool Lint::runOnFunction(Function &F) {
178 AA = &getAnalysis<AliasAnalysis>();
179 TD = getAnalysisIfAvailable<TargetData>();
181 dbgs() << MessagesStr.str();
185 void Lint::visitFunction(Function &F) {
186 // This isn't undefined behavior, it's just a little unusual, and it's a
187 // fairly common mistake to neglect to name a function.
188 Assert1(F.hasName() || F.hasLocalLinkage(),
189 "Unusual: Unnamed function with non-local linkage", &F);
192 void Lint::visitCallSite(CallSite CS) {
193 Instruction &I = *CS.getInstruction();
194 Value *Callee = CS.getCalledValue();
196 visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
198 if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
199 Assert1(CS.getCallingConv() == F->getCallingConv(),
200 "Undefined behavior: Caller and callee calling convention differ",
203 const FunctionType *FT = F->getFunctionType();
204 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
206 Assert1(FT->isVarArg() ?
207 FT->getNumParams() <= NumActualArgs :
208 FT->getNumParams() == NumActualArgs,
209 "Undefined behavior: Call argument count mismatches callee "
210 "argument count", &I);
212 // TODO: Check argument types (in case the callee was casted)
214 // TODO: Check ABI-significant attributes.
216 // TODO: Check noalias attribute.
218 // TODO: Check sret attribute.
221 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
222 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
224 Value *Obj = (*AI)->getUnderlyingObject();
225 Assert1(!isa<AllocaInst>(Obj) && !isa<VAArgInst>(Obj),
226 "Undefined behavior: Call with \"tail\" keyword references "
227 "alloca or va_arg", &I);
231 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
232 switch (II->getIntrinsicID()) {
235 // TODO: Check more intrinsics
237 case Intrinsic::memcpy: {
238 MemCpyInst *MCI = cast<MemCpyInst>(&I);
239 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
241 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
244 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
245 // isn't expressive enough for what we really want to do. Known partial
246 // overlap is not distinguished from the case where nothing is known.
248 if (const ConstantInt *Len =
249 dyn_cast<ConstantInt>(MCI->getLength()->stripPointerCasts()))
250 if (Len->getValue().isIntN(32))
251 Size = Len->getValue().getZExtValue();
252 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
253 AliasAnalysis::MustAlias,
254 "Undefined behavior: memcpy source and destination overlap", &I);
257 case Intrinsic::memmove: {
258 MemMoveInst *MMI = cast<MemMoveInst>(&I);
259 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
261 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
265 case Intrinsic::memset: {
266 MemSetInst *MSI = cast<MemSetInst>(&I);
267 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
272 case Intrinsic::vastart:
273 Assert1(I.getParent()->getParent()->isVarArg(),
274 "Undefined behavior: va_start called in a non-varargs function",
277 visitMemoryReference(I, CS.getArgument(0), 0, 0,
278 MemRef::Read | MemRef::Write);
280 case Intrinsic::vacopy:
281 visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
282 visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
284 case Intrinsic::vaend:
285 visitMemoryReference(I, CS.getArgument(0), 0, 0,
286 MemRef::Read | MemRef::Write);
291 void Lint::visitCallInst(CallInst &I) {
292 return visitCallSite(&I);
295 void Lint::visitInvokeInst(InvokeInst &I) {
296 return visitCallSite(&I);
299 void Lint::visitReturnInst(ReturnInst &I) {
300 Function *F = I.getParent()->getParent();
301 Assert1(!F->doesNotReturn(),
302 "Unusual: Return statement in function with noreturn attribute",
306 // TODO: Add a length argument and check that the reference is in bounds
307 void Lint::visitMemoryReference(Instruction &I,
308 Value *Ptr, unsigned Align, const Type *Ty,
310 Value *UnderlyingObject = Ptr->getUnderlyingObject();
311 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
312 "Undefined behavior: Null pointer dereference", &I);
313 Assert1(!isa<UndefValue>(UnderlyingObject),
314 "Undefined behavior: Undef pointer dereference", &I);
316 if (Flags & MemRef::Write) {
317 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
318 Assert1(!GV->isConstant(),
319 "Undefined behavior: Write to read-only memory", &I);
320 Assert1(!isa<Function>(UnderlyingObject) &&
321 !isa<BlockAddress>(UnderlyingObject),
322 "Undefined behavior: Write to text section", &I);
324 if (Flags & MemRef::Read) {
325 Assert1(!isa<Function>(UnderlyingObject),
326 "Unusual: Load from function body", &I);
327 Assert1(!isa<BlockAddress>(UnderlyingObject),
328 "Undefined behavior: Load from block address", &I);
330 if (Flags & MemRef::Callee) {
331 Assert1(!isa<BlockAddress>(UnderlyingObject),
332 "Undefined behavior: Call to block address", &I);
334 if (Flags & MemRef::Branchee) {
335 Assert1(!isa<Constant>(UnderlyingObject) ||
336 isa<BlockAddress>(UnderlyingObject),
337 "Undefined behavior: Branch to non-blockaddress", &I);
341 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
344 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
345 APInt Mask = APInt::getAllOnesValue(BitWidth),
346 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
347 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
348 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
349 "Undefined behavior: Memory reference address is misaligned", &I);
354 void Lint::visitLoadInst(LoadInst &I) {
355 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
359 void Lint::visitStoreInst(StoreInst &I) {
360 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
361 I.getOperand(0)->getType(), MemRef::Write);
364 void Lint::visitXor(BinaryOperator &I) {
365 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
366 !isa<UndefValue>(I.getOperand(1)),
367 "Undefined result: xor(undef, undef)", &I);
370 void Lint::visitSub(BinaryOperator &I) {
371 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
372 !isa<UndefValue>(I.getOperand(1)),
373 "Undefined result: sub(undef, undef)", &I);
376 void Lint::visitLShr(BinaryOperator &I) {
377 if (ConstantInt *CI =
378 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
379 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
380 "Undefined result: Shift count out of range", &I);
383 void Lint::visitAShr(BinaryOperator &I) {
384 if (ConstantInt *CI =
385 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
386 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
387 "Undefined result: Shift count out of range", &I);
390 void Lint::visitShl(BinaryOperator &I) {
391 if (ConstantInt *CI =
392 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
393 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
394 "Undefined result: Shift count out of range", &I);
397 static bool isZero(Value *V, TargetData *TD) {
398 // Assume undef could be zero.
399 if (isa<UndefValue>(V)) return true;
401 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
402 APInt Mask = APInt::getAllOnesValue(BitWidth),
403 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
404 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
405 return KnownZero.isAllOnesValue();
408 void Lint::visitSDiv(BinaryOperator &I) {
409 Assert1(!isZero(I.getOperand(1), TD),
410 "Undefined behavior: Division by zero", &I);
413 void Lint::visitUDiv(BinaryOperator &I) {
414 Assert1(!isZero(I.getOperand(1), TD),
415 "Undefined behavior: Division by zero", &I);
418 void Lint::visitSRem(BinaryOperator &I) {
419 Assert1(!isZero(I.getOperand(1), TD),
420 "Undefined behavior: Division by zero", &I);
423 void Lint::visitURem(BinaryOperator &I) {
424 Assert1(!isZero(I.getOperand(1), TD),
425 "Undefined behavior: Division by zero", &I);
428 void Lint::visitAllocaInst(AllocaInst &I) {
429 if (isa<ConstantInt>(I.getArraySize()))
430 // This isn't undefined behavior, it's just an obvious pessimization.
431 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
432 "Pessimization: Static alloca outside of entry block", &I);
435 void Lint::visitVAArgInst(VAArgInst &I) {
436 visitMemoryReference(I, I.getOperand(0), 0, 0,
437 MemRef::Read | MemRef::Write);
440 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
441 visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
444 void Lint::visitExtractElementInst(ExtractElementInst &I) {
445 if (ConstantInt *CI =
446 dyn_cast<ConstantInt>(I.getIndexOperand()->stripPointerCasts()))
447 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
448 "Undefined result: extractelement index out of range", &I);
451 void Lint::visitInsertElementInst(InsertElementInst &I) {
452 if (ConstantInt *CI =
453 dyn_cast<ConstantInt>(I.getOperand(2)->stripPointerCasts()))
454 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
455 "Undefined result: insertelement index out of range", &I);
458 void Lint::visitUnreachableInst(UnreachableInst &I) {
459 // This isn't undefined behavior, it's merely suspicious.
460 Assert1(&I == I.getParent()->begin() ||
461 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
462 "Unusual: unreachable immediately preceded by instruction without "
466 //===----------------------------------------------------------------------===//
467 // Implement the public interfaces to this file...
468 //===----------------------------------------------------------------------===//
470 FunctionPass *llvm::createLintPass() {
474 /// lintFunction - Check a function for errors, printing messages on stderr.
476 void llvm::lintFunction(const Function &f) {
477 Function &F = const_cast<Function&>(f);
478 assert(!F.isDeclaration() && "Cannot lint external functions");
480 FunctionPassManager FPM(F.getParent());
481 Lint *V = new Lint();
486 /// lintModule - Check a module for errors, printing messages on stderr.
487 /// Return true if the module is corrupt.
489 void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
491 Lint *V = new Lint();
493 PM.run(const_cast<Module&>(M));
496 *ErrorInfo = V->MessagesStr.str();