blob: a9d972435f5fb8bbcea035b8d3d586f3283127fa [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,
Dan Gohmand3b6e412010-07-06 15:21:57 +000022// but this pass will warn about it anyway. This is the main reason why most
23// of these checks live here instead of in the Verifier pass.
Dan Gohman08833552010-04-22 01:30:05 +000024//
Dan Gohman113902e2010-04-08 18:47:09 +000025// Optimization passes may make conditions that this pass checks for more or
26// less obvious. If an optimization pass appears to be introducing a warning,
27// it may be that the optimization pass is merely exposing an existing
28// condition in the code.
29//
30// This code may be run before instcombine. In many cases, instcombine checks
31// for the same kinds of things and turns instructions with undefined behavior
32// into unreachable (or equivalent). Because of this, this pass makes some
33// effort to look through bitcasts and so on.
34//
35//===----------------------------------------------------------------------===//
36
37#include "llvm/Analysis/Passes.h"
38#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000039#include "llvm/Analysis/InstructionSimplify.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/Dominators.h"
Dan Gohman113902e2010-04-08 18:47:09 +000042#include "llvm/Analysis/Lint.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000043#include "llvm/Analysis/Loads.h"
Dan Gohman113902e2010-04-08 18:47:09 +000044#include "llvm/Analysis/ValueTracking.h"
45#include "llvm/Assembly/Writer.h"
46#include "llvm/Target/TargetData.h"
47#include "llvm/Pass.h"
48#include "llvm/PassManager.h"
49#include "llvm/IntrinsicInst.h"
50#include "llvm/Function.h"
51#include "llvm/Support/CallSite.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/InstVisitor.h"
54#include "llvm/Support/raw_ostream.h"
Dan Gohmanbe02b202010-04-09 01:39:53 +000055#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000056using namespace llvm;
57
58namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000059 namespace MemRef {
60 static unsigned Read = 1;
61 static unsigned Write = 2;
62 static unsigned Callee = 4;
63 static unsigned Branchee = 8;
64 }
65
Dan Gohman113902e2010-04-08 18:47:09 +000066 class Lint : public FunctionPass, public InstVisitor<Lint> {
67 friend class InstVisitor<Lint>;
68
Dan Gohmanbe02b202010-04-09 01:39:53 +000069 void visitFunction(Function &F);
70
Dan Gohman113902e2010-04-08 18:47:09 +000071 void visitCallSite(CallSite CS);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +000072 void visitMemoryReference(Instruction &I, Value *Ptr,
73 unsigned Size, unsigned Align,
Dan Gohman5b61b382010-04-30 19:05:00 +000074 const Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000075
Dan Gohman113902e2010-04-08 18:47:09 +000076 void visitCallInst(CallInst &I);
77 void visitInvokeInst(InvokeInst &I);
78 void visitReturnInst(ReturnInst &I);
79 void visitLoadInst(LoadInst &I);
80 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000081 void visitXor(BinaryOperator &I);
82 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000083 void visitLShr(BinaryOperator &I);
84 void visitAShr(BinaryOperator &I);
85 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000086 void visitSDiv(BinaryOperator &I);
87 void visitUDiv(BinaryOperator &I);
88 void visitSRem(BinaryOperator &I);
89 void visitURem(BinaryOperator &I);
90 void visitAllocaInst(AllocaInst &I);
91 void visitVAArgInst(VAArgInst &I);
92 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000093 void visitExtractElementInst(ExtractElementInst &I);
94 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000095 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000096
Dan Gohmanff26d4e2010-05-28 16:21:24 +000097 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman17d95962010-05-28 16:45:33 +000098 Value *findValueImpl(Value *V, bool OffsetOk,
99 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000100
Dan Gohman113902e2010-04-08 18:47:09 +0000101 public:
102 Module *Mod;
103 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000104 DominatorTree *DT;
Dan Gohman113902e2010-04-08 18:47:09 +0000105 TargetData *TD;
106
107 std::string Messages;
108 raw_string_ostream MessagesStr;
109
110 static char ID; // Pass identification, replacement for typeid
Owen Anderson9ccaf532010-08-05 23:42:04 +0000111 Lint() : FunctionPass(ID), MessagesStr(Messages) {}
Dan Gohman113902e2010-04-08 18:47:09 +0000112
113 virtual bool runOnFunction(Function &F);
114
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.setPreservesAll();
117 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000118 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000119 }
120 virtual void print(raw_ostream &O, const Module *M) const {}
121
122 void WriteValue(const Value *V) {
123 if (!V) return;
124 if (isa<Instruction>(V)) {
125 MessagesStr << *V << '\n';
126 } else {
127 WriteAsOperand(MessagesStr, V, true, Mod);
128 MessagesStr << '\n';
129 }
130 }
131
132 void WriteType(const Type *T) {
133 if (!T) return;
134 MessagesStr << ' ';
135 WriteTypeSymbolic(MessagesStr, T, Mod);
136 }
137
138 // CheckFailed - A check failed, so print out the condition and the message
139 // that failed. This provides a nice place to put a breakpoint if you want
140 // to see why something is not correct.
141 void CheckFailed(const Twine &Message,
142 const Value *V1 = 0, const Value *V2 = 0,
143 const Value *V3 = 0, const Value *V4 = 0) {
144 MessagesStr << Message.str() << "\n";
145 WriteValue(V1);
146 WriteValue(V2);
147 WriteValue(V3);
148 WriteValue(V4);
149 }
150
151 void CheckFailed(const Twine &Message, const Value *V1,
152 const Type *T2, const Value *V3 = 0) {
153 MessagesStr << Message.str() << "\n";
154 WriteValue(V1);
155 WriteType(T2);
156 WriteValue(V3);
157 }
158
159 void CheckFailed(const Twine &Message, const Type *T1,
160 const Type *T2 = 0, const Type *T3 = 0) {
161 MessagesStr << Message.str() << "\n";
162 WriteType(T1);
163 WriteType(T2);
164 WriteType(T3);
165 }
166 };
167}
168
169char Lint::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000170INITIALIZE_PASS(Lint, "lint", "Statically lint-checks LLVM IR", false, true);
Dan Gohman113902e2010-04-08 18:47:09 +0000171
172// Assert - We know that cond should be true, if not print an error message.
173#define Assert(C, M) \
174 do { if (!(C)) { CheckFailed(M); return; } } while (0)
175#define Assert1(C, M, V1) \
176 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
177#define Assert2(C, M, V1, V2) \
178 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
179#define Assert3(C, M, V1, V2, V3) \
180 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
181#define Assert4(C, M, V1, V2, V3, V4) \
182 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
183
184// Lint::run - This is the main Analysis entry point for a
185// function.
186//
187bool Lint::runOnFunction(Function &F) {
188 Mod = F.getParent();
189 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000190 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000191 TD = getAnalysisIfAvailable<TargetData>();
192 visit(F);
193 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000194 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000195 return false;
196}
197
Dan Gohmanbe02b202010-04-09 01:39:53 +0000198void Lint::visitFunction(Function &F) {
199 // This isn't undefined behavior, it's just a little unusual, and it's a
200 // fairly common mistake to neglect to name a function.
201 Assert1(F.hasName() || F.hasLocalLinkage(),
202 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000203
204 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000205}
206
207void Lint::visitCallSite(CallSite CS) {
208 Instruction &I = *CS.getInstruction();
209 Value *Callee = CS.getCalledValue();
210
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000211 visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000212
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000213 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000214 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000215 "Undefined behavior: Caller and callee calling convention differ",
216 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000217
218 const FunctionType *FT = F->getFunctionType();
219 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
220
221 Assert1(FT->isVarArg() ?
222 FT->getNumParams() <= NumActualArgs :
223 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000224 "Undefined behavior: Call argument count mismatches callee "
225 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000226
Dan Gohman545d0062010-07-12 18:02:04 +0000227 Assert1(FT->getReturnType() == I.getType(),
228 "Undefined behavior: Call return type mismatches "
229 "callee return type", &I);
230
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000231 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000232 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000233 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
234 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
235 for (; AI != AE; ++AI) {
236 Value *Actual = *AI;
237 if (PI != PE) {
238 Argument *Formal = PI++;
239 Assert1(Formal->getType() == Actual->getType(),
240 "Undefined behavior: Call argument type mismatches "
241 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000242
243 // Check that noalias arguments don't alias other arguments. The
244 // AliasAnalysis API isn't expressive enough for what we really want
245 // to do. Known partial overlap is not distinguished from the case
246 // where nothing is known.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000247 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman10e77262010-06-01 20:51:40 +0000248 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
Dan Gohman847a84e2010-08-03 00:56:30 +0000249 Assert1(AI == BI || AA->alias(*AI, *BI) != AliasAnalysis::MustAlias,
Dan Gohman10e77262010-06-01 20:51:40 +0000250 "Unusual: noalias argument aliases another argument", &I);
251 }
252
253 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000254 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
255 const Type *Ty =
256 cast<PointerType>(Formal->getType())->getElementType();
257 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
258 TD ? TD->getABITypeAlignment(Ty) : 0,
259 Ty, MemRef::Read | MemRef::Write);
260 }
261 }
262 }
Dan Gohman113902e2010-04-08 18:47:09 +0000263 }
264
Dan Gohman113b3e22010-05-26 21:46:36 +0000265 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
266 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
267 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000268 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000269 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000270 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000271 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000272 }
273
Dan Gohman113902e2010-04-08 18:47:09 +0000274
275 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
276 switch (II->getIntrinsicID()) {
277 default: break;
278
279 // TODO: Check more intrinsics
280
281 case Intrinsic::memcpy: {
282 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000283 // TODO: If the size is known, use it.
284 visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000285 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000286 visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000287 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000288
Dan Gohmanbe02b202010-04-09 01:39:53 +0000289 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
290 // isn't expressive enough for what we really want to do. Known partial
291 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000292 unsigned Size = 0;
293 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000294 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
295 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000296 if (Len->getValue().isIntN(32))
297 Size = Len->getValue().getZExtValue();
298 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
299 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000300 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000301 break;
302 }
303 case Intrinsic::memmove: {
304 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000305 // TODO: If the size is known, use it.
306 visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000307 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000308 visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000309 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000310 break;
311 }
312 case Intrinsic::memset: {
313 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000314 // TODO: If the size is known, use it.
315 visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000316 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000317 break;
318 }
319
320 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000321 Assert1(I.getParent()->getParent()->isVarArg(),
322 "Undefined behavior: va_start called in a non-varargs function",
323 &I);
324
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000325 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000326 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000327 break;
328 case Intrinsic::vacopy:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000329 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
330 visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000331 break;
332 case Intrinsic::vaend:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000333 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000334 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000335 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000336
337 case Intrinsic::stackrestore:
338 // Stackrestore doesn't read or write memory, but it sets the
339 // stack pointer, which the compiler may read from or write to
340 // at any time, so check it for both readability and writeability.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000341 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman882ddb42010-05-26 22:21:25 +0000342 MemRef::Read | MemRef::Write);
343 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000344 }
345}
346
347void Lint::visitCallInst(CallInst &I) {
348 return visitCallSite(&I);
349}
350
351void Lint::visitInvokeInst(InvokeInst &I) {
352 return visitCallSite(&I);
353}
354
355void Lint::visitReturnInst(ReturnInst &I) {
356 Function *F = I.getParent()->getParent();
357 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000358 "Unusual: Return statement in function with noreturn attribute",
359 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000360
361 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000362 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000363 Assert1(!isa<AllocaInst>(Obj),
364 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000365 }
Dan Gohman113902e2010-04-08 18:47:09 +0000366}
367
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000368// TODO: Check that the reference is in bounds.
Dan Gohman0ce24992010-07-06 15:23:00 +0000369// TODO: Check readnone/readonly function attributes.
Dan Gohman113902e2010-04-08 18:47:09 +0000370void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000371 Value *Ptr, unsigned Size, unsigned Align,
372 const Type *Ty, unsigned Flags) {
373 // If no memory is being referenced, it doesn't matter if the pointer
374 // is valid.
375 if (Size == 0)
376 return;
377
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000378 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000379 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
380 "Undefined behavior: Null pointer dereference", &I);
381 Assert1(!isa<UndefValue>(UnderlyingObject),
382 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000383 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
384 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
385 "Unusual: All-ones pointer dereference", &I);
386 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
387 !cast<ConstantInt>(UnderlyingObject)->isOne(),
388 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000389
Dan Gohman5b61b382010-04-30 19:05:00 +0000390 if (Flags & MemRef::Write) {
391 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
392 Assert1(!GV->isConstant(),
393 "Undefined behavior: Write to read-only memory", &I);
394 Assert1(!isa<Function>(UnderlyingObject) &&
395 !isa<BlockAddress>(UnderlyingObject),
396 "Undefined behavior: Write to text section", &I);
397 }
398 if (Flags & MemRef::Read) {
399 Assert1(!isa<Function>(UnderlyingObject),
400 "Unusual: Load from function body", &I);
401 Assert1(!isa<BlockAddress>(UnderlyingObject),
402 "Undefined behavior: Load from block address", &I);
403 }
404 if (Flags & MemRef::Callee) {
405 Assert1(!isa<BlockAddress>(UnderlyingObject),
406 "Undefined behavior: Call to block address", &I);
407 }
408 if (Flags & MemRef::Branchee) {
409 Assert1(!isa<Constant>(UnderlyingObject) ||
410 isa<BlockAddress>(UnderlyingObject),
411 "Undefined behavior: Branch to non-blockaddress", &I);
412 }
413
Dan Gohman113902e2010-04-08 18:47:09 +0000414 if (TD) {
415 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
416
417 if (Align != 0) {
418 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
419 APInt Mask = APInt::getAllOnesValue(BitWidth),
420 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
421 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
422 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000423 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000424 }
425 }
426}
427
428void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000429 visitMemoryReference(I, I.getPointerOperand(),
430 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
431 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000432}
433
434void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000435 visitMemoryReference(I, I.getPointerOperand(),
436 AA->getTypeStoreSize(I.getOperand(0)->getType()),
437 I.getAlignment(),
438 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000439}
440
Dan Gohmanbe02b202010-04-09 01:39:53 +0000441void Lint::visitXor(BinaryOperator &I) {
442 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
443 !isa<UndefValue>(I.getOperand(1)),
444 "Undefined result: xor(undef, undef)", &I);
445}
446
447void Lint::visitSub(BinaryOperator &I) {
448 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
449 !isa<UndefValue>(I.getOperand(1)),
450 "Undefined result: sub(undef, undef)", &I);
451}
452
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000453void Lint::visitLShr(BinaryOperator &I) {
454 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000455 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000456 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000457 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000458}
459
460void Lint::visitAShr(BinaryOperator &I) {
461 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000462 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000463 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000464 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000465}
466
467void Lint::visitShl(BinaryOperator &I) {
468 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000469 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000470 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000471 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000472}
473
Dan Gohman113902e2010-04-08 18:47:09 +0000474static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000475 // Assume undef could be zero.
476 if (isa<UndefValue>(V)) return true;
477
Dan Gohman113902e2010-04-08 18:47:09 +0000478 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
479 APInt Mask = APInt::getAllOnesValue(BitWidth),
480 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
481 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
482 return KnownZero.isAllOnesValue();
483}
484
485void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000486 Assert1(!isZero(I.getOperand(1), TD),
487 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000488}
489
490void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000491 Assert1(!isZero(I.getOperand(1), TD),
492 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000493}
494
495void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000496 Assert1(!isZero(I.getOperand(1), TD),
497 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000498}
499
500void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000501 Assert1(!isZero(I.getOperand(1), TD),
502 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000503}
504
505void Lint::visitAllocaInst(AllocaInst &I) {
506 if (isa<ConstantInt>(I.getArraySize()))
507 // This isn't undefined behavior, it's just an obvious pessimization.
508 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000509 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000510
511 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000512}
513
514void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000515 visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000516 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000517}
518
519void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000520 visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
Dan Gohmana8afb2a2010-08-02 23:06:43 +0000521
522 Assert1(I.getNumDestinations() != 0,
523 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000524}
525
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000526void Lint::visitExtractElementInst(ExtractElementInst &I) {
527 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000528 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
529 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000530 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000531 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000532}
533
534void Lint::visitInsertElementInst(InsertElementInst &I) {
535 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000536 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
537 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000538 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000539 "Undefined result: insertelement index out of range", &I);
540}
541
542void Lint::visitUnreachableInst(UnreachableInst &I) {
543 // This isn't undefined behavior, it's merely suspicious.
544 Assert1(&I == I.getParent()->begin() ||
545 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
546 "Unusual: unreachable immediately preceded by instruction without "
547 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000548}
549
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000550/// findValue - Look through bitcasts and simple memory reference patterns
551/// to identify an equivalent, but more informative, value. If OffsetOk
552/// is true, look through getelementptrs with non-zero offsets too.
553///
554/// Most analysis passes don't require this logic, because instcombine
555/// will simplify most of these kinds of things away. But it's a goal of
556/// this Lint pass to be useful even on non-optimized IR.
557Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000558 SmallPtrSet<Value *, 4> Visited;
559 return findValueImpl(V, OffsetOk, Visited);
560}
561
562/// findValueImpl - Implementation helper for findValue.
563Value *Lint::findValueImpl(Value *V, bool OffsetOk,
564 SmallPtrSet<Value *, 4> &Visited) const {
565 // Detect self-referential values.
566 if (!Visited.insert(V))
567 return UndefValue::get(V->getType());
568
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000569 // TODO: Look through sext or zext cast, when the result is known to
570 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000571 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000572 // TODO: Look through calls with unique return values.
573 // TODO: Look through vector insert/extract/shuffle.
574 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
575 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
576 BasicBlock::iterator BBI = L;
577 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000578 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000579 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000580 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000581 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
582 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000583 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000584 if (BBI != BB->begin()) break;
585 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000586 if (!BB) break;
587 BBI = BB->end();
588 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000589 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
590 if (Value *W = PN->hasConstantValue(DT))
591 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000592 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
593 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
594 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000595 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000596 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
597 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
598 Ex->idx_begin(),
599 Ex->idx_end()))
600 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000601 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000602 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
603 // Same as above, but for ConstantExpr instead of Instruction.
604 if (Instruction::isCast(CE->getOpcode())) {
605 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
606 CE->getOperand(0)->getType(),
607 CE->getType(),
608 TD ? TD->getIntPtrType(V->getContext()) :
609 Type::getInt64Ty(V->getContext())))
610 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
611 } else if (CE->getOpcode() == Instruction::ExtractValue) {
612 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
613 if (Value *W = FindInsertedValue(CE->getOperand(0),
614 Indices.begin(),
615 Indices.end()))
616 if (W != V)
617 return findValueImpl(W, OffsetOk, Visited);
618 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000619 }
620
621 // As a last resort, try SimplifyInstruction or constant folding.
622 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
623 if (Value *W = SimplifyInstruction(Inst, TD))
624 if (W != Inst)
Dan Gohman17d95962010-05-28 16:45:33 +0000625 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000626 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
627 if (Value *W = ConstantFoldConstantExpression(CE, TD))
628 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000629 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000630 }
631
632 return V;
633}
634
Dan Gohman113902e2010-04-08 18:47:09 +0000635//===----------------------------------------------------------------------===//
636// Implement the public interfaces to this file...
637//===----------------------------------------------------------------------===//
638
639FunctionPass *llvm::createLintPass() {
640 return new Lint();
641}
642
643/// lintFunction - Check a function for errors, printing messages on stderr.
644///
645void llvm::lintFunction(const Function &f) {
646 Function &F = const_cast<Function&>(f);
647 assert(!F.isDeclaration() && "Cannot lint external functions");
648
649 FunctionPassManager FPM(F.getParent());
650 Lint *V = new Lint();
651 FPM.add(V);
652 FPM.run(F);
653}
654
655/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000656///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000657void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000658 PassManager PM;
659 Lint *V = new Lint();
660 PM.add(V);
661 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000662}