blob: 7c0ead64ae67827524eff6314a4eb09338ede828 [file] [log] [blame]
Dan Gohman98bc4372010-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 Gohmanf855b392010-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 Gohmanc951e6e2010-04-22 01:30:05 +000024//
Dan Gohman98bc4372010-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/Lint.h"
38#include "llvm/ADT/STLExtras.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000039#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000040#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000042#include "llvm/Analysis/Loads.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Analysis/Passes.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000044#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000046#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Function.h"
48#include "llvm/IR/IntrinsicInst.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000049#include "llvm/InstVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Pass.h"
51#include "llvm/PassManager.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000052#include "llvm/Support/CallSite.h"
53#include "llvm/Support/Debug.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/Target/TargetLibraryInfo.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000056using namespace llvm;
57
58namespace {
Dan Gohman299e7b92010-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 Gohman98bc4372010-04-08 18:47:09 +000066 class Lint : public FunctionPass, public InstVisitor<Lint> {
67 friend class InstVisitor<Lint>;
68
Dan Gohman9ba08a42010-04-09 01:39:53 +000069 void visitFunction(Function &F);
70
Dan Gohman98bc4372010-04-08 18:47:09 +000071 void visitCallSite(CallSite CS);
Dan Gohman0fa67e42010-05-28 21:43:57 +000072 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohmanf372cf82010-10-19 22:54:46 +000073 uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +000074 Type *Ty, unsigned Flags);
Dan Gohman98bc4372010-04-08 18:47:09 +000075
Dan Gohman98bc4372010-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 Gohman9ba08a42010-04-09 01:39:53 +000081 void visitXor(BinaryOperator &I);
82 void visitSub(BinaryOperator &I);
Dan Gohman7808d492010-04-08 23:05:57 +000083 void visitLShr(BinaryOperator &I);
84 void visitAShr(BinaryOperator &I);
85 void visitShl(BinaryOperator &I);
Dan Gohman98bc4372010-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 Gohman7808d492010-04-08 23:05:57 +000093 void visitExtractElementInst(ExtractElementInst &I);
94 void visitInsertElementInst(InsertElementInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +000095 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman98bc4372010-04-08 18:47:09 +000096
Dan Gohman54d7aaa2010-05-28 16:21:24 +000097 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman862f0342010-05-28 16:45:33 +000098 Value *findValueImpl(Value *V, bool OffsetOk,
99 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000100
Dan Gohman98bc4372010-04-08 18:47:09 +0000101 public:
102 Module *Mod;
103 AliasAnalysis *AA;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000104 DominatorTree *DT;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000105 DataLayout *TD;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000106 TargetLibraryInfo *TLI;
Dan Gohman98bc4372010-04-08 18:47:09 +0000107
108 std::string Messages;
109 raw_string_ostream MessagesStr;
110
111 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000112 Lint() : FunctionPass(ID), MessagesStr(Messages) {
113 initializeLintPass(*PassRegistry::getPassRegistry());
114 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000115
116 virtual bool runOnFunction(Function &F);
117
118 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
119 AU.setPreservesAll();
120 AU.addRequired<AliasAnalysis>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000121 AU.addRequired<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000122 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000123 }
124 virtual void print(raw_ostream &O, const Module *M) const {}
125
126 void WriteValue(const Value *V) {
127 if (!V) return;
128 if (isa<Instruction>(V)) {
129 MessagesStr << *V << '\n';
130 } else {
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000131 V->printAsOperand(MessagesStr, true, Mod);
Dan Gohman98bc4372010-04-08 18:47:09 +0000132 MessagesStr << '\n';
133 }
134 }
135
Dan Gohman98bc4372010-04-08 18:47:09 +0000136 // CheckFailed - A check failed, so print out the condition and the message
137 // that failed. This provides a nice place to put a breakpoint if you want
138 // to see why something is not correct.
139 void CheckFailed(const Twine &Message,
140 const Value *V1 = 0, const Value *V2 = 0,
141 const Value *V3 = 0, const Value *V4 = 0) {
142 MessagesStr << Message.str() << "\n";
143 WriteValue(V1);
144 WriteValue(V2);
145 WriteValue(V3);
146 WriteValue(V4);
147 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000148 };
149}
150
151char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000152INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
153 false, true)
Chad Rosierc24b86f2011-12-01 03:08:23 +0000154INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chandler Carruth73523022014-01-13 13:07:17 +0000155INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000156INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
157INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
158 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000159
160// Assert - We know that cond should be true, if not print an error message.
161#define Assert(C, M) \
162 do { if (!(C)) { CheckFailed(M); return; } } while (0)
163#define Assert1(C, M, V1) \
164 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
165#define Assert2(C, M, V1, V2) \
166 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
167#define Assert3(C, M, V1, V2, V3) \
168 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
169#define Assert4(C, M, V1, V2, V3, V4) \
170 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
171
172// Lint::run - This is the main Analysis entry point for a
173// function.
174//
175bool Lint::runOnFunction(Function &F) {
176 Mod = F.getParent();
177 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +0000178 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000179 TD = getAnalysisIfAvailable<DataLayout>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000180 TLI = &getAnalysis<TargetLibraryInfo>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000181 visit(F);
182 dbgs() << MessagesStr.str();
Dan Gohman084bcb12010-05-26 22:28:53 +0000183 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000184 return false;
185}
186
Dan Gohman9ba08a42010-04-09 01:39:53 +0000187void Lint::visitFunction(Function &F) {
188 // This isn't undefined behavior, it's just a little unusual, and it's a
189 // fairly common mistake to neglect to name a function.
190 Assert1(F.hasName() || F.hasLocalLinkage(),
191 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000192
193 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000194}
195
196void Lint::visitCallSite(CallSite CS) {
197 Instruction &I = *CS.getInstruction();
198 Value *Callee = CS.getCalledValue();
199
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000200 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
201 0, 0, MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000202
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000203 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman98bc4372010-04-08 18:47:09 +0000204 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000205 "Undefined behavior: Caller and callee calling convention differ",
206 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000207
Chris Lattner229907c2011-07-18 04:54:35 +0000208 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000209 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000210
211 Assert1(FT->isVarArg() ?
212 FT->getNumParams() <= NumActualArgs :
213 FT->getNumParams() == NumActualArgs,
Dan Gohman9ba08a42010-04-09 01:39:53 +0000214 "Undefined behavior: Call argument count mismatches callee "
215 "argument count", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000216
Dan Gohmanc128e702010-07-12 18:02:04 +0000217 Assert1(FT->getReturnType() == I.getType(),
218 "Undefined behavior: Call return type mismatches "
219 "callee return type", &I);
220
Dan Gohman0fa67e42010-05-28 21:43:57 +0000221 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman1e33b182010-07-06 15:23:00 +0000222 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000223 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
224 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
225 for (; AI != AE; ++AI) {
226 Value *Actual = *AI;
227 if (PI != PE) {
228 Argument *Formal = PI++;
229 Assert1(Formal->getType() == Actual->getType(),
230 "Undefined behavior: Call argument type mismatches "
231 "callee parameter type", &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000232
Dan Gohman3cb55a12010-12-13 22:53:18 +0000233 // Check that noalias arguments don't alias other arguments. This is
234 // not fully precise because we don't know the sizes of the dereferenced
235 // memory regions.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000236 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000237 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000238 if (AI != BI && (*BI)->getType()->isPointerTy()) {
239 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
240 Assert1(Result != AliasAnalysis::MustAlias &&
241 Result != AliasAnalysis::PartialAlias,
242 "Unusual: noalias argument aliases another argument", &I);
243 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000244
245 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000246 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000247 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000248 cast<PointerType>(Formal->getType())->getElementType();
249 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
250 TD ? TD->getABITypeAlignment(Ty) : 0,
251 Ty, MemRef::Read | MemRef::Write);
252 }
253 }
254 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000255 }
256
Dan Gohman1249adf2010-05-26 21:46:36 +0000257 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
258 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
259 AI != AE; ++AI) {
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000260 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohmancef9fc32010-05-28 16:34:49 +0000261 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman1249adf2010-05-26 21:46:36 +0000262 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohmancef9fc32010-05-28 16:34:49 +0000263 "alloca", &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000264 }
265
Dan Gohman98bc4372010-04-08 18:47:09 +0000266
267 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
268 switch (II->getIntrinsicID()) {
269 default: break;
270
271 // TODO: Check more intrinsics
272
273 case Intrinsic::memcpy: {
274 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000275 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000276 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
277 MCI->getAlignment(), 0,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000278 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000279 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
280 MCI->getAlignment(), 0,
Dan Gohman299e7b92010-04-30 19:05:00 +0000281 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000282
Dan Gohman9ba08a42010-04-09 01:39:53 +0000283 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
284 // isn't expressive enough for what we really want to do. Known partial
285 // overlap is not distinguished from the case where nothing is known.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000286 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000287 if (const ConstantInt *Len =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000288 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
289 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000290 if (Len->getValue().isIntN(32))
291 Size = Len->getValue().getZExtValue();
292 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
293 AliasAnalysis::MustAlias,
Dan Gohman9ba08a42010-04-09 01:39:53 +0000294 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000295 break;
296 }
297 case Intrinsic::memmove: {
298 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000299 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000300 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
301 MMI->getAlignment(), 0,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000302 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000303 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
304 MMI->getAlignment(), 0,
Dan Gohman299e7b92010-04-30 19:05:00 +0000305 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000306 break;
307 }
308 case Intrinsic::memset: {
309 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000310 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000311 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
312 MSI->getAlignment(), 0,
Dan Gohman299e7b92010-04-30 19:05:00 +0000313 MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000314 break;
315 }
316
317 case Intrinsic::vastart:
Dan Gohman9ba08a42010-04-09 01:39:53 +0000318 Assert1(I.getParent()->getParent()->isVarArg(),
319 "Undefined behavior: va_start called in a non-varargs function",
320 &I);
321
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000322 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
323 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000324 break;
325 case Intrinsic::vacopy:
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000326 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
327 0, 0, MemRef::Write);
328 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
329 0, 0, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000330 break;
331 case Intrinsic::vaend:
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000332 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
333 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000334 break;
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000335
336 case Intrinsic::stackrestore:
337 // Stackrestore doesn't read or write memory, but it sets the
338 // stack pointer, which the compiler may read from or write to
339 // at any time, so check it for both readability and writeability.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000340 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
341 0, 0, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000342 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000343 }
344}
345
346void Lint::visitCallInst(CallInst &I) {
347 return visitCallSite(&I);
348}
349
350void Lint::visitInvokeInst(InvokeInst &I) {
351 return visitCallSite(&I);
352}
353
354void Lint::visitReturnInst(ReturnInst &I) {
355 Function *F = I.getParent()->getParent();
356 Assert1(!F->doesNotReturn(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000357 "Unusual: Return statement in function with noreturn attribute",
358 &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000359
360 if (Value *V = I.getReturnValue()) {
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000361 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohmancef9fc32010-05-28 16:34:49 +0000362 Assert1(!isa<AllocaInst>(Obj),
363 "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000364 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000365}
366
Dan Gohman0fa67e42010-05-28 21:43:57 +0000367// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000368// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000369void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000370 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000371 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000372 // If no memory is being referenced, it doesn't matter if the pointer
373 // is valid.
374 if (Size == 0)
375 return;
376
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000377 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000378 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
379 "Undefined behavior: Null pointer dereference", &I);
380 Assert1(!isa<UndefValue>(UnderlyingObject),
381 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000382 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
383 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
384 "Unusual: All-ones pointer dereference", &I);
385 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
386 !cast<ConstantInt>(UnderlyingObject)->isOne(),
387 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000388
Dan Gohman299e7b92010-04-30 19:05:00 +0000389 if (Flags & MemRef::Write) {
390 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
391 Assert1(!GV->isConstant(),
392 "Undefined behavior: Write to read-only memory", &I);
393 Assert1(!isa<Function>(UnderlyingObject) &&
394 !isa<BlockAddress>(UnderlyingObject),
395 "Undefined behavior: Write to text section", &I);
396 }
397 if (Flags & MemRef::Read) {
398 Assert1(!isa<Function>(UnderlyingObject),
399 "Unusual: Load from function body", &I);
400 Assert1(!isa<BlockAddress>(UnderlyingObject),
401 "Undefined behavior: Load from block address", &I);
402 }
403 if (Flags & MemRef::Callee) {
404 Assert1(!isa<BlockAddress>(UnderlyingObject),
405 "Undefined behavior: Call to block address", &I);
406 }
407 if (Flags & MemRef::Branchee) {
408 Assert1(!isa<Constant>(UnderlyingObject) ||
409 isa<BlockAddress>(UnderlyingObject),
410 "Undefined behavior: Branch to non-blockaddress", &I);
411 }
412
Duncan Sandsa221eea2012-09-26 07:45:36 +0000413 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000414 // Only handles memory references that read/write something simple like an
415 // alloca instruction or a global variable.
416 int64_t Offset = 0;
417 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, TD)) {
418 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
419 // something we can handle and if so extract the size of this base object
420 // along with its alignment.
421 uint64_t BaseSize = AliasAnalysis::UnknownSize;
422 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000423
Dan Gohman20a2ae92013-01-31 02:00:45 +0000424 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
425 Type *ATy = AI->getAllocatedType();
426 if (TD && !AI->isArrayAllocation() && ATy->isSized())
427 BaseSize = TD->getTypeAllocSize(ATy);
428 BaseAlign = AI->getAlignment();
429 if (TD && BaseAlign == 0 && ATy->isSized())
430 BaseAlign = TD->getABITypeAlignment(ATy);
431 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
432 // If the global may be defined differently in another compilation unit
433 // then don't warn about funky memory accesses.
434 if (GV->hasDefinitiveInitializer()) {
435 Type *GTy = GV->getType()->getElementType();
436 if (TD && GTy->isSized())
437 BaseSize = TD->getTypeAllocSize(GTy);
438 BaseAlign = GV->getAlignment();
439 if (TD && BaseAlign == 0 && GTy->isSized())
440 BaseAlign = TD->getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000441 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000442 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000443
444 // Accesses from before the start or after the end of the object are not
445 // defined.
446 Assert1(Size == AliasAnalysis::UnknownSize ||
447 BaseSize == AliasAnalysis::UnknownSize ||
448 (Offset >= 0 && Offset + Size <= BaseSize),
449 "Undefined behavior: Buffer overflow", &I);
450
451 // Accesses that say that the memory is more aligned than it is are not
452 // defined.
453 if (TD && Align == 0 && Ty && Ty->isSized())
454 Align = TD->getABITypeAlignment(Ty);
455 Assert1(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
456 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000457 }
458}
459
460void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000461 visitMemoryReference(I, I.getPointerOperand(),
462 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
463 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000464}
465
466void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000467 visitMemoryReference(I, I.getPointerOperand(),
468 AA->getTypeStoreSize(I.getOperand(0)->getType()),
469 I.getAlignment(),
470 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000471}
472
Dan Gohman9ba08a42010-04-09 01:39:53 +0000473void Lint::visitXor(BinaryOperator &I) {
474 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
475 !isa<UndefValue>(I.getOperand(1)),
476 "Undefined result: xor(undef, undef)", &I);
477}
478
479void Lint::visitSub(BinaryOperator &I) {
480 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
481 !isa<UndefValue>(I.getOperand(1)),
482 "Undefined result: sub(undef, undef)", &I);
483}
484
Dan Gohman7808d492010-04-08 23:05:57 +0000485void Lint::visitLShr(BinaryOperator &I) {
486 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000487 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000488 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000489 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000490}
491
492void Lint::visitAShr(BinaryOperator &I) {
493 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000494 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000495 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000496 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000497}
498
499void Lint::visitShl(BinaryOperator &I) {
500 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000501 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000502 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000503 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000504}
505
Matt Arsenault5faa6692013-08-26 23:29:33 +0000506static bool isZero(Value *V, DataLayout *DL) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000507 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000508 if (isa<UndefValue>(V))
509 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000510
Matt Arsenault5faa6692013-08-26 23:29:33 +0000511 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
512 if (!VecTy) {
513 unsigned BitWidth = V->getType()->getIntegerBitWidth();
514 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
515 ComputeMaskedBits(V, KnownZero, KnownOne, DL);
516 return KnownZero.isAllOnesValue();
517 }
518
519 // Per-component check doesn't work with zeroinitializer
520 Constant *C = dyn_cast<Constant>(V);
521 if (!C)
522 return false;
523
524 if (C->isZeroValue())
525 return true;
526
527 // For a vector, KnownZero will only be true if all values are zero, so check
528 // this per component
529 unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
530 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
531 Constant *Elem = C->getAggregateElement(I);
532 if (isa<UndefValue>(Elem))
533 return true;
534
535 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
536 ComputeMaskedBits(Elem, KnownZero, KnownOne, DL);
537 if (KnownZero.isAllOnesValue())
538 return true;
539 }
540
541 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000542}
543
544void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000545 Assert1(!isZero(I.getOperand(1), TD),
546 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000547}
548
549void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000550 Assert1(!isZero(I.getOperand(1), TD),
551 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000552}
553
554void Lint::visitSRem(BinaryOperator &I) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000555 Assert1(!isZero(I.getOperand(1), TD),
556 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000557}
558
559void Lint::visitURem(BinaryOperator &I) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000560 Assert1(!isZero(I.getOperand(1), TD),
561 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000562}
563
564void Lint::visitAllocaInst(AllocaInst &I) {
565 if (isa<ConstantInt>(I.getArraySize()))
566 // This isn't undefined behavior, it's just an obvious pessimization.
567 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000568 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000569
570 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000571}
572
573void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000574 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0, 0,
Dan Gohman299e7b92010-04-30 19:05:00 +0000575 MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000576}
577
578void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000579 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0, 0,
580 MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000581
582 Assert1(I.getNumDestinations() != 0,
583 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000584}
585
Dan Gohman7808d492010-04-08 23:05:57 +0000586void Lint::visitExtractElementInst(ExtractElementInst &I) {
587 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000588 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
589 /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000590 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000591 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000592}
593
594void Lint::visitInsertElementInst(InsertElementInst &I) {
595 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000596 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
597 /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000598 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000599 "Undefined result: insertelement index out of range", &I);
600}
601
602void Lint::visitUnreachableInst(UnreachableInst &I) {
603 // This isn't undefined behavior, it's merely suspicious.
604 Assert1(&I == I.getParent()->begin() ||
605 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
606 "Unusual: unreachable immediately preceded by instruction without "
607 "side effects", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000608}
609
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000610/// findValue - Look through bitcasts and simple memory reference patterns
611/// to identify an equivalent, but more informative, value. If OffsetOk
612/// is true, look through getelementptrs with non-zero offsets too.
613///
614/// Most analysis passes don't require this logic, because instcombine
615/// will simplify most of these kinds of things away. But it's a goal of
616/// this Lint pass to be useful even on non-optimized IR.
617Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000618 SmallPtrSet<Value *, 4> Visited;
619 return findValueImpl(V, OffsetOk, Visited);
620}
621
622/// findValueImpl - Implementation helper for findValue.
623Value *Lint::findValueImpl(Value *V, bool OffsetOk,
624 SmallPtrSet<Value *, 4> &Visited) const {
625 // Detect self-referential values.
626 if (!Visited.insert(V))
627 return UndefValue::get(V->getType());
628
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000629 // TODO: Look through sext or zext cast, when the result is known to
630 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000631 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000632 // TODO: Look through calls with unique return values.
633 // TODO: Look through vector insert/extract/shuffle.
Dan Gohman0f124e12011-01-24 18:53:32 +0000634 V = OffsetOk ? GetUnderlyingObject(V, TD) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000635 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
636 BasicBlock::iterator BBI = L;
637 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000638 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000639 for (;;) {
Dan Gohmanc575ec62010-05-28 17:44:00 +0000640 if (!VisitedBlocks.insert(BB)) break;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000641 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
642 BB, BBI, 6, AA))
Dan Gohman862f0342010-05-28 16:45:33 +0000643 return findValueImpl(U, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000644 if (BBI != BB->begin()) break;
645 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000646 if (!BB) break;
647 BBI = BB->end();
648 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000649 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000650 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000651 if (W != V)
652 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000653 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chandler Carruth7ec50852012-11-01 08:07:29 +0000654 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
655 Type::getInt64Ty(V->getContext())))
Dan Gohman862f0342010-05-28 16:45:33 +0000656 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000657 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
658 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000659 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000660 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000661 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000662 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
663 // Same as above, but for ConstantExpr instead of Instruction.
664 if (Instruction::isCast(CE->getOpcode())) {
665 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
666 CE->getOperand(0)->getType(),
667 CE->getType(),
Chandler Carruth7ec50852012-11-01 08:07:29 +0000668 TD ? TD->getIntPtrType(V->getContext()) :
Dan Gohman0fa67e42010-05-28 21:43:57 +0000669 Type::getInt64Ty(V->getContext())))
670 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
671 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000672 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000673 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000674 if (W != V)
675 return findValueImpl(W, OffsetOk, Visited);
676 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000677 }
678
679 // As a last resort, try SimplifyInstruction or constant folding.
680 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chad Rosierc24b86f2011-12-01 03:08:23 +0000681 if (Value *W = SimplifyInstruction(Inst, TD, TLI, DT))
Duncan Sands64e41cf2010-11-17 08:35:29 +0000682 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000683 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chad Rosier43a33062011-12-02 01:26:24 +0000684 if (Value *W = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000685 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000686 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000687 }
688
689 return V;
690}
691
Dan Gohman98bc4372010-04-08 18:47:09 +0000692//===----------------------------------------------------------------------===//
693// Implement the public interfaces to this file...
694//===----------------------------------------------------------------------===//
695
696FunctionPass *llvm::createLintPass() {
697 return new Lint();
698}
699
700/// lintFunction - Check a function for errors, printing messages on stderr.
701///
702void llvm::lintFunction(const Function &f) {
703 Function &F = const_cast<Function&>(f);
704 assert(!F.isDeclaration() && "Cannot lint external functions");
705
706 FunctionPassManager FPM(F.getParent());
707 Lint *V = new Lint();
708 FPM.add(V);
709 FPM.run(F);
710}
711
712/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000713///
Dan Gohman084bcb12010-05-26 22:28:53 +0000714void llvm::lintModule(const Module &M) {
Dan Gohman98bc4372010-04-08 18:47:09 +0000715 PassManager PM;
716 Lint *V = new Lint();
717 PM.add(V);
718 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000719}