Eli pointed out that va_arg instruction result values don't
[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/InstructionSimplify.h"
39 #include "llvm/Analysis/ConstantFolding.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Analysis/Lint.h"
42 #include "llvm/Analysis/Loads.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Assembly/Writer.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Pass.h"
47 #include "llvm/PassManager.h"
48 #include "llvm/IntrinsicInst.h"
49 #include "llvm/Function.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/InstVisitor.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/ADT/STLExtras.h"
55 using namespace llvm;
56
57 namespace {
58   namespace MemRef {
59     static unsigned Read     = 1;
60     static unsigned Write    = 2;
61     static unsigned Callee   = 4;
62     static unsigned Branchee = 8;
63   }
64
65   class Lint : public FunctionPass, public InstVisitor<Lint> {
66     friend class InstVisitor<Lint>;
67
68     void visitFunction(Function &F);
69
70     void visitCallSite(CallSite CS);
71     void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
72                               const Type *Ty, unsigned Flags);
73
74     void visitCallInst(CallInst &I);
75     void visitInvokeInst(InvokeInst &I);
76     void visitReturnInst(ReturnInst &I);
77     void visitLoadInst(LoadInst &I);
78     void visitStoreInst(StoreInst &I);
79     void visitXor(BinaryOperator &I);
80     void visitSub(BinaryOperator &I);
81     void visitLShr(BinaryOperator &I);
82     void visitAShr(BinaryOperator &I);
83     void visitShl(BinaryOperator &I);
84     void visitSDiv(BinaryOperator &I);
85     void visitUDiv(BinaryOperator &I);
86     void visitSRem(BinaryOperator &I);
87     void visitURem(BinaryOperator &I);
88     void visitAllocaInst(AllocaInst &I);
89     void visitVAArgInst(VAArgInst &I);
90     void visitIndirectBrInst(IndirectBrInst &I);
91     void visitExtractElementInst(ExtractElementInst &I);
92     void visitInsertElementInst(InsertElementInst &I);
93     void visitUnreachableInst(UnreachableInst &I);
94
95     Value *findValue(Value *V, bool OffsetOk) const;
96
97   public:
98     Module *Mod;
99     AliasAnalysis *AA;
100     DominatorTree *DT;
101     TargetData *TD;
102
103     std::string Messages;
104     raw_string_ostream MessagesStr;
105
106     static char ID; // Pass identification, replacement for typeid
107     Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
108
109     virtual bool runOnFunction(Function &F);
110
111     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112       AU.setPreservesAll();
113       AU.addRequired<AliasAnalysis>();
114       AU.addRequired<DominatorTree>();
115     }
116     virtual void print(raw_ostream &O, const Module *M) const {}
117
118     void WriteValue(const Value *V) {
119       if (!V) return;
120       if (isa<Instruction>(V)) {
121         MessagesStr << *V << '\n';
122       } else {
123         WriteAsOperand(MessagesStr, V, true, Mod);
124         MessagesStr << '\n';
125       }
126     }
127
128     void WriteType(const Type *T) {
129       if (!T) return;
130       MessagesStr << ' ';
131       WriteTypeSymbolic(MessagesStr, T, Mod);
132     }
133
134     // CheckFailed - A check failed, so print out the condition and the message
135     // that failed.  This provides a nice place to put a breakpoint if you want
136     // to see why something is not correct.
137     void CheckFailed(const Twine &Message,
138                      const Value *V1 = 0, const Value *V2 = 0,
139                      const Value *V3 = 0, const Value *V4 = 0) {
140       MessagesStr << Message.str() << "\n";
141       WriteValue(V1);
142       WriteValue(V2);
143       WriteValue(V3);
144       WriteValue(V4);
145     }
146
147     void CheckFailed(const Twine &Message, const Value *V1,
148                      const Type *T2, const Value *V3 = 0) {
149       MessagesStr << Message.str() << "\n";
150       WriteValue(V1);
151       WriteType(T2);
152       WriteValue(V3);
153     }
154
155     void CheckFailed(const Twine &Message, const Type *T1,
156                      const Type *T2 = 0, const Type *T3 = 0) {
157       MessagesStr << Message.str() << "\n";
158       WriteType(T1);
159       WriteType(T2);
160       WriteType(T3);
161     }
162   };
163 }
164
165 char Lint::ID = 0;
166 static RegisterPass<Lint>
167 X("lint", "Statically lint-checks LLVM IR", false, true);
168
169 // Assert - We know that cond should be true, if not print an error message.
170 #define Assert(C, M) \
171     do { if (!(C)) { CheckFailed(M); return; } } while (0)
172 #define Assert1(C, M, V1) \
173     do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
174 #define Assert2(C, M, V1, V2) \
175     do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
176 #define Assert3(C, M, V1, V2, V3) \
177     do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
178 #define Assert4(C, M, V1, V2, V3, V4) \
179     do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
180
181 // Lint::run - This is the main Analysis entry point for a
182 // function.
183 //
184 bool Lint::runOnFunction(Function &F) {
185   Mod = F.getParent();
186   AA = &getAnalysis<AliasAnalysis>();
187   DT = &getAnalysis<DominatorTree>();
188   TD = getAnalysisIfAvailable<TargetData>();
189   visit(F);
190   dbgs() << MessagesStr.str();
191   Messages.clear();
192   return false;
193 }
194
195 void Lint::visitFunction(Function &F) {
196   // This isn't undefined behavior, it's just a little unusual, and it's a
197   // fairly common mistake to neglect to name a function.
198   Assert1(F.hasName() || F.hasLocalLinkage(),
199           "Unusual: Unnamed function with non-local linkage", &F);
200 }
201
202 void Lint::visitCallSite(CallSite CS) {
203   Instruction &I = *CS.getInstruction();
204   Value *Callee = CS.getCalledValue();
205
206   visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
207
208   if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
209     Assert1(CS.getCallingConv() == F->getCallingConv(),
210             "Undefined behavior: Caller and callee calling convention differ",
211             &I);
212
213     const FunctionType *FT = F->getFunctionType();
214     unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
215
216     Assert1(FT->isVarArg() ?
217               FT->getNumParams() <= NumActualArgs :
218               FT->getNumParams() == NumActualArgs,
219             "Undefined behavior: Call argument count mismatches callee "
220             "argument count", &I);
221       
222     // TODO: Check argument types (in case the callee was casted)
223
224     // TODO: Check ABI-significant attributes.
225
226     // TODO: Check noalias attribute.
227
228     // TODO: Check sret attribute.
229   }
230
231   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
232     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
233          AI != AE; ++AI) {
234       Value *Obj = findValue(*AI, /*OffsetOk=*/true);
235       Assert1(!isa<AllocaInst>(Obj),
236               "Undefined behavior: Call with \"tail\" keyword references "
237               "alloca", &I);
238     }
239
240
241   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
242     switch (II->getIntrinsicID()) {
243     default: break;
244
245     // TODO: Check more intrinsics
246
247     case Intrinsic::memcpy: {
248       MemCpyInst *MCI = cast<MemCpyInst>(&I);
249       visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
250                            MemRef::Write);
251       visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
252                            MemRef::Read);
253
254       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
255       // isn't expressive enough for what we really want to do. Known partial
256       // overlap is not distinguished from the case where nothing is known.
257       unsigned Size = 0;
258       if (const ConstantInt *Len =
259             dyn_cast<ConstantInt>(findValue(MCI->getLength(),
260                                             /*OffsetOk=*/false)))
261         if (Len->getValue().isIntN(32))
262           Size = Len->getValue().getZExtValue();
263       Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
264               AliasAnalysis::MustAlias,
265               "Undefined behavior: memcpy source and destination overlap", &I);
266       break;
267     }
268     case Intrinsic::memmove: {
269       MemMoveInst *MMI = cast<MemMoveInst>(&I);
270       visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
271                            MemRef::Write);
272       visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
273                            MemRef::Read);
274       break;
275     }
276     case Intrinsic::memset: {
277       MemSetInst *MSI = cast<MemSetInst>(&I);
278       visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
279                            MemRef::Write);
280       break;
281     }
282
283     case Intrinsic::vastart:
284       Assert1(I.getParent()->getParent()->isVarArg(),
285               "Undefined behavior: va_start called in a non-varargs function",
286               &I);
287
288       visitMemoryReference(I, CS.getArgument(0), 0, 0,
289                            MemRef::Read | MemRef::Write);
290       break;
291     case Intrinsic::vacopy:
292       visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
293       visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
294       break;
295     case Intrinsic::vaend:
296       visitMemoryReference(I, CS.getArgument(0), 0, 0,
297                            MemRef::Read | MemRef::Write);
298       break;
299
300     case Intrinsic::stackrestore:
301       // Stackrestore doesn't read or write memory, but it sets the
302       // stack pointer, which the compiler may read from or write to
303       // at any time, so check it for both readability and writeability.
304       visitMemoryReference(I, CS.getArgument(0), 0, 0,
305                            MemRef::Read | MemRef::Write);
306       break;
307     }
308 }
309
310 void Lint::visitCallInst(CallInst &I) {
311   return visitCallSite(&I);
312 }
313
314 void Lint::visitInvokeInst(InvokeInst &I) {
315   return visitCallSite(&I);
316 }
317
318 void Lint::visitReturnInst(ReturnInst &I) {
319   Function *F = I.getParent()->getParent();
320   Assert1(!F->doesNotReturn(),
321           "Unusual: Return statement in function with noreturn attribute",
322           &I);
323
324   if (Value *V = I.getReturnValue()) {
325     Value *Obj = findValue(V, /*OffsetOk=*/true);
326     Assert1(!isa<AllocaInst>(Obj),
327             "Unusual: Returning alloca value", &I);
328   }
329 }
330
331 // TODO: Add a length argument and check that the reference is in bounds
332 void Lint::visitMemoryReference(Instruction &I,
333                                 Value *Ptr, unsigned Align, const Type *Ty,
334                                 unsigned Flags) {
335   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
336   Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
337           "Undefined behavior: Null pointer dereference", &I);
338   Assert1(!isa<UndefValue>(UnderlyingObject),
339           "Undefined behavior: Undef pointer dereference", &I);
340
341   if (Flags & MemRef::Write) {
342     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
343       Assert1(!GV->isConstant(),
344               "Undefined behavior: Write to read-only memory", &I);
345     Assert1(!isa<Function>(UnderlyingObject) &&
346             !isa<BlockAddress>(UnderlyingObject),
347             "Undefined behavior: Write to text section", &I);
348   }
349   if (Flags & MemRef::Read) {
350     Assert1(!isa<Function>(UnderlyingObject),
351             "Unusual: Load from function body", &I);
352     Assert1(!isa<BlockAddress>(UnderlyingObject),
353             "Undefined behavior: Load from block address", &I);
354   }
355   if (Flags & MemRef::Callee) {
356     Assert1(!isa<BlockAddress>(UnderlyingObject),
357             "Undefined behavior: Call to block address", &I);
358   }
359   if (Flags & MemRef::Branchee) {
360     Assert1(!isa<Constant>(UnderlyingObject) ||
361             isa<BlockAddress>(UnderlyingObject),
362             "Undefined behavior: Branch to non-blockaddress", &I);
363   }
364
365   if (TD) {
366     if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
367
368     if (Align != 0) {
369       unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
370       APInt Mask = APInt::getAllOnesValue(BitWidth),
371                    KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
372       ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
373       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
374               "Undefined behavior: Memory reference address is misaligned", &I);
375     }
376   }
377 }
378
379 void Lint::visitLoadInst(LoadInst &I) {
380   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
381                        MemRef::Read);
382 }
383
384 void Lint::visitStoreInst(StoreInst &I) {
385   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
386                   I.getOperand(0)->getType(), MemRef::Write);
387 }
388
389 void Lint::visitXor(BinaryOperator &I) {
390   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
391           !isa<UndefValue>(I.getOperand(1)),
392           "Undefined result: xor(undef, undef)", &I);
393 }
394
395 void Lint::visitSub(BinaryOperator &I) {
396   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
397           !isa<UndefValue>(I.getOperand(1)),
398           "Undefined result: sub(undef, undef)", &I);
399 }
400
401 void Lint::visitLShr(BinaryOperator &I) {
402   if (ConstantInt *CI =
403         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
404     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
405             "Undefined result: Shift count out of range", &I);
406 }
407
408 void Lint::visitAShr(BinaryOperator &I) {
409   if (ConstantInt *CI =
410         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
411     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
412             "Undefined result: Shift count out of range", &I);
413 }
414
415 void Lint::visitShl(BinaryOperator &I) {
416   if (ConstantInt *CI =
417         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
418     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
419             "Undefined result: Shift count out of range", &I);
420 }
421
422 static bool isZero(Value *V, TargetData *TD) {
423   // Assume undef could be zero.
424   if (isa<UndefValue>(V)) return true;
425
426   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
427   APInt Mask = APInt::getAllOnesValue(BitWidth),
428                KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
429   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
430   return KnownZero.isAllOnesValue();
431 }
432
433 void Lint::visitSDiv(BinaryOperator &I) {
434   Assert1(!isZero(I.getOperand(1), TD),
435           "Undefined behavior: Division by zero", &I);
436 }
437
438 void Lint::visitUDiv(BinaryOperator &I) {
439   Assert1(!isZero(I.getOperand(1), TD),
440           "Undefined behavior: Division by zero", &I);
441 }
442
443 void Lint::visitSRem(BinaryOperator &I) {
444   Assert1(!isZero(I.getOperand(1), TD),
445           "Undefined behavior: Division by zero", &I);
446 }
447
448 void Lint::visitURem(BinaryOperator &I) {
449   Assert1(!isZero(I.getOperand(1), TD),
450           "Undefined behavior: Division by zero", &I);
451 }
452
453 void Lint::visitAllocaInst(AllocaInst &I) {
454   if (isa<ConstantInt>(I.getArraySize()))
455     // This isn't undefined behavior, it's just an obvious pessimization.
456     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
457             "Pessimization: Static alloca outside of entry block", &I);
458 }
459
460 void Lint::visitVAArgInst(VAArgInst &I) {
461   visitMemoryReference(I, I.getOperand(0), 0, 0,
462                        MemRef::Read | MemRef::Write);
463 }
464
465 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
466   visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
467 }
468
469 void Lint::visitExtractElementInst(ExtractElementInst &I) {
470   if (ConstantInt *CI =
471         dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
472                                         /*OffsetOk=*/false)))
473     Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
474             "Undefined result: extractelement index out of range", &I);
475 }
476
477 void Lint::visitInsertElementInst(InsertElementInst &I) {
478   if (ConstantInt *CI =
479         dyn_cast<ConstantInt>(findValue(I.getOperand(2),
480                                         /*OffsetOk=*/false)))
481     Assert1(CI->getValue().ult(I.getType()->getNumElements()),
482             "Undefined result: insertelement index out of range", &I);
483 }
484
485 void Lint::visitUnreachableInst(UnreachableInst &I) {
486   // This isn't undefined behavior, it's merely suspicious.
487   Assert1(&I == I.getParent()->begin() ||
488           prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
489           "Unusual: unreachable immediately preceded by instruction without "
490           "side effects", &I);
491 }
492
493 /// findValue - Look through bitcasts and simple memory reference patterns
494 /// to identify an equivalent, but more informative, value.  If OffsetOk
495 /// is true, look through getelementptrs with non-zero offsets too.
496 ///
497 /// Most analysis passes don't require this logic, because instcombine
498 /// will simplify most of these kinds of things away. But it's a goal of
499 /// this Lint pass to be useful even on non-optimized IR.
500 Value *Lint::findValue(Value *V, bool OffsetOk) const {
501   // TODO: Look through sext or zext cast, when the result is known to
502   // be interpreted as signed or unsigned, respectively.
503   // TODO: Look through calls with unique return values.
504   // TODO: Look through vector insert/extract/shuffle.
505   V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
506   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
507     BasicBlock::iterator BBI = L;
508     BasicBlock *BB = L->getParent();
509     for (;;) {
510       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
511                                               BB, BBI, 6, AA))
512         return findValue(U, OffsetOk);
513       BB = L->getParent()->getUniquePredecessor();
514       if (!BB) break;
515       BBI = BB->end();
516     }
517   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
518     if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
519                             Type::getInt64Ty(V->getContext())))
520       return findValue(CI->getOperand(0), OffsetOk);
521   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
522     if (Value *W = PN->hasConstantValue(DT))
523       return findValue(W, OffsetOk);
524   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
525     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
526                                      Ex->idx_begin(),
527                                      Ex->idx_end()))
528       if (W != V)
529         return findValue(W, OffsetOk);
530   }
531
532   // As a last resort, try SimplifyInstruction or constant folding.
533   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
534     if (Value *W = SimplifyInstruction(Inst, TD))
535       if (W != Inst)
536         return findValue(W, OffsetOk);
537   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
538     if (Value *W = ConstantFoldConstantExpression(CE, TD))
539       if (W != V)
540         return findValue(W, OffsetOk);
541   }
542
543   return V;
544 }
545
546 //===----------------------------------------------------------------------===//
547 //  Implement the public interfaces to this file...
548 //===----------------------------------------------------------------------===//
549
550 FunctionPass *llvm::createLintPass() {
551   return new Lint();
552 }
553
554 /// lintFunction - Check a function for errors, printing messages on stderr.
555 ///
556 void llvm::lintFunction(const Function &f) {
557   Function &F = const_cast<Function&>(f);
558   assert(!F.isDeclaration() && "Cannot lint external functions");
559
560   FunctionPassManager FPM(F.getParent());
561   Lint *V = new Lint();
562   FPM.add(V);
563   FPM.run(F);
564 }
565
566 /// lintModule - Check a module for errors, printing messages on stderr.
567 ///
568 void llvm::lintModule(const Module &M) {
569   PassManager PM;
570   Lint *V = new Lint();
571   PM.add(V);
572   PM.run(const_cast<Module&>(M));
573 }