blob: f7be3298522bbe933a30c6de7b50524cd0aaf877 [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 Anderson90c579d2010-08-06 18:33:48 +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
Dan Gohman113902e2010-04-08 18:47:09 +0000132 // CheckFailed - A check failed, so print out the condition and the message
133 // that failed. This provides a nice place to put a breakpoint if you want
134 // to see why something is not correct.
135 void CheckFailed(const Twine &Message,
136 const Value *V1 = 0, const Value *V2 = 0,
137 const Value *V3 = 0, const Value *V4 = 0) {
138 MessagesStr << Message.str() << "\n";
139 WriteValue(V1);
140 WriteValue(V2);
141 WriteValue(V3);
142 WriteValue(V4);
143 }
Dan Gohman113902e2010-04-08 18:47:09 +0000144 };
145}
146
147char Lint::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000148INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
149 false, true)
150INITIALIZE_PASS_DEPENDENCY(DominatorTree)
151INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
152INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
153 false, true)
Dan Gohman113902e2010-04-08 18:47:09 +0000154
155// Assert - We know that cond should be true, if not print an error message.
156#define Assert(C, M) \
157 do { if (!(C)) { CheckFailed(M); return; } } while (0)
158#define Assert1(C, M, V1) \
159 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
160#define Assert2(C, M, V1, V2) \
161 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
162#define Assert3(C, M, V1, V2, V3) \
163 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
164#define Assert4(C, M, V1, V2, V3, V4) \
165 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
166
167// Lint::run - This is the main Analysis entry point for a
168// function.
169//
170bool Lint::runOnFunction(Function &F) {
171 Mod = F.getParent();
172 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000173 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000174 TD = getAnalysisIfAvailable<TargetData>();
175 visit(F);
176 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000177 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000178 return false;
179}
180
Dan Gohmanbe02b202010-04-09 01:39:53 +0000181void Lint::visitFunction(Function &F) {
182 // This isn't undefined behavior, it's just a little unusual, and it's a
183 // fairly common mistake to neglect to name a function.
184 Assert1(F.hasName() || F.hasLocalLinkage(),
185 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000186
187 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000188}
189
190void Lint::visitCallSite(CallSite CS) {
191 Instruction &I = *CS.getInstruction();
192 Value *Callee = CS.getCalledValue();
193
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000194 visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000195
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000196 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000197 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000198 "Undefined behavior: Caller and callee calling convention differ",
199 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000200
201 const FunctionType *FT = F->getFunctionType();
202 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
203
204 Assert1(FT->isVarArg() ?
205 FT->getNumParams() <= NumActualArgs :
206 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000207 "Undefined behavior: Call argument count mismatches callee "
208 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000209
Dan Gohman545d0062010-07-12 18:02:04 +0000210 Assert1(FT->getReturnType() == I.getType(),
211 "Undefined behavior: Call return type mismatches "
212 "callee return type", &I);
213
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000214 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000215 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000216 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
217 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
218 for (; AI != AE; ++AI) {
219 Value *Actual = *AI;
220 if (PI != PE) {
221 Argument *Formal = PI++;
222 Assert1(Formal->getType() == Actual->getType(),
223 "Undefined behavior: Call argument type mismatches "
224 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000225
226 // Check that noalias arguments don't alias other arguments. The
227 // AliasAnalysis API isn't expressive enough for what we really want
228 // to do. Known partial overlap is not distinguished from the case
229 // where nothing is known.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000230 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman10e77262010-06-01 20:51:40 +0000231 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
Dan Gohman847a84e2010-08-03 00:56:30 +0000232 Assert1(AI == BI || AA->alias(*AI, *BI) != AliasAnalysis::MustAlias,
Dan Gohman10e77262010-06-01 20:51:40 +0000233 "Unusual: noalias argument aliases another argument", &I);
234 }
235
236 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000237 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
238 const Type *Ty =
239 cast<PointerType>(Formal->getType())->getElementType();
240 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
241 TD ? TD->getABITypeAlignment(Ty) : 0,
242 Ty, MemRef::Read | MemRef::Write);
243 }
244 }
245 }
Dan Gohman113902e2010-04-08 18:47:09 +0000246 }
247
Dan Gohman113b3e22010-05-26 21:46:36 +0000248 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
249 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
250 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000251 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000252 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000253 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000254 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000255 }
256
Dan Gohman113902e2010-04-08 18:47:09 +0000257
258 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
259 switch (II->getIntrinsicID()) {
260 default: break;
261
262 // TODO: Check more intrinsics
263
264 case Intrinsic::memcpy: {
265 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000266 // TODO: If the size is known, use it.
267 visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000268 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000269 visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000270 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000271
Dan Gohmanbe02b202010-04-09 01:39:53 +0000272 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
273 // isn't expressive enough for what we really want to do. Known partial
274 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000275 unsigned Size = 0;
276 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000277 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
278 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000279 if (Len->getValue().isIntN(32))
280 Size = Len->getValue().getZExtValue();
281 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
282 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000283 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000284 break;
285 }
286 case Intrinsic::memmove: {
287 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000288 // TODO: If the size is known, use it.
289 visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000290 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000291 visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000292 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000293 break;
294 }
295 case Intrinsic::memset: {
296 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000297 // TODO: If the size is known, use it.
298 visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000299 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000300 break;
301 }
302
303 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000304 Assert1(I.getParent()->getParent()->isVarArg(),
305 "Undefined behavior: va_start called in a non-varargs function",
306 &I);
307
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000308 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000309 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000310 break;
311 case Intrinsic::vacopy:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000312 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
313 visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000314 break;
315 case Intrinsic::vaend:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000316 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000317 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000318 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000319
320 case Intrinsic::stackrestore:
321 // Stackrestore doesn't read or write memory, but it sets the
322 // stack pointer, which the compiler may read from or write to
323 // at any time, so check it for both readability and writeability.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000324 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman882ddb42010-05-26 22:21:25 +0000325 MemRef::Read | MemRef::Write);
326 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000327 }
328}
329
330void Lint::visitCallInst(CallInst &I) {
331 return visitCallSite(&I);
332}
333
334void Lint::visitInvokeInst(InvokeInst &I) {
335 return visitCallSite(&I);
336}
337
338void Lint::visitReturnInst(ReturnInst &I) {
339 Function *F = I.getParent()->getParent();
340 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000341 "Unusual: Return statement in function with noreturn attribute",
342 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000343
344 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000345 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000346 Assert1(!isa<AllocaInst>(Obj),
347 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000348 }
Dan Gohman113902e2010-04-08 18:47:09 +0000349}
350
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000351// TODO: Check that the reference is in bounds.
Dan Gohman0ce24992010-07-06 15:23:00 +0000352// TODO: Check readnone/readonly function attributes.
Dan Gohman113902e2010-04-08 18:47:09 +0000353void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000354 Value *Ptr, unsigned Size, unsigned Align,
355 const Type *Ty, unsigned Flags) {
356 // If no memory is being referenced, it doesn't matter if the pointer
357 // is valid.
358 if (Size == 0)
359 return;
360
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000361 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000362 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
363 "Undefined behavior: Null pointer dereference", &I);
364 Assert1(!isa<UndefValue>(UnderlyingObject),
365 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000366 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
367 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
368 "Unusual: All-ones pointer dereference", &I);
369 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
370 !cast<ConstantInt>(UnderlyingObject)->isOne(),
371 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000372
Dan Gohman5b61b382010-04-30 19:05:00 +0000373 if (Flags & MemRef::Write) {
374 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
375 Assert1(!GV->isConstant(),
376 "Undefined behavior: Write to read-only memory", &I);
377 Assert1(!isa<Function>(UnderlyingObject) &&
378 !isa<BlockAddress>(UnderlyingObject),
379 "Undefined behavior: Write to text section", &I);
380 }
381 if (Flags & MemRef::Read) {
382 Assert1(!isa<Function>(UnderlyingObject),
383 "Unusual: Load from function body", &I);
384 Assert1(!isa<BlockAddress>(UnderlyingObject),
385 "Undefined behavior: Load from block address", &I);
386 }
387 if (Flags & MemRef::Callee) {
388 Assert1(!isa<BlockAddress>(UnderlyingObject),
389 "Undefined behavior: Call to block address", &I);
390 }
391 if (Flags & MemRef::Branchee) {
392 Assert1(!isa<Constant>(UnderlyingObject) ||
393 isa<BlockAddress>(UnderlyingObject),
394 "Undefined behavior: Branch to non-blockaddress", &I);
395 }
396
Dan Gohman113902e2010-04-08 18:47:09 +0000397 if (TD) {
398 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
399
400 if (Align != 0) {
401 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
402 APInt Mask = APInt::getAllOnesValue(BitWidth),
403 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
404 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
405 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000406 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000407 }
408 }
409}
410
411void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000412 visitMemoryReference(I, I.getPointerOperand(),
413 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
414 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000415}
416
417void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000418 visitMemoryReference(I, I.getPointerOperand(),
419 AA->getTypeStoreSize(I.getOperand(0)->getType()),
420 I.getAlignment(),
421 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000422}
423
Dan Gohmanbe02b202010-04-09 01:39:53 +0000424void Lint::visitXor(BinaryOperator &I) {
425 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
426 !isa<UndefValue>(I.getOperand(1)),
427 "Undefined result: xor(undef, undef)", &I);
428}
429
430void Lint::visitSub(BinaryOperator &I) {
431 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
432 !isa<UndefValue>(I.getOperand(1)),
433 "Undefined result: sub(undef, undef)", &I);
434}
435
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000436void Lint::visitLShr(BinaryOperator &I) {
437 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000438 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000439 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000440 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000441}
442
443void Lint::visitAShr(BinaryOperator &I) {
444 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000445 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000446 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000447 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000448}
449
450void Lint::visitShl(BinaryOperator &I) {
451 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000452 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000453 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000454 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000455}
456
Dan Gohman113902e2010-04-08 18:47:09 +0000457static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000458 // Assume undef could be zero.
459 if (isa<UndefValue>(V)) return true;
460
Dan Gohman113902e2010-04-08 18:47:09 +0000461 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
462 APInt Mask = APInt::getAllOnesValue(BitWidth),
463 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
464 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
465 return KnownZero.isAllOnesValue();
466}
467
468void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000469 Assert1(!isZero(I.getOperand(1), TD),
470 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000471}
472
473void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000474 Assert1(!isZero(I.getOperand(1), TD),
475 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000476}
477
478void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000479 Assert1(!isZero(I.getOperand(1), TD),
480 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000481}
482
483void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000484 Assert1(!isZero(I.getOperand(1), TD),
485 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000486}
487
488void Lint::visitAllocaInst(AllocaInst &I) {
489 if (isa<ConstantInt>(I.getArraySize()))
490 // This isn't undefined behavior, it's just an obvious pessimization.
491 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000492 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000493
494 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000495}
496
497void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000498 visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000499 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000500}
501
502void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000503 visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
Dan Gohmana8afb2a2010-08-02 23:06:43 +0000504
505 Assert1(I.getNumDestinations() != 0,
506 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000507}
508
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000509void Lint::visitExtractElementInst(ExtractElementInst &I) {
510 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000511 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
512 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000513 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000514 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000515}
516
517void Lint::visitInsertElementInst(InsertElementInst &I) {
518 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000519 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
520 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000521 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000522 "Undefined result: insertelement index out of range", &I);
523}
524
525void Lint::visitUnreachableInst(UnreachableInst &I) {
526 // This isn't undefined behavior, it's merely suspicious.
527 Assert1(&I == I.getParent()->begin() ||
528 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
529 "Unusual: unreachable immediately preceded by instruction without "
530 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000531}
532
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000533/// findValue - Look through bitcasts and simple memory reference patterns
534/// to identify an equivalent, but more informative, value. If OffsetOk
535/// is true, look through getelementptrs with non-zero offsets too.
536///
537/// Most analysis passes don't require this logic, because instcombine
538/// will simplify most of these kinds of things away. But it's a goal of
539/// this Lint pass to be useful even on non-optimized IR.
540Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000541 SmallPtrSet<Value *, 4> Visited;
542 return findValueImpl(V, OffsetOk, Visited);
543}
544
545/// findValueImpl - Implementation helper for findValue.
546Value *Lint::findValueImpl(Value *V, bool OffsetOk,
547 SmallPtrSet<Value *, 4> &Visited) const {
548 // Detect self-referential values.
549 if (!Visited.insert(V))
550 return UndefValue::get(V->getType());
551
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000552 // TODO: Look through sext or zext cast, when the result is known to
553 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000554 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000555 // TODO: Look through calls with unique return values.
556 // TODO: Look through vector insert/extract/shuffle.
557 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
558 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
559 BasicBlock::iterator BBI = L;
560 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000561 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000562 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000563 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000564 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
565 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000566 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000567 if (BBI != BB->begin()) break;
568 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000569 if (!BB) break;
570 BBI = BB->end();
571 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000572 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
573 if (Value *W = PN->hasConstantValue(DT))
574 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000575 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
576 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
577 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000578 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000579 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
580 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
581 Ex->idx_begin(),
582 Ex->idx_end()))
583 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000584 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000585 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
586 // Same as above, but for ConstantExpr instead of Instruction.
587 if (Instruction::isCast(CE->getOpcode())) {
588 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
589 CE->getOperand(0)->getType(),
590 CE->getType(),
591 TD ? TD->getIntPtrType(V->getContext()) :
592 Type::getInt64Ty(V->getContext())))
593 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
594 } else if (CE->getOpcode() == Instruction::ExtractValue) {
595 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
596 if (Value *W = FindInsertedValue(CE->getOperand(0),
597 Indices.begin(),
598 Indices.end()))
599 if (W != V)
600 return findValueImpl(W, OffsetOk, Visited);
601 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000602 }
603
604 // As a last resort, try SimplifyInstruction or constant folding.
605 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
606 if (Value *W = SimplifyInstruction(Inst, TD))
607 if (W != Inst)
Dan Gohman17d95962010-05-28 16:45:33 +0000608 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000609 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
610 if (Value *W = ConstantFoldConstantExpression(CE, TD))
611 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000612 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000613 }
614
615 return V;
616}
617
Dan Gohman113902e2010-04-08 18:47:09 +0000618//===----------------------------------------------------------------------===//
619// Implement the public interfaces to this file...
620//===----------------------------------------------------------------------===//
621
622FunctionPass *llvm::createLintPass() {
623 return new Lint();
624}
625
626/// lintFunction - Check a function for errors, printing messages on stderr.
627///
628void llvm::lintFunction(const Function &f) {
629 Function &F = const_cast<Function&>(f);
630 assert(!F.isDeclaration() && "Cannot lint external functions");
631
632 FunctionPassManager FPM(F.getParent());
633 Lint *V = new Lint();
634 FPM.add(V);
635 FPM.run(F);
636}
637
638/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000639///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000640void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000641 PassManager PM;
642 Lint *V = new Lint();
643 PM.add(V);
644 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000645}