Add a lint check for returning the address of stack memory.
[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   namespace MemRef {
55     static unsigned Read     = 1;
56     static unsigned Write    = 2;
57     static unsigned Callee   = 4;
58     static unsigned Branchee = 8;
59   }
60
61   class Lint : public FunctionPass, public InstVisitor<Lint> {
62     friend class InstVisitor<Lint>;
63
64     void visitFunction(Function &F);
65
66     void visitCallSite(CallSite CS);
67     void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
68                               const Type *Ty, unsigned Flags);
69
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);
90
91   public:
92     Module *Mod;
93     AliasAnalysis *AA;
94     TargetData *TD;
95
96     std::string Messages;
97     raw_string_ostream MessagesStr;
98
99     static char ID; // Pass identification, replacement for typeid
100     Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
101
102     virtual bool runOnFunction(Function &F);
103
104     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
105       AU.setPreservesAll();
106       AU.addRequired<AliasAnalysis>();
107     }
108     virtual void print(raw_ostream &O, const Module *M) const {}
109
110     void WriteValue(const Value *V) {
111       if (!V) return;
112       if (isa<Instruction>(V)) {
113         MessagesStr << *V << '\n';
114       } else {
115         WriteAsOperand(MessagesStr, V, true, Mod);
116         MessagesStr << '\n';
117       }
118     }
119
120     void WriteType(const Type *T) {
121       if (!T) return;
122       MessagesStr << ' ';
123       WriteTypeSymbolic(MessagesStr, T, Mod);
124     }
125
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";
133       WriteValue(V1);
134       WriteValue(V2);
135       WriteValue(V3);
136       WriteValue(V4);
137     }
138
139     void CheckFailed(const Twine &Message, const Value *V1,
140                      const Type *T2, const Value *V3 = 0) {
141       MessagesStr << Message.str() << "\n";
142       WriteValue(V1);
143       WriteType(T2);
144       WriteValue(V3);
145     }
146
147     void CheckFailed(const Twine &Message, const Type *T1,
148                      const Type *T2 = 0, const Type *T3 = 0) {
149       MessagesStr << Message.str() << "\n";
150       WriteType(T1);
151       WriteType(T2);
152       WriteType(T3);
153     }
154   };
155 }
156
157 char Lint::ID = 0;
158 static RegisterPass<Lint>
159 X("lint", "Statically lint-checks LLVM IR", false, true);
160
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)
172
173 // Lint::run - This is the main Analysis entry point for a
174 // function.
175 //
176 bool Lint::runOnFunction(Function &F) {
177   Mod = F.getParent();
178   AA = &getAnalysis<AliasAnalysis>();
179   TD = getAnalysisIfAvailable<TargetData>();
180   visit(F);
181   dbgs() << MessagesStr.str();
182   Messages.clear();
183   return false;
184 }
185
186 void Lint::visitFunction(Function &F) {
187   // This isn't undefined behavior, it's just a little unusual, and it's a
188   // fairly common mistake to neglect to name a function.
189   Assert1(F.hasName() || F.hasLocalLinkage(),
190           "Unusual: Unnamed function with non-local linkage", &F);
191 }
192
193 void Lint::visitCallSite(CallSite CS) {
194   Instruction &I = *CS.getInstruction();
195   Value *Callee = CS.getCalledValue();
196
197   visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
198
199   if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
200     Assert1(CS.getCallingConv() == F->getCallingConv(),
201             "Undefined behavior: Caller and callee calling convention differ",
202             &I);
203
204     const FunctionType *FT = F->getFunctionType();
205     unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
206
207     Assert1(FT->isVarArg() ?
208               FT->getNumParams() <= NumActualArgs :
209               FT->getNumParams() == NumActualArgs,
210             "Undefined behavior: Call argument count mismatches callee "
211             "argument count", &I);
212       
213     // TODO: Check argument types (in case the callee was casted)
214
215     // TODO: Check ABI-significant attributes.
216
217     // TODO: Check noalias attribute.
218
219     // TODO: Check sret attribute.
220   }
221
222   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
223     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
224          AI != AE; ++AI) {
225       Value *Obj = (*AI)->getUnderlyingObject();
226       Assert1(!isa<AllocaInst>(Obj) && !isa<VAArgInst>(Obj),
227               "Undefined behavior: Call with \"tail\" keyword references "
228               "alloca or va_arg", &I);
229     }
230
231
232   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
233     switch (II->getIntrinsicID()) {
234     default: break;
235
236     // TODO: Check more intrinsics
237
238     case Intrinsic::memcpy: {
239       MemCpyInst *MCI = cast<MemCpyInst>(&I);
240       visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
241                            MemRef::Write);
242       visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
243                            MemRef::Read);
244
245       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
246       // isn't expressive enough for what we really want to do. Known partial
247       // overlap is not distinguished from the case where nothing is known.
248       unsigned Size = 0;
249       if (const ConstantInt *Len =
250             dyn_cast<ConstantInt>(MCI->getLength()->stripPointerCasts()))
251         if (Len->getValue().isIntN(32))
252           Size = Len->getValue().getZExtValue();
253       Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
254               AliasAnalysis::MustAlias,
255               "Undefined behavior: memcpy source and destination overlap", &I);
256       break;
257     }
258     case Intrinsic::memmove: {
259       MemMoveInst *MMI = cast<MemMoveInst>(&I);
260       visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
261                            MemRef::Write);
262       visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
263                            MemRef::Read);
264       break;
265     }
266     case Intrinsic::memset: {
267       MemSetInst *MSI = cast<MemSetInst>(&I);
268       visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
269                            MemRef::Write);
270       break;
271     }
272
273     case Intrinsic::vastart:
274       Assert1(I.getParent()->getParent()->isVarArg(),
275               "Undefined behavior: va_start called in a non-varargs function",
276               &I);
277
278       visitMemoryReference(I, CS.getArgument(0), 0, 0,
279                            MemRef::Read | MemRef::Write);
280       break;
281     case Intrinsic::vacopy:
282       visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
283       visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
284       break;
285     case Intrinsic::vaend:
286       visitMemoryReference(I, CS.getArgument(0), 0, 0,
287                            MemRef::Read | MemRef::Write);
288       break;
289
290     case Intrinsic::stackrestore:
291       // Stackrestore doesn't read or write memory, but it sets the
292       // stack pointer, which the compiler may read from or write to
293       // at any time, so check it for both readability and writeability.
294       visitMemoryReference(I, CS.getArgument(0), 0, 0,
295                            MemRef::Read | MemRef::Write);
296       break;
297     }
298 }
299
300 void Lint::visitCallInst(CallInst &I) {
301   return visitCallSite(&I);
302 }
303
304 void Lint::visitInvokeInst(InvokeInst &I) {
305   return visitCallSite(&I);
306 }
307
308 void Lint::visitReturnInst(ReturnInst &I) {
309   Function *F = I.getParent()->getParent();
310   Assert1(!F->doesNotReturn(),
311           "Unusual: Return statement in function with noreturn attribute",
312           &I);
313
314   if (Value *V = I.getReturnValue()) {
315     Value *Obj = V->getUnderlyingObject();
316     Assert1(!isa<AllocaInst>(Obj) && !isa<VAArgInst>(Obj),
317             "Unusual: Returning alloca or va_arg value", &I);
318   }
319 }
320
321 // TODO: Add a length argument and check that the reference is in bounds
322 void Lint::visitMemoryReference(Instruction &I,
323                                 Value *Ptr, unsigned Align, const Type *Ty,
324                                 unsigned Flags) {
325   Value *UnderlyingObject = Ptr->getUnderlyingObject();
326   Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
327           "Undefined behavior: Null pointer dereference", &I);
328   Assert1(!isa<UndefValue>(UnderlyingObject),
329           "Undefined behavior: Undef pointer dereference", &I);
330
331   if (Flags & MemRef::Write) {
332     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
333       Assert1(!GV->isConstant(),
334               "Undefined behavior: Write to read-only memory", &I);
335     Assert1(!isa<Function>(UnderlyingObject) &&
336             !isa<BlockAddress>(UnderlyingObject),
337             "Undefined behavior: Write to text section", &I);
338   }
339   if (Flags & MemRef::Read) {
340     Assert1(!isa<Function>(UnderlyingObject),
341             "Unusual: Load from function body", &I);
342     Assert1(!isa<BlockAddress>(UnderlyingObject),
343             "Undefined behavior: Load from block address", &I);
344   }
345   if (Flags & MemRef::Callee) {
346     Assert1(!isa<BlockAddress>(UnderlyingObject),
347             "Undefined behavior: Call to block address", &I);
348   }
349   if (Flags & MemRef::Branchee) {
350     Assert1(!isa<Constant>(UnderlyingObject) ||
351             isa<BlockAddress>(UnderlyingObject),
352             "Undefined behavior: Branch to non-blockaddress", &I);
353   }
354
355   if (TD) {
356     if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
357
358     if (Align != 0) {
359       unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
360       APInt Mask = APInt::getAllOnesValue(BitWidth),
361                    KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
362       ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
363       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
364               "Undefined behavior: Memory reference address is misaligned", &I);
365     }
366   }
367 }
368
369 void Lint::visitLoadInst(LoadInst &I) {
370   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
371                        MemRef::Read);
372 }
373
374 void Lint::visitStoreInst(StoreInst &I) {
375   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
376                   I.getOperand(0)->getType(), MemRef::Write);
377 }
378
379 void Lint::visitXor(BinaryOperator &I) {
380   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
381           !isa<UndefValue>(I.getOperand(1)),
382           "Undefined result: xor(undef, undef)", &I);
383 }
384
385 void Lint::visitSub(BinaryOperator &I) {
386   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
387           !isa<UndefValue>(I.getOperand(1)),
388           "Undefined result: sub(undef, undef)", &I);
389 }
390
391 void Lint::visitLShr(BinaryOperator &I) {
392   if (ConstantInt *CI =
393         dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
394     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
395             "Undefined result: Shift count out of range", &I);
396 }
397
398 void Lint::visitAShr(BinaryOperator &I) {
399   if (ConstantInt *CI =
400         dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
401     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
402             "Undefined result: Shift count out of range", &I);
403 }
404
405 void Lint::visitShl(BinaryOperator &I) {
406   if (ConstantInt *CI =
407         dyn_cast<ConstantInt>(I.getOperand(1)->stripPointerCasts()))
408     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
409             "Undefined result: Shift count out of range", &I);
410 }
411
412 static bool isZero(Value *V, TargetData *TD) {
413   // Assume undef could be zero.
414   if (isa<UndefValue>(V)) return true;
415
416   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
417   APInt Mask = APInt::getAllOnesValue(BitWidth),
418                KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
419   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
420   return KnownZero.isAllOnesValue();
421 }
422
423 void Lint::visitSDiv(BinaryOperator &I) {
424   Assert1(!isZero(I.getOperand(1), TD),
425           "Undefined behavior: Division by zero", &I);
426 }
427
428 void Lint::visitUDiv(BinaryOperator &I) {
429   Assert1(!isZero(I.getOperand(1), TD),
430           "Undefined behavior: Division by zero", &I);
431 }
432
433 void Lint::visitSRem(BinaryOperator &I) {
434   Assert1(!isZero(I.getOperand(1), TD),
435           "Undefined behavior: Division by zero", &I);
436 }
437
438 void Lint::visitURem(BinaryOperator &I) {
439   Assert1(!isZero(I.getOperand(1), TD),
440           "Undefined behavior: Division by zero", &I);
441 }
442
443 void Lint::visitAllocaInst(AllocaInst &I) {
444   if (isa<ConstantInt>(I.getArraySize()))
445     // This isn't undefined behavior, it's just an obvious pessimization.
446     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
447             "Pessimization: Static alloca outside of entry block", &I);
448 }
449
450 void Lint::visitVAArgInst(VAArgInst &I) {
451   visitMemoryReference(I, I.getOperand(0), 0, 0,
452                        MemRef::Read | MemRef::Write);
453 }
454
455 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
456   visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
457 }
458
459 void Lint::visitExtractElementInst(ExtractElementInst &I) {
460   if (ConstantInt *CI =
461         dyn_cast<ConstantInt>(I.getIndexOperand()->stripPointerCasts()))
462     Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
463             "Undefined result: extractelement index out of range", &I);
464 }
465
466 void Lint::visitInsertElementInst(InsertElementInst &I) {
467   if (ConstantInt *CI =
468         dyn_cast<ConstantInt>(I.getOperand(2)->stripPointerCasts()))
469     Assert1(CI->getValue().ult(I.getType()->getNumElements()),
470             "Undefined result: insertelement index out of range", &I);
471 }
472
473 void Lint::visitUnreachableInst(UnreachableInst &I) {
474   // This isn't undefined behavior, it's merely suspicious.
475   Assert1(&I == I.getParent()->begin() ||
476           prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
477           "Unusual: unreachable immediately preceded by instruction without "
478           "side effects", &I);
479 }
480
481 //===----------------------------------------------------------------------===//
482 //  Implement the public interfaces to this file...
483 //===----------------------------------------------------------------------===//
484
485 FunctionPass *llvm::createLintPass() {
486   return new Lint();
487 }
488
489 /// lintFunction - Check a function for errors, printing messages on stderr.
490 ///
491 void llvm::lintFunction(const Function &f) {
492   Function &F = const_cast<Function&>(f);
493   assert(!F.isDeclaration() && "Cannot lint external functions");
494
495   FunctionPassManager FPM(F.getParent());
496   Lint *V = new Lint();
497   FPM.add(V);
498   FPM.run(F);
499 }
500
501 /// lintModule - Check a module for errors, printing messages on stderr.
502 ///
503 void llvm::lintModule(const Module &M) {
504   PassManager PM;
505   Lint *V = new Lint();
506   PM.add(V);
507   PM.run(const_cast<Module&>(M));
508 }