blob: 6d6d580ed19ae5ed517bb8d54e8b2148d24d74b5 [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"
Micah Villmow3574eca2012-10-08 16:38:25 +000046#include "llvm/DataLayout.h"
Chad Rosier618c1db2011-12-01 03:08:23 +000047#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohman113902e2010-04-08 18:47:09 +000048#include "llvm/Pass.h"
49#include "llvm/PassManager.h"
50#include "llvm/IntrinsicInst.h"
51#include "llvm/Function.h"
52#include "llvm/Support/CallSite.h"
53#include "llvm/Support/Debug.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/raw_ostream.h"
Dan Gohmanbe02b202010-04-09 01:39:53 +000056#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000057using namespace llvm;
58
59namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000060 namespace MemRef {
61 static unsigned Read = 1;
62 static unsigned Write = 2;
63 static unsigned Callee = 4;
64 static unsigned Branchee = 8;
65 }
66
Dan Gohman113902e2010-04-08 18:47:09 +000067 class Lint : public FunctionPass, public InstVisitor<Lint> {
68 friend class InstVisitor<Lint>;
69
Dan Gohmanbe02b202010-04-09 01:39:53 +000070 void visitFunction(Function &F);
71
Dan Gohman113902e2010-04-08 18:47:09 +000072 void visitCallSite(CallSite CS);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +000073 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohman3da848b2010-10-19 22:54:46 +000074 uint64_t Size, unsigned Align,
Chris Lattnerdb125cf2011-07-18 04:54:35 +000075 Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000076
Dan Gohman113902e2010-04-08 18:47:09 +000077 void visitCallInst(CallInst &I);
78 void visitInvokeInst(InvokeInst &I);
79 void visitReturnInst(ReturnInst &I);
80 void visitLoadInst(LoadInst &I);
81 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000082 void visitXor(BinaryOperator &I);
83 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000084 void visitLShr(BinaryOperator &I);
85 void visitAShr(BinaryOperator &I);
86 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000087 void visitSDiv(BinaryOperator &I);
88 void visitUDiv(BinaryOperator &I);
89 void visitSRem(BinaryOperator &I);
90 void visitURem(BinaryOperator &I);
91 void visitAllocaInst(AllocaInst &I);
92 void visitVAArgInst(VAArgInst &I);
93 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000094 void visitExtractElementInst(ExtractElementInst &I);
95 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000096 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000097
Dan Gohmanff26d4e2010-05-28 16:21:24 +000098 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman17d95962010-05-28 16:45:33 +000099 Value *findValueImpl(Value *V, bool OffsetOk,
100 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000101
Dan Gohman113902e2010-04-08 18:47:09 +0000102 public:
103 Module *Mod;
104 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000105 DominatorTree *DT;
Micah Villmow3574eca2012-10-08 16:38:25 +0000106 DataLayout *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000107 TargetLibraryInfo *TLI;
Dan Gohman113902e2010-04-08 18:47:09 +0000108
109 std::string Messages;
110 raw_string_ostream MessagesStr;
111
112 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000113 Lint() : FunctionPass(ID), MessagesStr(Messages) {
114 initializeLintPass(*PassRegistry::getPassRegistry());
115 }
Dan Gohman113902e2010-04-08 18:47:09 +0000116
117 virtual bool runOnFunction(Function &F);
118
119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.setPreservesAll();
121 AU.addRequired<AliasAnalysis>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000122 AU.addRequired<TargetLibraryInfo>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000123 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000124 }
125 virtual void print(raw_ostream &O, const Module *M) const {}
126
127 void WriteValue(const Value *V) {
128 if (!V) return;
129 if (isa<Instruction>(V)) {
130 MessagesStr << *V << '\n';
131 } else {
132 WriteAsOperand(MessagesStr, V, true, Mod);
133 MessagesStr << '\n';
134 }
135 }
136
Dan Gohman113902e2010-04-08 18:47:09 +0000137 // CheckFailed - A check failed, so print out the condition and the message
138 // that failed. This provides a nice place to put a breakpoint if you want
139 // to see why something is not correct.
140 void CheckFailed(const Twine &Message,
141 const Value *V1 = 0, const Value *V2 = 0,
142 const Value *V3 = 0, const Value *V4 = 0) {
143 MessagesStr << Message.str() << "\n";
144 WriteValue(V1);
145 WriteValue(V2);
146 WriteValue(V3);
147 WriteValue(V4);
148 }
Dan Gohman113902e2010-04-08 18:47:09 +0000149 };
150}
151
152char Lint::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000153INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
154 false, true)
Chad Rosier618c1db2011-12-01 03:08:23 +0000155INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000156INITIALIZE_PASS_DEPENDENCY(DominatorTree)
157INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
158INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
159 false, true)
Dan Gohman113902e2010-04-08 18:47:09 +0000160
161// Assert - We know that cond should be true, if not print an error message.
162#define Assert(C, M) \
163 do { if (!(C)) { CheckFailed(M); return; } } while (0)
164#define Assert1(C, M, V1) \
165 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
166#define Assert2(C, M, V1, V2) \
167 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
168#define Assert3(C, M, V1, V2, V3) \
169 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
170#define Assert4(C, M, V1, V2, V3, V4) \
171 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
172
173// Lint::run - This is the main Analysis entry point for a
174// function.
175//
176bool Lint::runOnFunction(Function &F) {
177 Mod = F.getParent();
178 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000179 DT = &getAnalysis<DominatorTree>();
Micah Villmow3574eca2012-10-08 16:38:25 +0000180 TD = getAnalysisIfAvailable<DataLayout>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000181 TLI = &getAnalysis<TargetLibraryInfo>();
Dan Gohman113902e2010-04-08 18:47:09 +0000182 visit(F);
183 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000184 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000185 return false;
186}
187
Dan Gohmanbe02b202010-04-09 01:39:53 +0000188void Lint::visitFunction(Function &F) {
189 // This isn't undefined behavior, it's just a little unusual, and it's a
190 // fairly common mistake to neglect to name a function.
191 Assert1(F.hasName() || F.hasLocalLinkage(),
192 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000193
194 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000195}
196
197void Lint::visitCallSite(CallSite CS) {
198 Instruction &I = *CS.getInstruction();
199 Value *Callee = CS.getCalledValue();
200
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000201 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
202 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000203
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000204 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000205 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000206 "Undefined behavior: Caller and callee calling convention differ",
207 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000208
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000209 FunctionType *FT = F->getFunctionType();
Dan Gohman113902e2010-04-08 18:47:09 +0000210 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
211
212 Assert1(FT->isVarArg() ?
213 FT->getNumParams() <= NumActualArgs :
214 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000215 "Undefined behavior: Call argument count mismatches callee "
216 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000217
Dan Gohman545d0062010-07-12 18:02:04 +0000218 Assert1(FT->getReturnType() == I.getType(),
219 "Undefined behavior: Call return type mismatches "
220 "callee return type", &I);
221
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000222 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000223 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000224 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
225 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
226 for (; AI != AE; ++AI) {
227 Value *Actual = *AI;
228 if (PI != PE) {
229 Argument *Formal = PI++;
230 Assert1(Formal->getType() == Actual->getType(),
231 "Undefined behavior: Call argument type mismatches "
232 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000233
Dan Gohmanc1f1efd2010-12-13 22:53:18 +0000234 // Check that noalias arguments don't alias other arguments. This is
235 // not fully precise because we don't know the sizes of the dereferenced
236 // memory regions.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000237 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohmanf3b8c762010-11-11 19:23:51 +0000238 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman4a2a3ea2010-12-10 20:04:06 +0000239 if (AI != BI && (*BI)->getType()->isPointerTy()) {
240 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
241 Assert1(Result != AliasAnalysis::MustAlias &&
242 Result != AliasAnalysis::PartialAlias,
243 "Unusual: noalias argument aliases another argument", &I);
244 }
Dan Gohman10e77262010-06-01 20:51:40 +0000245
246 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000247 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000248 Type *Ty =
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000249 cast<PointerType>(Formal->getType())->getElementType();
250 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
251 TD ? TD->getABITypeAlignment(Ty) : 0,
252 Ty, MemRef::Read | MemRef::Write);
253 }
254 }
255 }
Dan Gohman113902e2010-04-08 18:47:09 +0000256 }
257
Dan Gohman113b3e22010-05-26 21:46:36 +0000258 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
259 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
260 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000261 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000262 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000263 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000264 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000265 }
266
Dan Gohman113902e2010-04-08 18:47:09 +0000267
268 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
269 switch (II->getIntrinsicID()) {
270 default: break;
271
272 // TODO: Check more intrinsics
273
274 case Intrinsic::memcpy: {
275 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000276 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000277 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
278 MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000279 MemRef::Write);
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000280 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
281 MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000282 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000283
Dan Gohmanbe02b202010-04-09 01:39:53 +0000284 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
285 // isn't expressive enough for what we really want to do. Known partial
286 // overlap is not distinguished from the case where nothing is known.
Dan Gohman3da848b2010-10-19 22:54:46 +0000287 uint64_t Size = 0;
Dan Gohman113902e2010-04-08 18:47:09 +0000288 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000289 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
290 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000291 if (Len->getValue().isIntN(32))
292 Size = Len->getValue().getZExtValue();
293 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
294 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000295 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000296 break;
297 }
298 case Intrinsic::memmove: {
299 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000300 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000301 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
302 MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000303 MemRef::Write);
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000304 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
305 MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000306 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000307 break;
308 }
309 case Intrinsic::memset: {
310 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000311 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000312 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
313 MSI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000314 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000315 break;
316 }
317
318 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000319 Assert1(I.getParent()->getParent()->isVarArg(),
320 "Undefined behavior: va_start called in a non-varargs function",
321 &I);
322
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000323 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
324 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000325 break;
326 case Intrinsic::vacopy:
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000327 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
328 0, 0, MemRef::Write);
329 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
330 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000331 break;
332 case Intrinsic::vaend:
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000333 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
334 0, 0, 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 Gohmanf3a925d2010-10-19 17:06:23 +0000341 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
342 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman882ddb42010-05-26 22:21:25 +0000343 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 Gohman3da848b2010-10-19 22:54:46 +0000371 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000372 Type *Ty, unsigned Flags) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000373 // 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
Duncan Sandsc7c42f72012-09-26 07:45:36 +0000414 // Check for buffer overflows and misalignment.
Dan Gohman113902e2010-04-08 18:47:09 +0000415 if (TD) {
Duncan Sandsc7c42f72012-09-26 07:45:36 +0000416 // Only handles memory references that read/write something simple like an
417 // alloca instruction or a global variable.
418 int64_t Offset = 0;
419 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *TD)) {
420 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
421 // something we can handle and if so extract the size of this base object
422 // along with its alignment.
423 uint64_t BaseSize = AliasAnalysis::UnknownSize;
424 unsigned BaseAlign = 0;
Dan Gohman113902e2010-04-08 18:47:09 +0000425
Duncan Sandsc7c42f72012-09-26 07:45:36 +0000426 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
427 Type *ATy = AI->getAllocatedType();
428 if (!AI->isArrayAllocation() && ATy->isSized())
429 BaseSize = TD->getTypeAllocSize(ATy);
430 BaseAlign = AI->getAlignment();
431 if (BaseAlign == 0 && ATy->isSized())
432 BaseAlign = TD->getABITypeAlignment(ATy);
Duncan Sandsb6204692012-09-30 07:30:10 +0000433 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
434 // If the global may be defined differently in another compilation unit
435 // then don't warn about funky memory accesses.
436 if (GV->hasDefinitiveInitializer()) {
437 Type *GTy = GV->getType()->getElementType();
438 if (GTy->isSized())
439 BaseSize = TD->getTypeAllocSize(GTy);
440 BaseAlign = GV->getAlignment();
441 if (BaseAlign == 0 && GTy->isSized())
442 BaseAlign = TD->getABITypeAlignment(GTy);
443 }
Duncan Sands00edf4c2012-09-25 10:00:49 +0000444 }
Duncan Sandsc7c42f72012-09-26 07:45:36 +0000445
446 // Accesses from before the start or after the end of the object are not
447 // defined.
448 Assert1(Size == AliasAnalysis::UnknownSize ||
449 BaseSize == AliasAnalysis::UnknownSize ||
450 (Offset >= 0 && Offset + Size <= BaseSize),
451 "Undefined behavior: Buffer overflow", &I);
452
453 // Accesses that say that the memory is more aligned than it is are not
454 // defined.
455 if (Align == 0 && Ty && Ty->isSized())
456 Align = TD->getABITypeAlignment(Ty);
457 Assert1(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
458 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000459 }
460 }
461}
462
463void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000464 visitMemoryReference(I, I.getPointerOperand(),
465 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
466 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000467}
468
469void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000470 visitMemoryReference(I, I.getPointerOperand(),
471 AA->getTypeStoreSize(I.getOperand(0)->getType()),
472 I.getAlignment(),
473 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000474}
475
Dan Gohmanbe02b202010-04-09 01:39:53 +0000476void Lint::visitXor(BinaryOperator &I) {
477 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
478 !isa<UndefValue>(I.getOperand(1)),
479 "Undefined result: xor(undef, undef)", &I);
480}
481
482void Lint::visitSub(BinaryOperator &I) {
483 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
484 !isa<UndefValue>(I.getOperand(1)),
485 "Undefined result: sub(undef, undef)", &I);
486}
487
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000488void Lint::visitLShr(BinaryOperator &I) {
489 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000490 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000491 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000492 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000493}
494
495void Lint::visitAShr(BinaryOperator &I) {
496 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000497 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000498 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000499 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000500}
501
502void Lint::visitShl(BinaryOperator &I) {
503 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000504 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000505 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000506 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000507}
508
Micah Villmow3574eca2012-10-08 16:38:25 +0000509static bool isZero(Value *V, DataLayout *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000510 // Assume undef could be zero.
511 if (isa<UndefValue>(V)) return true;
512
Dan Gohman113902e2010-04-08 18:47:09 +0000513 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000514 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
515 ComputeMaskedBits(V, KnownZero, KnownOne, TD);
Dan Gohman113902e2010-04-08 18:47:09 +0000516 return KnownZero.isAllOnesValue();
517}
518
519void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000520 Assert1(!isZero(I.getOperand(1), TD),
521 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000522}
523
524void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000525 Assert1(!isZero(I.getOperand(1), TD),
526 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000527}
528
529void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000530 Assert1(!isZero(I.getOperand(1), TD),
531 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000532}
533
534void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000535 Assert1(!isZero(I.getOperand(1), TD),
536 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000537}
538
539void Lint::visitAllocaInst(AllocaInst &I) {
540 if (isa<ConstantInt>(I.getArraySize()))
541 // This isn't undefined behavior, it's just an obvious pessimization.
542 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000543 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000544
545 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000546}
547
548void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000549 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000550 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000551}
552
553void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000554 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0, 0,
555 MemRef::Branchee);
Dan Gohmana8afb2a2010-08-02 23:06:43 +0000556
557 Assert1(I.getNumDestinations() != 0,
558 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000559}
560
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000561void Lint::visitExtractElementInst(ExtractElementInst &I) {
562 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000563 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
564 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000565 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000566 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000567}
568
569void Lint::visitInsertElementInst(InsertElementInst &I) {
570 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000571 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
572 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000573 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000574 "Undefined result: insertelement index out of range", &I);
575}
576
577void Lint::visitUnreachableInst(UnreachableInst &I) {
578 // This isn't undefined behavior, it's merely suspicious.
579 Assert1(&I == I.getParent()->begin() ||
580 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
581 "Unusual: unreachable immediately preceded by instruction without "
582 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000583}
584
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000585/// findValue - Look through bitcasts and simple memory reference patterns
586/// to identify an equivalent, but more informative, value. If OffsetOk
587/// is true, look through getelementptrs with non-zero offsets too.
588///
589/// Most analysis passes don't require this logic, because instcombine
590/// will simplify most of these kinds of things away. But it's a goal of
591/// this Lint pass to be useful even on non-optimized IR.
592Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000593 SmallPtrSet<Value *, 4> Visited;
594 return findValueImpl(V, OffsetOk, Visited);
595}
596
597/// findValueImpl - Implementation helper for findValue.
598Value *Lint::findValueImpl(Value *V, bool OffsetOk,
599 SmallPtrSet<Value *, 4> &Visited) const {
600 // Detect self-referential values.
601 if (!Visited.insert(V))
602 return UndefValue::get(V->getType());
603
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000604 // TODO: Look through sext or zext cast, when the result is known to
605 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000606 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000607 // TODO: Look through calls with unique return values.
608 // TODO: Look through vector insert/extract/shuffle.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000609 V = OffsetOk ? GetUnderlyingObject(V, TD) : V->stripPointerCasts();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000610 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
611 BasicBlock::iterator BBI = L;
612 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000613 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000614 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000615 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000616 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
617 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000618 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000619 if (BBI != BB->begin()) break;
620 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000621 if (!BB) break;
622 BBI = BB->end();
623 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000624 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sandsff103412010-11-17 04:30:22 +0000625 if (Value *W = PN->hasConstantValue())
Duncan Sands23a19572010-11-17 10:23:23 +0000626 if (W != V)
627 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000628 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
629 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
630 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000631 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000632 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
633 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +0000634 Ex->getIndices()))
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000635 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000636 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000637 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
638 // Same as above, but for ConstantExpr instead of Instruction.
639 if (Instruction::isCast(CE->getOpcode())) {
640 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
641 CE->getOperand(0)->getType(),
642 CE->getType(),
643 TD ? TD->getIntPtrType(V->getContext()) :
644 Type::getInt64Ty(V->getContext())))
645 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
646 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foadd30aa5a2011-04-13 15:22:40 +0000647 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foadfc6d3a42011-07-13 10:26:04 +0000648 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000649 if (W != V)
650 return findValueImpl(W, OffsetOk, Visited);
651 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000652 }
653
654 // As a last resort, try SimplifyInstruction or constant folding.
655 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000656 if (Value *W = SimplifyInstruction(Inst, TD, TLI, DT))
Duncan Sandsd261dc62010-11-17 08:35:29 +0000657 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000658 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000659 if (Value *W = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000660 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000661 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000662 }
663
664 return V;
665}
666
Dan Gohman113902e2010-04-08 18:47:09 +0000667//===----------------------------------------------------------------------===//
668// Implement the public interfaces to this file...
669//===----------------------------------------------------------------------===//
670
671FunctionPass *llvm::createLintPass() {
672 return new Lint();
673}
674
675/// lintFunction - Check a function for errors, printing messages on stderr.
676///
677void llvm::lintFunction(const Function &f) {
678 Function &F = const_cast<Function&>(f);
679 assert(!F.isDeclaration() && "Cannot lint external functions");
680
681 FunctionPassManager FPM(F.getParent());
682 Lint *V = new Lint();
683 FPM.add(V);
684 FPM.run(F);
685}
686
687/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000688///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000689void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000690 PassManager PM;
691 Lint *V = new Lint();
692 PM.add(V);
693 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000694}