blob: 7c3e6b3e84b7cfe1723ed88d0d8da407f2cd5a2e [file] [log] [blame]
Dan Gohman113902e2010-04-08 18:47:09 +00001//===-- 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.
Dan Gohman08833552010-04-22 01:30:05 +000023//
Dan Gohman113902e2010-04-08 18:47:09 +000024// 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.
28//
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.
33//
34//===----------------------------------------------------------------------===//
35
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"
Dan Gohmanbe02b202010-04-09 01:39:53 +000050#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000051using namespace llvm;
52
53namespace {
54 class Lint : public FunctionPass, public InstVisitor<Lint> {
55 friend class InstVisitor<Lint>;
56
Dan Gohmanbe02b202010-04-09 01:39:53 +000057 void visitFunction(Function &F);
58
Dan Gohman113902e2010-04-08 18:47:09 +000059 void visitCallSite(CallSite CS);
60 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
61 const Type *Ty);
62
Dan Gohman113902e2010-04-08 18:47:09 +000063 void visitCallInst(CallInst &I);
64 void visitInvokeInst(InvokeInst &I);
65 void visitReturnInst(ReturnInst &I);
66 void visitLoadInst(LoadInst &I);
67 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000068 void visitXor(BinaryOperator &I);
69 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000070 void visitLShr(BinaryOperator &I);
71 void visitAShr(BinaryOperator &I);
72 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000073 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);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000080 void visitExtractElementInst(ExtractElementInst &I);
81 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000082 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000083
84 public:
85 Module *Mod;
86 AliasAnalysis *AA;
87 TargetData *TD;
88
89 std::string Messages;
90 raw_string_ostream MessagesStr;
91
92 static char ID; // Pass identification, replacement for typeid
93 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
94
95 virtual bool runOnFunction(Function &F);
96
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
98 AU.setPreservesAll();
99 AU.addRequired<AliasAnalysis>();
100 }
101 virtual void print(raw_ostream &O, const Module *M) const {}
102
103 void WriteValue(const Value *V) {
104 if (!V) return;
105 if (isa<Instruction>(V)) {
106 MessagesStr << *V << '\n';
107 } else {
108 WriteAsOperand(MessagesStr, V, true, Mod);
109 MessagesStr << '\n';
110 }
111 }
112
113 void WriteType(const Type *T) {
114 if (!T) return;
115 MessagesStr << ' ';
116 WriteTypeSymbolic(MessagesStr, T, Mod);
117 }
118
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";
126 WriteValue(V1);
127 WriteValue(V2);
128 WriteValue(V3);
129 WriteValue(V4);
130 }
131
132 void CheckFailed(const Twine &Message, const Value *V1,
133 const Type *T2, const Value *V3 = 0) {
134 MessagesStr << Message.str() << "\n";
135 WriteValue(V1);
136 WriteType(T2);
137 WriteValue(V3);
138 }
139
140 void CheckFailed(const Twine &Message, const Type *T1,
141 const Type *T2 = 0, const Type *T3 = 0) {
142 MessagesStr << Message.str() << "\n";
143 WriteType(T1);
144 WriteType(T2);
145 WriteType(T3);
146 }
147 };
148}
149
150char Lint::ID = 0;
151static RegisterPass<Lint>
152X("lint", "Statically lint-checks LLVM IR", false, true);
153
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)
165
166// Lint::run - This is the main Analysis entry point for a
167// function.
168//
169bool Lint::runOnFunction(Function &F) {
170 Mod = F.getParent();
171 AA = &getAnalysis<AliasAnalysis>();
172 TD = getAnalysisIfAvailable<TargetData>();
173 visit(F);
174 dbgs() << MessagesStr.str();
175 return false;
176}
177
Dan Gohmanbe02b202010-04-09 01:39:53 +0000178void 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);
Dan Gohman113902e2010-04-08 18:47:09 +0000183}
184
185void Lint::visitCallSite(CallSite CS) {
186 Instruction &I = *CS.getInstruction();
187 Value *Callee = CS.getCalledValue();
188
189 // TODO: Check function alignment?
190 visitMemoryReference(I, Callee, 0, 0);
191
192 if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
193 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000194 "Undefined behavior: Caller and callee calling convention differ",
195 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000196
197 const FunctionType *FT = F->getFunctionType();
198 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
199
200 Assert1(FT->isVarArg() ?
201 FT->getNumParams() <= NumActualArgs :
202 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000203 "Undefined behavior: Call argument count mismatches callee "
204 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000205
206 // TODO: Check argument types (in case the callee was casted)
207
208 // TODO: Check ABI-significant attributes.
209
210 // TODO: Check noalias attribute.
211
212 // TODO: Check sret attribute.
213 }
214
215 // TODO: Check the "tail" keyword constraints.
216
217 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
218 switch (II->getIntrinsicID()) {
219 default: break;
220
221 // TODO: Check more intrinsics
222
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);
227
Dan Gohmanbe02b202010-04-09 01:39:53 +0000228 // 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.
Dan Gohman113902e2010-04-08 18:47:09 +0000231 unsigned Size = 0;
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,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000238 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000239 break;
240 }
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);
245 break;
246 }
247 case Intrinsic::memset: {
248 MemSetInst *MSI = cast<MemSetInst>(&I);
249 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0);
250 break;
251 }
252
253 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000254 Assert1(I.getParent()->getParent()->isVarArg(),
255 "Undefined behavior: va_start called in a non-varargs function",
256 &I);
257
Dan Gohman113902e2010-04-08 18:47:09 +0000258 visitMemoryReference(I, CS.getArgument(0), 0, 0);
259 break;
260 case Intrinsic::vacopy:
261 visitMemoryReference(I, CS.getArgument(0), 0, 0);
262 visitMemoryReference(I, CS.getArgument(1), 0, 0);
263 break;
264 case Intrinsic::vaend:
265 visitMemoryReference(I, CS.getArgument(0), 0, 0);
266 break;
267
268 case Intrinsic::stackrestore:
269 visitMemoryReference(I, CS.getArgument(0), 0, 0);
270 break;
271 }
272}
273
274void Lint::visitCallInst(CallInst &I) {
275 return visitCallSite(&I);
276}
277
278void Lint::visitInvokeInst(InvokeInst &I) {
279 return visitCallSite(&I);
280}
281
282void Lint::visitReturnInst(ReturnInst &I) {
283 Function *F = I.getParent()->getParent();
284 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000285 "Unusual: Return statement in function with noreturn attribute",
286 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000287}
288
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
292void Lint::visitMemoryReference(Instruction &I,
293 Value *Ptr, unsigned Align, const Type *Ty) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000294 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);
Dan Gohman113902e2010-04-08 18:47:09 +0000299
300 if (TD) {
301 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
302
303 if (Align != 0) {
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))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000309 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000310 }
311 }
312}
313
314void Lint::visitLoadInst(LoadInst &I) {
315 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType());
316}
317
318void Lint::visitStoreInst(StoreInst &I) {
319 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
320 I.getOperand(0)->getType());
321}
322
Dan Gohmanbe02b202010-04-09 01:39:53 +0000323void Lint::visitXor(BinaryOperator &I) {
324 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
325 !isa<UndefValue>(I.getOperand(1)),
326 "Undefined result: xor(undef, undef)", &I);
327}
328
329void Lint::visitSub(BinaryOperator &I) {
330 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
331 !isa<UndefValue>(I.getOperand(1)),
332 "Undefined result: sub(undef, undef)", &I);
333}
334
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000335void 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()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000339 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000340}
341
342void 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()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000346 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000347}
348
349void 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()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000353 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000354}
355
Dan Gohman113902e2010-04-08 18:47:09 +0000356static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000357 // Assume undef could be zero.
358 if (isa<UndefValue>(V)) return true;
359
Dan Gohman113902e2010-04-08 18:47:09 +0000360 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();
365}
366
367void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000368 Assert1(!isZero(I.getOperand(1), TD),
369 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000370}
371
372void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000373 Assert1(!isZero(I.getOperand(1), TD),
374 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000375}
376
377void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000378 Assert1(!isZero(I.getOperand(1), TD),
379 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000380}
381
382void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000383 Assert1(!isZero(I.getOperand(1), TD),
384 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000385}
386
387void 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(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000391 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000392}
393
394void Lint::visitVAArgInst(VAArgInst &I) {
395 visitMemoryReference(I, I.getOperand(0), 0, 0);
396}
397
398void Lint::visitIndirectBrInst(IndirectBrInst &I) {
399 visitMemoryReference(I, I.getAddress(), 0, 0);
400}
401
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000402void Lint::visitExtractElementInst(ExtractElementInst &I) {
403 if (ConstantInt *CI =
404 dyn_cast<ConstantInt>(I.getIndexOperand()->stripPointerCasts()))
405 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000406 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000407}
408
409void Lint::visitInsertElementInst(InsertElementInst &I) {
410 if (ConstantInt *CI =
411 dyn_cast<ConstantInt>(I.getOperand(2)->stripPointerCasts()))
412 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000413 "Undefined result: insertelement index out of range", &I);
414}
415
416void 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 "
421 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000422}
423
Dan Gohman113902e2010-04-08 18:47:09 +0000424//===----------------------------------------------------------------------===//
425// Implement the public interfaces to this file...
426//===----------------------------------------------------------------------===//
427
428FunctionPass *llvm::createLintPass() {
429 return new Lint();
430}
431
432/// lintFunction - Check a function for errors, printing messages on stderr.
433///
434void llvm::lintFunction(const Function &f) {
435 Function &F = const_cast<Function&>(f);
436 assert(!F.isDeclaration() && "Cannot lint external functions");
437
438 FunctionPassManager FPM(F.getParent());
439 Lint *V = new Lint();
440 FPM.add(V);
441 FPM.run(F);
442}
443
444/// lintModule - Check a module for errors, printing messages on stderr.
445/// Return true if the module is corrupt.
446///
447void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
448 PassManager PM;
449 Lint *V = new Lint();
450 PM.add(V);
451 PM.run(const_cast<Module&>(M));
452
453 if (ErrorInfo)
454 *ErrorInfo = V->MessagesStr.str();
455}