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"
54 class Lint : public FunctionPass, public InstVisitor<Lint> {
55 friend class InstVisitor<Lint>;
57 void visitFunction(Function &F);
59 void visitCallSite(CallSite CS);
60 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
63 void visitCallInst(CallInst &I);
64 void visitInvokeInst(InvokeInst &I);
65 void visitReturnInst(ReturnInst &I);
66 void visitLoadInst(LoadInst &I);
67 void visitStoreInst(StoreInst &I);
68 void visitXor(BinaryOperator &I);
69 void visitSub(BinaryOperator &I);
70 void visitLShr(BinaryOperator &I);
71 void visitAShr(BinaryOperator &I);
72 void visitShl(BinaryOperator &I);
73 void visitSDiv(BinaryOperator &I);
74 void visitUDiv(BinaryOperator &I);
75 void visitSRem(BinaryOperator &I);
76 void visitURem(BinaryOperator &I);
77 void visitAllocaInst(AllocaInst &I);
78 void visitVAArgInst(VAArgInst &I);
79 void visitIndirectBrInst(IndirectBrInst &I);
80 void visitExtractElementInst(ExtractElementInst &I);
81 void visitInsertElementInst(InsertElementInst &I);
82 void visitUnreachableInst(UnreachableInst &I);
90 raw_string_ostream MessagesStr;
92 static char ID; // Pass identification, replacement for typeid
93 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
95 virtual bool runOnFunction(Function &F);
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<AliasAnalysis>();
101 virtual void print(raw_ostream &O, const Module *M) const {}
103 void WriteValue(const Value *V) {
105 if (isa<Instruction>(V)) {
106 MessagesStr << *V << '\n';
108 WriteAsOperand(MessagesStr, V, true, Mod);
113 void WriteType(const Type *T) {
116 WriteTypeSymbolic(MessagesStr, T, Mod);
119 // CheckFailed - A check failed, so print out the condition and the message
120 // that failed. This provides a nice place to put a breakpoint if you want
121 // to see why something is not correct.
122 void CheckFailed(const Twine &Message,
123 const Value *V1 = 0, const Value *V2 = 0,
124 const Value *V3 = 0, const Value *V4 = 0) {
125 MessagesStr << Message.str() << "\n";
132 void CheckFailed(const Twine &Message, const Value *V1,
133 const Type *T2, const Value *V3 = 0) {
134 MessagesStr << Message.str() << "\n";
140 void CheckFailed(const Twine &Message, const Type *T1,
141 const Type *T2 = 0, const Type *T3 = 0) {
142 MessagesStr << Message.str() << "\n";
151 static RegisterPass<Lint>
152 X("lint", "Statically lint-checks LLVM IR", false, true);
154 // Assert - We know that cond should be true, if not print an error message.
155 #define Assert(C, M) \
156 do { if (!(C)) { CheckFailed(M); return; } } while (0)
157 #define Assert1(C, M, V1) \
158 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
159 #define Assert2(C, M, V1, V2) \
160 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
161 #define Assert3(C, M, V1, V2, V3) \
162 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
163 #define Assert4(C, M, V1, V2, V3, V4) \
164 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
166 // Lint::run - This is the main Analysis entry point for a
169 bool Lint::runOnFunction(Function &F) {
171 AA = &getAnalysis<AliasAnalysis>();
172 TD = getAnalysisIfAvailable<TargetData>();
174 dbgs() << MessagesStr.str();
178 void Lint::visitFunction(Function &F) {
179 // This isn't undefined behavior, it's just a little unusual, and it's a
180 // fairly common mistake to neglect to name a function.
181 Assert1(F.hasName() || F.hasLocalLinkage(),
182 "Unusual: Unnamed function with non-local linkage", &F);
185 void Lint::visitCallSite(CallSite CS) {
186 Instruction &I = *CS.getInstruction();
187 Value *Callee = CS.getCalledValue();
189 // TODO: Check function alignment?
190 visitMemoryReference(I, Callee, 0, 0);
192 if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
193 Assert1(CS.getCallingConv() == F->getCallingConv(),
194 "Undefined behavior: Caller and callee calling convention differ",
197 const FunctionType *FT = F->getFunctionType();
198 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
200 Assert1(FT->isVarArg() ?
201 FT->getNumParams() <= NumActualArgs :
202 FT->getNumParams() == NumActualArgs,
203 "Undefined behavior: Call argument count mismatches callee "
204 "argument count", &I);
206 // TODO: Check argument types (in case the callee was casted)
208 // TODO: Check ABI-significant attributes.
210 // TODO: Check noalias attribute.
212 // TODO: Check sret attribute.
215 // TODO: Check the "tail" keyword constraints.
217 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
218 switch (II->getIntrinsicID()) {
221 // TODO: Check more intrinsics
223 case Intrinsic::memcpy: {
224 MemCpyInst *MCI = cast<MemCpyInst>(&I);
225 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0);
226 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0);
228 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
229 // isn't expressive enough for what we really want to do. Known partial
230 // overlap is not distinguished from the case where nothing is known.
232 if (const ConstantInt *Len =
233 dyn_cast<ConstantInt>(MCI->getLength()->stripPointerCasts()))
234 if (Len->getValue().isIntN(32))
235 Size = Len->getValue().getZExtValue();
236 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
237 AliasAnalysis::MustAlias,
238 "Undefined behavior: memcpy source and destination overlap", &I);
241 case Intrinsic::memmove: {
242 MemMoveInst *MMI = cast<MemMoveInst>(&I);
243 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0);
244 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0);
247 case Intrinsic::memset: {
248 MemSetInst *MSI = cast<MemSetInst>(&I);
249 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0);
253 case Intrinsic::vastart:
254 Assert1(I.getParent()->getParent()->isVarArg(),
255 "Undefined behavior: va_start called in a non-varargs function",
258 visitMemoryReference(I, CS.getArgument(0), 0, 0);
260 case Intrinsic::vacopy:
261 visitMemoryReference(I, CS.getArgument(0), 0, 0);
262 visitMemoryReference(I, CS.getArgument(1), 0, 0);
264 case Intrinsic::vaend:
265 visitMemoryReference(I, CS.getArgument(0), 0, 0);
268 case Intrinsic::stackrestore:
269 visitMemoryReference(I, CS.getArgument(0), 0, 0);
274 void Lint::visitCallInst(CallInst &I) {
275 return visitCallSite(&I);
278 void Lint::visitInvokeInst(InvokeInst &I) {
279 return visitCallSite(&I);
282 void Lint::visitReturnInst(ReturnInst &I) {
283 Function *F = I.getParent()->getParent();
284 Assert1(!F->doesNotReturn(),
285 "Unusual: Return statement in function with noreturn attribute",
289 // TODO: Add a length argument and check that the reference is in bounds
290 // TODO: Add read/write/execute flags and check for writing to read-only
291 // memory or jumping to suspicious writeable memory
292 void Lint::visitMemoryReference(Instruction &I,
293 Value *Ptr, unsigned Align, const Type *Ty) {
294 Value *UnderlyingObject = Ptr->getUnderlyingObject();
295 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
296 "Undefined behavior: Null pointer dereference", &I);
297 Assert1(!isa<UndefValue>(UnderlyingObject),
298 "Undefined behavior: Undef pointer dereference", &I);
301 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
304 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
305 APInt Mask = APInt::getAllOnesValue(BitWidth),
306 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
307 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
308 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
309 "Undefined behavior: Memory reference address is misaligned", &I);
314 void Lint::visitLoadInst(LoadInst &I) {
315 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType());
318 void Lint::visitStoreInst(StoreInst &I) {
319 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
320 I.getOperand(0)->getType());
323 void Lint::visitXor(BinaryOperator &I) {
324 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
325 !isa<UndefValue>(I.getOperand(1)),
326 "Undefined result: xor(undef, undef)", &I);
329 void Lint::visitSub(BinaryOperator &I) {
330 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
331 !isa<UndefValue>(I.getOperand(1)),
332 "Undefined result: sub(undef, undef)", &I);
335 void Lint::visitLShr(BinaryOperator &I) {
336 if (ConstantInt *CI =
337 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
338 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
339 "Undefined result: Shift count out of range", &I);
342 void Lint::visitAShr(BinaryOperator &I) {
343 if (ConstantInt *CI =
344 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
345 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
346 "Undefined result: Shift count out of range", &I);
349 void Lint::visitShl(BinaryOperator &I) {
350 if (ConstantInt *CI =
351 dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
352 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
353 "Undefined result: Shift count out of range", &I);
356 static bool isZero(Value *V, TargetData *TD) {
357 // Assume undef could be zero.
358 if (isa<UndefValue>(V)) return true;
360 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
361 APInt Mask = APInt::getAllOnesValue(BitWidth),
362 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
363 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
364 return KnownZero.isAllOnesValue();
367 void Lint::visitSDiv(BinaryOperator &I) {
368 Assert1(!isZero(I.getOperand(1), TD),
369 "Undefined behavior: Division by zero", &I);
372 void Lint::visitUDiv(BinaryOperator &I) {
373 Assert1(!isZero(I.getOperand(1), TD),
374 "Undefined behavior: Division by zero", &I);
377 void Lint::visitSRem(BinaryOperator &I) {
378 Assert1(!isZero(I.getOperand(1), TD),
379 "Undefined behavior: Division by zero", &I);
382 void Lint::visitURem(BinaryOperator &I) {
383 Assert1(!isZero(I.getOperand(1), TD),
384 "Undefined behavior: Division by zero", &I);
387 void Lint::visitAllocaInst(AllocaInst &I) {
388 if (isa<ConstantInt>(I.getArraySize()))
389 // This isn't undefined behavior, it's just an obvious pessimization.
390 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
391 "Pessimization: Static alloca outside of entry block", &I);
394 void Lint::visitVAArgInst(VAArgInst &I) {
395 visitMemoryReference(I, I.getOperand(0), 0, 0);
398 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
399 visitMemoryReference(I, I.getAddress(), 0, 0);
402 void Lint::visitExtractElementInst(ExtractElementInst &I) {
403 if (ConstantInt *CI =
404 dyn_cast<ConstantInt>(I.getIndexOperand()->stripPointerCasts()))
405 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
406 "Undefined result: extractelement index out of range", &I);
409 void Lint::visitInsertElementInst(InsertElementInst &I) {
410 if (ConstantInt *CI =
411 dyn_cast<ConstantInt>(I.getOperand(2)->stripPointerCasts()))
412 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
413 "Undefined result: insertelement index out of range", &I);
416 void Lint::visitUnreachableInst(UnreachableInst &I) {
417 // This isn't undefined behavior, it's merely suspicious.
418 Assert1(&I == I.getParent()->begin() ||
419 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
420 "Unusual: unreachable immediately preceded by instruction without "
424 //===----------------------------------------------------------------------===//
425 // Implement the public interfaces to this file...
426 //===----------------------------------------------------------------------===//
428 FunctionPass *llvm::createLintPass() {
432 /// lintFunction - Check a function for errors, printing messages on stderr.
434 void llvm::lintFunction(const Function &f) {
435 Function &F = const_cast<Function&>(f);
436 assert(!F.isDeclaration() && "Cannot lint external functions");
438 FunctionPassManager FPM(F.getParent());
439 Lint *V = new Lint();
444 /// lintModule - Check a module for errors, printing messages on stderr.
445 /// Return true if the module is corrupt.
447 void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
449 Lint *V = new Lint();
451 PM.run(const_cast<Module&>(M));
454 *ErrorInfo = V->MessagesStr.str();