Add several more lint checks.
[oota-llvm.git] / lib / Analysis / Lint.cpp
1 //===-- 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.
23
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.
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"
50 #include "llvm/ADT/STLExtras.h"
51 using namespace llvm;
52
53 namespace {
54   class Lint : public FunctionPass, public InstVisitor<Lint> {
55     friend class InstVisitor<Lint>;
56
57     void visitFunction(Function &F);
58
59     void visitCallSite(CallSite CS);
60     void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
61                               const Type *Ty);
62
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);
83
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
150 char Lint::ID = 0;
151 static RegisterPass<Lint>
152 X("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 //
169 bool 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
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);
183 }
184
185 void 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(),
194             "Undefined behavior: Caller and callee calling convention differ",
195             &I);
196
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,
203             "Undefined behavior: Call argument count mismatches callee "
204             "argument count", &I);
205       
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
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.
231       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,
238               "Undefined behavior: memcpy source and destination overlap", &I);
239       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:
254       Assert1(I.getParent()->getParent()->isVarArg(),
255               "Undefined behavior: va_start called in a non-varargs function",
256               &I);
257
258       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
274 void Lint::visitCallInst(CallInst &I) {
275   return visitCallSite(&I);
276 }
277
278 void Lint::visitInvokeInst(InvokeInst &I) {
279   return visitCallSite(&I);
280 }
281
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",
286           &I);
287 }
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
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);
299
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))),
309               "Undefined behavior: Memory reference address is misaligned", &I);
310     }
311   }
312 }
313
314 void Lint::visitLoadInst(LoadInst &I) {
315   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType());
316 }
317
318 void Lint::visitStoreInst(StoreInst &I) {
319   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
320                   I.getOperand(0)->getType());
321 }
322
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);
327 }
328
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);
333 }
334
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);
340 }
341
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);
347 }
348
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);
354 }
355
356 static bool isZero(Value *V, TargetData *TD) {
357   // Assume undef could be zero.
358   if (isa<UndefValue>(V)) return true;
359
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();
365 }
366
367 void Lint::visitSDiv(BinaryOperator &I) {
368   Assert1(!isZero(I.getOperand(1), TD),
369           "Undefined behavior: Division by zero", &I);
370 }
371
372 void Lint::visitUDiv(BinaryOperator &I) {
373   Assert1(!isZero(I.getOperand(1), TD),
374           "Undefined behavior: Division by zero", &I);
375 }
376
377 void Lint::visitSRem(BinaryOperator &I) {
378   Assert1(!isZero(I.getOperand(1), TD),
379           "Undefined behavior: Division by zero", &I);
380 }
381
382 void Lint::visitURem(BinaryOperator &I) {
383   Assert1(!isZero(I.getOperand(1), TD),
384           "Undefined behavior: Division by zero", &I);
385 }
386
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);
392 }
393
394 void Lint::visitVAArgInst(VAArgInst &I) {
395   visitMemoryReference(I, I.getOperand(0), 0, 0);
396 }
397
398 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
399   visitMemoryReference(I, I.getAddress(), 0, 0);
400 }
401
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);
407 }
408
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);
414 }
415
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 "
421           "side effects", &I);
422 }
423
424 //===----------------------------------------------------------------------===//
425 //  Implement the public interfaces to this file...
426 //===----------------------------------------------------------------------===//
427
428 FunctionPass *llvm::createLintPass() {
429   return new Lint();
430 }
431
432 /// lintFunction - Check a function for errors, printing messages on stderr.
433 ///
434 void 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 ///
447 void 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 }