blob: 91929be3462df02c252387a42ff042d0d7b05470 [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"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000038#include "llvm/Analysis/InstructionSimplify.h"
39#include "llvm/Analysis/ConstantFolding.h"
40#include "llvm/Analysis/Dominators.h"
Dan Gohman113902e2010-04-08 18:47:09 +000041#include "llvm/Analysis/Lint.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000042#include "llvm/Analysis/Loads.h"
Dan Gohman113902e2010-04-08 18:47:09 +000043#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"
Dan Gohmanbe02b202010-04-09 01:39:53 +000054#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000055using namespace llvm;
56
57namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000058 namespace MemRef {
59 static unsigned Read = 1;
60 static unsigned Write = 2;
61 static unsigned Callee = 4;
62 static unsigned Branchee = 8;
63 }
64
Dan Gohman113902e2010-04-08 18:47:09 +000065 class Lint : public FunctionPass, public InstVisitor<Lint> {
66 friend class InstVisitor<Lint>;
67
Dan Gohmanbe02b202010-04-09 01:39:53 +000068 void visitFunction(Function &F);
69
Dan Gohman113902e2010-04-08 18:47:09 +000070 void visitCallSite(CallSite CS);
71 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
Dan Gohman5b61b382010-04-30 19:05:00 +000072 const Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000073
Dan Gohman113902e2010-04-08 18:47:09 +000074 void visitCallInst(CallInst &I);
75 void visitInvokeInst(InvokeInst &I);
76 void visitReturnInst(ReturnInst &I);
77 void visitLoadInst(LoadInst &I);
78 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000079 void visitXor(BinaryOperator &I);
80 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000081 void visitLShr(BinaryOperator &I);
82 void visitAShr(BinaryOperator &I);
83 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000084 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);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000091 void visitExtractElementInst(ExtractElementInst &I);
92 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000093 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000094
Dan Gohmanff26d4e2010-05-28 16:21:24 +000095 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman17d95962010-05-28 16:45:33 +000096 Value *findValueImpl(Value *V, bool OffsetOk,
97 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +000098
Dan Gohman113902e2010-04-08 18:47:09 +000099 public:
100 Module *Mod;
101 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000102 DominatorTree *DT;
Dan Gohman113902e2010-04-08 18:47:09 +0000103 TargetData *TD;
104
105 std::string Messages;
106 raw_string_ostream MessagesStr;
107
108 static char ID; // Pass identification, replacement for typeid
109 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
110
111 virtual bool runOnFunction(Function &F);
112
113 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.setPreservesAll();
115 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000116 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000117 }
118 virtual void print(raw_ostream &O, const Module *M) const {}
119
120 void WriteValue(const Value *V) {
121 if (!V) return;
122 if (isa<Instruction>(V)) {
123 MessagesStr << *V << '\n';
124 } else {
125 WriteAsOperand(MessagesStr, V, true, Mod);
126 MessagesStr << '\n';
127 }
128 }
129
130 void WriteType(const Type *T) {
131 if (!T) return;
132 MessagesStr << ' ';
133 WriteTypeSymbolic(MessagesStr, T, Mod);
134 }
135
136 // CheckFailed - A check failed, so print out the condition and the message
137 // that failed. This provides a nice place to put a breakpoint if you want
138 // to see why something is not correct.
139 void CheckFailed(const Twine &Message,
140 const Value *V1 = 0, const Value *V2 = 0,
141 const Value *V3 = 0, const Value *V4 = 0) {
142 MessagesStr << Message.str() << "\n";
143 WriteValue(V1);
144 WriteValue(V2);
145 WriteValue(V3);
146 WriteValue(V4);
147 }
148
149 void CheckFailed(const Twine &Message, const Value *V1,
150 const Type *T2, const Value *V3 = 0) {
151 MessagesStr << Message.str() << "\n";
152 WriteValue(V1);
153 WriteType(T2);
154 WriteValue(V3);
155 }
156
157 void CheckFailed(const Twine &Message, const Type *T1,
158 const Type *T2 = 0, const Type *T3 = 0) {
159 MessagesStr << Message.str() << "\n";
160 WriteType(T1);
161 WriteType(T2);
162 WriteType(T3);
163 }
164 };
165}
166
167char Lint::ID = 0;
168static RegisterPass<Lint>
169X("lint", "Statically lint-checks LLVM IR", false, true);
170
171// Assert - We know that cond should be true, if not print an error message.
172#define Assert(C, M) \
173 do { if (!(C)) { CheckFailed(M); return; } } while (0)
174#define Assert1(C, M, V1) \
175 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
176#define Assert2(C, M, V1, V2) \
177 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
178#define Assert3(C, M, V1, V2, V3) \
179 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
180#define Assert4(C, M, V1, V2, V3, V4) \
181 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
182
183// Lint::run - This is the main Analysis entry point for a
184// function.
185//
186bool Lint::runOnFunction(Function &F) {
187 Mod = F.getParent();
188 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000189 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000190 TD = getAnalysisIfAvailable<TargetData>();
191 visit(F);
192 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000193 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000194 return false;
195}
196
Dan Gohmanbe02b202010-04-09 01:39:53 +0000197void Lint::visitFunction(Function &F) {
198 // This isn't undefined behavior, it's just a little unusual, and it's a
199 // fairly common mistake to neglect to name a function.
200 Assert1(F.hasName() || F.hasLocalLinkage(),
201 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman113902e2010-04-08 18:47:09 +0000202}
203
204void Lint::visitCallSite(CallSite CS) {
205 Instruction &I = *CS.getInstruction();
206 Value *Callee = CS.getCalledValue();
207
Dan Gohman5b61b382010-04-30 19:05:00 +0000208 visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000209
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000210 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000211 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000212 "Undefined behavior: Caller and callee calling convention differ",
213 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000214
215 const FunctionType *FT = F->getFunctionType();
216 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
217
218 Assert1(FT->isVarArg() ?
219 FT->getNumParams() <= NumActualArgs :
220 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000221 "Undefined behavior: Call argument count mismatches callee "
222 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000223
224 // TODO: Check argument types (in case the callee was casted)
225
226 // TODO: Check ABI-significant attributes.
227
228 // TODO: Check noalias attribute.
229
230 // TODO: Check sret attribute.
231 }
232
Dan Gohman113b3e22010-05-26 21:46:36 +0000233 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
234 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
235 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000236 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000237 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000238 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000239 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000240 }
241
Dan Gohman113902e2010-04-08 18:47:09 +0000242
243 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
244 switch (II->getIntrinsicID()) {
245 default: break;
246
247 // TODO: Check more intrinsics
248
249 case Intrinsic::memcpy: {
250 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000251 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000252 MemRef::Write);
253 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000254 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000255
Dan Gohmanbe02b202010-04-09 01:39:53 +0000256 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
257 // isn't expressive enough for what we really want to do. Known partial
258 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000259 unsigned Size = 0;
260 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000261 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
262 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000263 if (Len->getValue().isIntN(32))
264 Size = Len->getValue().getZExtValue();
265 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
266 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000267 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000268 break;
269 }
270 case Intrinsic::memmove: {
271 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000272 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000273 MemRef::Write);
274 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000275 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000276 break;
277 }
278 case Intrinsic::memset: {
279 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000280 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
281 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000282 break;
283 }
284
285 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000286 Assert1(I.getParent()->getParent()->isVarArg(),
287 "Undefined behavior: va_start called in a non-varargs function",
288 &I);
289
Dan Gohman5b61b382010-04-30 19:05:00 +0000290 visitMemoryReference(I, CS.getArgument(0), 0, 0,
291 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000292 break;
293 case Intrinsic::vacopy:
Dan Gohman5b61b382010-04-30 19:05:00 +0000294 visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
295 visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000296 break;
297 case Intrinsic::vaend:
Dan Gohman5b61b382010-04-30 19:05:00 +0000298 visitMemoryReference(I, CS.getArgument(0), 0, 0,
299 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000300 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000301
302 case Intrinsic::stackrestore:
303 // Stackrestore doesn't read or write memory, but it sets the
304 // stack pointer, which the compiler may read from or write to
305 // at any time, so check it for both readability and writeability.
306 visitMemoryReference(I, CS.getArgument(0), 0, 0,
307 MemRef::Read | MemRef::Write);
308 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000309 }
310}
311
312void Lint::visitCallInst(CallInst &I) {
313 return visitCallSite(&I);
314}
315
316void Lint::visitInvokeInst(InvokeInst &I) {
317 return visitCallSite(&I);
318}
319
320void Lint::visitReturnInst(ReturnInst &I) {
321 Function *F = I.getParent()->getParent();
322 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000323 "Unusual: Return statement in function with noreturn attribute",
324 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000325
326 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000327 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000328 Assert1(!isa<AllocaInst>(Obj),
329 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000330 }
Dan Gohman113902e2010-04-08 18:47:09 +0000331}
332
333// TODO: Add a length argument and check that the reference is in bounds
Dan Gohman113902e2010-04-08 18:47:09 +0000334void Lint::visitMemoryReference(Instruction &I,
Dan Gohman5b61b382010-04-30 19:05:00 +0000335 Value *Ptr, unsigned Align, const Type *Ty,
336 unsigned Flags) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000337 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000338 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
339 "Undefined behavior: Null pointer dereference", &I);
340 Assert1(!isa<UndefValue>(UnderlyingObject),
341 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000342
Dan Gohman5b61b382010-04-30 19:05:00 +0000343 if (Flags & MemRef::Write) {
344 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
345 Assert1(!GV->isConstant(),
346 "Undefined behavior: Write to read-only memory", &I);
347 Assert1(!isa<Function>(UnderlyingObject) &&
348 !isa<BlockAddress>(UnderlyingObject),
349 "Undefined behavior: Write to text section", &I);
350 }
351 if (Flags & MemRef::Read) {
352 Assert1(!isa<Function>(UnderlyingObject),
353 "Unusual: Load from function body", &I);
354 Assert1(!isa<BlockAddress>(UnderlyingObject),
355 "Undefined behavior: Load from block address", &I);
356 }
357 if (Flags & MemRef::Callee) {
358 Assert1(!isa<BlockAddress>(UnderlyingObject),
359 "Undefined behavior: Call to block address", &I);
360 }
361 if (Flags & MemRef::Branchee) {
362 Assert1(!isa<Constant>(UnderlyingObject) ||
363 isa<BlockAddress>(UnderlyingObject),
364 "Undefined behavior: Branch to non-blockaddress", &I);
365 }
366
Dan Gohman113902e2010-04-08 18:47:09 +0000367 if (TD) {
368 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
369
370 if (Align != 0) {
371 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
372 APInt Mask = APInt::getAllOnesValue(BitWidth),
373 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
374 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
375 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000376 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000377 }
378 }
379}
380
381void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000382 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
383 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000384}
385
386void Lint::visitStoreInst(StoreInst &I) {
387 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
Dan Gohman5b61b382010-04-30 19:05:00 +0000388 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000389}
390
Dan Gohmanbe02b202010-04-09 01:39:53 +0000391void Lint::visitXor(BinaryOperator &I) {
392 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
393 !isa<UndefValue>(I.getOperand(1)),
394 "Undefined result: xor(undef, undef)", &I);
395}
396
397void Lint::visitSub(BinaryOperator &I) {
398 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
399 !isa<UndefValue>(I.getOperand(1)),
400 "Undefined result: sub(undef, undef)", &I);
401}
402
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000403void Lint::visitLShr(BinaryOperator &I) {
404 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000405 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000406 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000407 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000408}
409
410void Lint::visitAShr(BinaryOperator &I) {
411 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000412 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000413 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000414 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000415}
416
417void Lint::visitShl(BinaryOperator &I) {
418 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000419 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000420 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000421 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000422}
423
Dan Gohman113902e2010-04-08 18:47:09 +0000424static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000425 // Assume undef could be zero.
426 if (isa<UndefValue>(V)) return true;
427
Dan Gohman113902e2010-04-08 18:47:09 +0000428 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
429 APInt Mask = APInt::getAllOnesValue(BitWidth),
430 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
431 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
432 return KnownZero.isAllOnesValue();
433}
434
435void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000436 Assert1(!isZero(I.getOperand(1), TD),
437 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000438}
439
440void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000441 Assert1(!isZero(I.getOperand(1), TD),
442 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000443}
444
445void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000446 Assert1(!isZero(I.getOperand(1), TD),
447 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000448}
449
450void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000451 Assert1(!isZero(I.getOperand(1), TD),
452 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000453}
454
455void Lint::visitAllocaInst(AllocaInst &I) {
456 if (isa<ConstantInt>(I.getArraySize()))
457 // This isn't undefined behavior, it's just an obvious pessimization.
458 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000459 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000460}
461
462void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000463 visitMemoryReference(I, I.getOperand(0), 0, 0,
464 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000465}
466
467void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000468 visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
Dan Gohman113902e2010-04-08 18:47:09 +0000469}
470
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000471void Lint::visitExtractElementInst(ExtractElementInst &I) {
472 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000473 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
474 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000475 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000476 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000477}
478
479void Lint::visitInsertElementInst(InsertElementInst &I) {
480 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000481 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
482 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000483 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000484 "Undefined result: insertelement index out of range", &I);
485}
486
487void Lint::visitUnreachableInst(UnreachableInst &I) {
488 // This isn't undefined behavior, it's merely suspicious.
489 Assert1(&I == I.getParent()->begin() ||
490 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
491 "Unusual: unreachable immediately preceded by instruction without "
492 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000493}
494
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000495/// findValue - Look through bitcasts and simple memory reference patterns
496/// to identify an equivalent, but more informative, value. If OffsetOk
497/// is true, look through getelementptrs with non-zero offsets too.
498///
499/// Most analysis passes don't require this logic, because instcombine
500/// will simplify most of these kinds of things away. But it's a goal of
501/// this Lint pass to be useful even on non-optimized IR.
502Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000503 SmallPtrSet<Value *, 4> Visited;
504 return findValueImpl(V, OffsetOk, Visited);
505}
506
507/// findValueImpl - Implementation helper for findValue.
508Value *Lint::findValueImpl(Value *V, bool OffsetOk,
509 SmallPtrSet<Value *, 4> &Visited) const {
510 // Detect self-referential values.
511 if (!Visited.insert(V))
512 return UndefValue::get(V->getType());
513
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000514 // TODO: Look through sext or zext cast, when the result is known to
515 // be interpreted as signed or unsigned, respectively.
516 // TODO: Look through calls with unique return values.
517 // TODO: Look through vector insert/extract/shuffle.
518 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
519 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
520 BasicBlock::iterator BBI = L;
521 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000522 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000523 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000524 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000525 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
526 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000527 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000528 if (BBI != BB->begin()) break;
529 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000530 if (!BB) break;
531 BBI = BB->end();
532 }
533 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
534 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
535 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000536 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000537 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
538 if (Value *W = PN->hasConstantValue(DT))
Dan Gohman17d95962010-05-28 16:45:33 +0000539 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000540 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
541 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
542 Ex->idx_begin(),
543 Ex->idx_end()))
544 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000545 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000546 }
547
548 // As a last resort, try SimplifyInstruction or constant folding.
549 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
550 if (Value *W = SimplifyInstruction(Inst, TD))
551 if (W != Inst)
Dan Gohman17d95962010-05-28 16:45:33 +0000552 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000553 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
554 if (Value *W = ConstantFoldConstantExpression(CE, TD))
555 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000556 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000557 }
558
559 return V;
560}
561
Dan Gohman113902e2010-04-08 18:47:09 +0000562//===----------------------------------------------------------------------===//
563// Implement the public interfaces to this file...
564//===----------------------------------------------------------------------===//
565
566FunctionPass *llvm::createLintPass() {
567 return new Lint();
568}
569
570/// lintFunction - Check a function for errors, printing messages on stderr.
571///
572void llvm::lintFunction(const Function &f) {
573 Function &F = const_cast<Function&>(f);
574 assert(!F.isDeclaration() && "Cannot lint external functions");
575
576 FunctionPassManager FPM(F.getParent());
577 Lint *V = new Lint();
578 FPM.add(V);
579 FPM.run(F);
580}
581
582/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000583///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000584void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000585 PassManager PM;
586 Lint *V = new Lint();
587 PM.add(V);
588 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000589}