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"
53 class Lint : public FunctionPass, public InstVisitor<Lint> {
54 friend class InstVisitor<Lint>;
56 void visitCallSite(CallSite CS);
57 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
60 void visitInstruction(Instruction &I);
61 void visitCallInst(CallInst &I);
62 void visitInvokeInst(InvokeInst &I);
63 void visitReturnInst(ReturnInst &I);
64 void visitLoadInst(LoadInst &I);
65 void visitStoreInst(StoreInst &I);
66 void visitSDiv(BinaryOperator &I);
67 void visitUDiv(BinaryOperator &I);
68 void visitSRem(BinaryOperator &I);
69 void visitURem(BinaryOperator &I);
70 void visitAllocaInst(AllocaInst &I);
71 void visitVAArgInst(VAArgInst &I);
72 void visitIndirectBrInst(IndirectBrInst &I);
80 raw_string_ostream MessagesStr;
82 static char ID; // Pass identification, replacement for typeid
83 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
85 virtual bool runOnFunction(Function &F);
87 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<AliasAnalysis>();
91 virtual void print(raw_ostream &O, const Module *M) const {}
93 void WriteValue(const Value *V) {
95 if (isa<Instruction>(V)) {
96 MessagesStr << *V << '\n';
98 WriteAsOperand(MessagesStr, V, true, Mod);
103 void WriteType(const Type *T) {
106 WriteTypeSymbolic(MessagesStr, T, Mod);
109 // CheckFailed - A check failed, so print out the condition and the message
110 // that failed. This provides a nice place to put a breakpoint if you want
111 // to see why something is not correct.
112 void CheckFailed(const Twine &Message,
113 const Value *V1 = 0, const Value *V2 = 0,
114 const Value *V3 = 0, const Value *V4 = 0) {
115 MessagesStr << Message.str() << "\n";
122 void CheckFailed(const Twine &Message, const Value *V1,
123 const Type *T2, const Value *V3 = 0) {
124 MessagesStr << Message.str() << "\n";
130 void CheckFailed(const Twine &Message, const Type *T1,
131 const Type *T2 = 0, const Type *T3 = 0) {
132 MessagesStr << Message.str() << "\n";
141 static RegisterPass<Lint>
142 X("lint", "Statically lint-checks LLVM IR", false, true);
144 // Assert - We know that cond should be true, if not print an error message.
145 #define Assert(C, M) \
146 do { if (!(C)) { CheckFailed(M); return; } } while (0)
147 #define Assert1(C, M, V1) \
148 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
149 #define Assert2(C, M, V1, V2) \
150 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
151 #define Assert3(C, M, V1, V2, V3) \
152 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
153 #define Assert4(C, M, V1, V2, V3, V4) \
154 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
156 // Lint::run - This is the main Analysis entry point for a
159 bool Lint::runOnFunction(Function &F) {
161 AA = &getAnalysis<AliasAnalysis>();
162 TD = getAnalysisIfAvailable<TargetData>();
164 dbgs() << MessagesStr.str();
168 void Lint::visitInstruction(Instruction &I) {
171 void Lint::visitCallSite(CallSite CS) {
172 Instruction &I = *CS.getInstruction();
173 Value *Callee = CS.getCalledValue();
175 // TODO: Check function alignment?
176 visitMemoryReference(I, Callee, 0, 0);
178 if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
179 Assert1(CS.getCallingConv() == F->getCallingConv(),
180 "Caller and callee calling convention differ", &I);
182 const FunctionType *FT = F->getFunctionType();
183 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
185 Assert1(FT->isVarArg() ?
186 FT->getNumParams() <= NumActualArgs :
187 FT->getNumParams() == NumActualArgs,
188 "Call argument count mismatches callee argument count", &I);
190 // TODO: Check argument types (in case the callee was casted)
192 // TODO: Check ABI-significant attributes.
194 // TODO: Check noalias attribute.
196 // TODO: Check sret attribute.
199 // TODO: Check the "tail" keyword constraints.
201 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
202 switch (II->getIntrinsicID()) {
205 // TODO: Check more intrinsics
207 case Intrinsic::memcpy: {
208 MemCpyInst *MCI = cast<MemCpyInst>(&I);
209 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0);
210 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0);
213 if (const ConstantInt *Len =
214 dyn_cast<ConstantInt>(MCI->getLength()->stripPointerCasts()))
215 if (Len->getValue().isIntN(32))
216 Size = Len->getValue().getZExtValue();
217 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
218 AliasAnalysis::MustAlias,
219 "memcpy source and destination overlap", &I);
222 case Intrinsic::memmove: {
223 MemMoveInst *MMI = cast<MemMoveInst>(&I);
224 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0);
225 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0);
228 case Intrinsic::memset: {
229 MemSetInst *MSI = cast<MemSetInst>(&I);
230 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0);
234 case Intrinsic::vastart:
235 visitMemoryReference(I, CS.getArgument(0), 0, 0);
237 case Intrinsic::vacopy:
238 visitMemoryReference(I, CS.getArgument(0), 0, 0);
239 visitMemoryReference(I, CS.getArgument(1), 0, 0);
241 case Intrinsic::vaend:
242 visitMemoryReference(I, CS.getArgument(0), 0, 0);
245 case Intrinsic::stackrestore:
246 visitMemoryReference(I, CS.getArgument(0), 0, 0);
251 void Lint::visitCallInst(CallInst &I) {
252 return visitCallSite(&I);
255 void Lint::visitInvokeInst(InvokeInst &I) {
256 return visitCallSite(&I);
259 void Lint::visitReturnInst(ReturnInst &I) {
260 Function *F = I.getParent()->getParent();
261 Assert1(!F->doesNotReturn(),
262 "Return statement in function with noreturn attribute", &I);
265 // TODO: Add a length argument and check that the reference is in bounds
266 // TODO: Add read/write/execute flags and check for writing to read-only
267 // memory or jumping to suspicious writeable memory
268 void Lint::visitMemoryReference(Instruction &I,
269 Value *Ptr, unsigned Align, const Type *Ty) {
270 Assert1(!isa<ConstantPointerNull>(Ptr->getUnderlyingObject()),
271 "Null pointer dereference", &I);
272 Assert1(!isa<UndefValue>(Ptr->getUnderlyingObject()),
273 "Undef pointer dereference", &I);
276 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
279 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
280 APInt Mask = APInt::getAllOnesValue(BitWidth),
281 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
282 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
283 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
284 "Memory reference address is misaligned", &I);
289 void Lint::visitLoadInst(LoadInst &I) {
290 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType());
293 void Lint::visitStoreInst(StoreInst &I) {
294 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
295 I.getOperand(0)->getType());
298 static bool isZero(Value *V, TargetData *TD) {
299 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
300 APInt Mask = APInt::getAllOnesValue(BitWidth),
301 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
302 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
303 return KnownZero.isAllOnesValue();
306 void Lint::visitSDiv(BinaryOperator &I) {
307 Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
310 void Lint::visitUDiv(BinaryOperator &I) {
311 Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
314 void Lint::visitSRem(BinaryOperator &I) {
315 Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
318 void Lint::visitURem(BinaryOperator &I) {
319 Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
322 void Lint::visitAllocaInst(AllocaInst &I) {
323 if (isa<ConstantInt>(I.getArraySize()))
324 // This isn't undefined behavior, it's just an obvious pessimization.
325 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
326 "Static alloca outside of entry block", &I);
329 void Lint::visitVAArgInst(VAArgInst &I) {
330 visitMemoryReference(I, I.getOperand(0), 0, 0);
333 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
334 visitMemoryReference(I, I.getAddress(), 0, 0);
337 //===----------------------------------------------------------------------===//
338 // Implement the public interfaces to this file...
339 //===----------------------------------------------------------------------===//
341 FunctionPass *llvm::createLintPass() {
345 /// lintFunction - Check a function for errors, printing messages on stderr.
347 void llvm::lintFunction(const Function &f) {
348 Function &F = const_cast<Function&>(f);
349 assert(!F.isDeclaration() && "Cannot lint external functions");
351 FunctionPassManager FPM(F.getParent());
352 Lint *V = new Lint();
357 /// lintModule - Check a module for errors, printing messages on stderr.
358 /// Return true if the module is corrupt.
360 void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
362 Lint *V = new Lint();
364 PM.run(const_cast<Module&>(M));
367 *ErrorInfo = V->MessagesStr.str();