blob: a7da4eeefdb09ba175baa82acd2599e0a71d8e11 [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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000019//
Dan Gohman98bc4372010-04-08 18:47:09 +000020// 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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000029//
Dan Gohman98bc4372010-04-08 18:47:09 +000030// 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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000034//
Dan Gohman98bc4372010-04-08 18:47:09 +000035//===----------------------------------------------------------------------===//
36
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/Lint.h"
38#include "llvm/ADT/STLExtras.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000039#include "llvm/ADT/SmallSet.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000040#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000041#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000044#include "llvm/Analysis/Loads.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000047#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000048#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000052#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000054#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/Pass.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000056#include "llvm/Support/Debug.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000057#include "llvm/Support/raw_ostream.h"
58using namespace llvm;
59
60namespace {
Dan Gohman299e7b92010-04-30 19:05:00 +000061 namespace MemRef {
Benjamin Kramer57a3d082015-03-08 16:07:39 +000062 static const unsigned Read = 1;
63 static const unsigned Write = 2;
64 static const unsigned Callee = 4;
65 static const unsigned Branchee = 8;
Dan Gohman299e7b92010-04-30 19:05:00 +000066 }
67
Dan Gohman98bc4372010-04-08 18:47:09 +000068 class Lint : public FunctionPass, public InstVisitor<Lint> {
69 friend class InstVisitor<Lint>;
70
Dan Gohman9ba08a42010-04-09 01:39:53 +000071 void visitFunction(Function &F);
72
Dan Gohman98bc4372010-04-08 18:47:09 +000073 void visitCallSite(CallSite CS);
Dan Gohman0fa67e42010-05-28 21:43:57 +000074 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohmanf372cf82010-10-19 22:54:46 +000075 uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +000076 Type *Ty, unsigned Flags);
Andrew Kaylor78b53db2015-02-10 19:52:43 +000077 void visitEHBeginCatch(IntrinsicInst *II);
78 void visitEHEndCatch(IntrinsicInst *II);
Dan Gohman98bc4372010-04-08 18:47:09 +000079
Dan Gohman98bc4372010-04-08 18:47:09 +000080 void visitCallInst(CallInst &I);
81 void visitInvokeInst(InvokeInst &I);
82 void visitReturnInst(ReturnInst &I);
83 void visitLoadInst(LoadInst &I);
84 void visitStoreInst(StoreInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +000085 void visitXor(BinaryOperator &I);
86 void visitSub(BinaryOperator &I);
Dan Gohman7808d492010-04-08 23:05:57 +000087 void visitLShr(BinaryOperator &I);
88 void visitAShr(BinaryOperator &I);
89 void visitShl(BinaryOperator &I);
Dan Gohman98bc4372010-04-08 18:47:09 +000090 void visitSDiv(BinaryOperator &I);
91 void visitUDiv(BinaryOperator &I);
92 void visitSRem(BinaryOperator &I);
93 void visitURem(BinaryOperator &I);
94 void visitAllocaInst(AllocaInst &I);
95 void visitVAArgInst(VAArgInst &I);
96 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohman7808d492010-04-08 23:05:57 +000097 void visitExtractElementInst(ExtractElementInst &I);
98 void visitInsertElementInst(InsertElementInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +000099 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000100
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000101 Value *findValue(Value *V, const DataLayout &DL, bool OffsetOk) const;
102 Value *findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000103 SmallPtrSetImpl<Value *> &Visited) const;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000104
Dan Gohman98bc4372010-04-08 18:47:09 +0000105 public:
106 Module *Mod;
107 AliasAnalysis *AA;
Chandler Carruth66b31302015-01-04 12:03:27 +0000108 AssumptionCache *AC;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000109 DominatorTree *DT;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000110 TargetLibraryInfo *TLI;
Dan Gohman98bc4372010-04-08 18:47:09 +0000111
Alp Tokere69170a2014-06-26 22:52:05 +0000112 std::string Messages;
113 raw_string_ostream MessagesStr;
Dan Gohman98bc4372010-04-08 18:47:09 +0000114
115 static char ID; // Pass identification, replacement for typeid
Alp Tokere69170a2014-06-26 22:52:05 +0000116 Lint() : FunctionPass(ID), MessagesStr(Messages) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000117 initializeLintPass(*PassRegistry::getPassRegistry());
118 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000119
Craig Toppere9ba7592014-03-05 07:30:04 +0000120 bool runOnFunction(Function &F) override;
Dan Gohman98bc4372010-04-08 18:47:09 +0000121
Craig Toppere9ba7592014-03-05 07:30:04 +0000122 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman98bc4372010-04-08 18:47:09 +0000123 AU.setPreservesAll();
124 AU.addRequired<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000125 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000126 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000127 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000128 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000129 void print(raw_ostream &O, const Module *M) const override {}
Dan Gohman98bc4372010-04-08 18:47:09 +0000130
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000131 void WriteValues(ArrayRef<const Value *> Vs) {
132 for (const Value *V : Vs) {
133 if (!V)
134 continue;
135 if (isa<Instruction>(V)) {
136 MessagesStr << *V << '\n';
137 } else {
138 V->printAsOperand(MessagesStr, true, Mod);
139 MessagesStr << '\n';
140 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000141 }
142 }
143
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000144 /// \brief A check failed, so printout out the condition and the message.
145 ///
146 /// This provides a nice place to put a breakpoint if you want to see why
147 /// something is not correct.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000148 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
149
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000150 /// \brief A check failed (with values to print).
151 ///
152 /// This calls the Message-only version so that the above is easier to set
153 /// a breakpoint on.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000154 template <typename T1, typename... Ts>
155 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
156 CheckFailed(Message);
157 WriteValues({V1, Vs...});
Dan Gohman98bc4372010-04-08 18:47:09 +0000158 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000159 };
Alexander Kornienko70bc5f12015-06-19 15:57:42 +0000160} // namespace
Dan Gohman98bc4372010-04-08 18:47:09 +0000161
162char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000163INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
164 false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +0000165INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000166INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000167INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000168INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
169INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
170 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000171
172// Assert - We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000173#define Assert(C, ...) \
174 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
Dan Gohman98bc4372010-04-08 18:47:09 +0000175
176// Lint::run - This is the main Analysis entry point for a
177// function.
178//
179bool Lint::runOnFunction(Function &F) {
180 Mod = F.getParent();
181 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000182 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000183 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000184 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman98bc4372010-04-08 18:47:09 +0000185 visit(F);
186 dbgs() << MessagesStr.str();
Alp Tokere69170a2014-06-26 22:52:05 +0000187 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000188 return false;
189}
190
Dan Gohman9ba08a42010-04-09 01:39:53 +0000191void Lint::visitFunction(Function &F) {
192 // This isn't undefined behavior, it's just a little unusual, and it's a
193 // fairly common mistake to neglect to name a function.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000194 Assert(F.hasName() || F.hasLocalLinkage(),
195 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000196
197 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000198}
199
200void Lint::visitCallSite(CallSite CS) {
201 Instruction &I = *CS.getInstruction();
202 Value *Callee = CS.getCalledValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000203 const DataLayout &DL = CS->getModule()->getDataLayout();
Dan Gohman98bc4372010-04-08 18:47:09 +0000204
Chandler Carruthecbd1682015-06-17 07:21:38 +0000205 visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
206 MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000207
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000208 if (Function *F = dyn_cast<Function>(findValue(Callee, DL,
209 /*OffsetOk=*/false))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000210 Assert(CS.getCallingConv() == F->getCallingConv(),
211 "Undefined behavior: Caller and callee calling convention differ",
212 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000213
Chris Lattner229907c2011-07-18 04:54:35 +0000214 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000215 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000216
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000217 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
218 : FT->getNumParams() == NumActualArgs,
219 "Undefined behavior: Call argument count mismatches callee "
220 "argument count",
221 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000222
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000223 Assert(FT->getReturnType() == I.getType(),
224 "Undefined behavior: Call return type mismatches "
225 "callee return type",
226 &I);
Dan Gohmanc128e702010-07-12 18:02:04 +0000227
Dan Gohman0fa67e42010-05-28 21:43:57 +0000228 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman1e33b182010-07-06 15:23:00 +0000229 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000230 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
231 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
232 for (; AI != AE; ++AI) {
233 Value *Actual = *AI;
234 if (PI != PE) {
235 Argument *Formal = PI++;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000236 Assert(Formal->getType() == Actual->getType(),
237 "Undefined behavior: Call argument type mismatches "
238 "callee parameter type",
239 &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000240
Dan Gohman3cb55a12010-12-13 22:53:18 +0000241 // Check that noalias arguments don't alias other arguments. This is
242 // not fully precise because we don't know the sizes of the dereferenced
243 // memory regions.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000244 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000245 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000246 if (AI != BI && (*BI)->getType()->isPointerTy()) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000247 AliasResult Result = AA->alias(*AI, *BI);
248 Assert(Result != MustAlias && Result != PartialAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000249 "Unusual: noalias argument aliases another argument", &I);
Dan Gohman201acdb2010-12-10 20:04:06 +0000250 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000251
252 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000253 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000254 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000255 cast<PointerType>(Formal->getType())->getElementType();
256 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000257 DL.getABITypeAlignment(Ty), Ty,
258 MemRef::Read | MemRef::Write);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000259 }
260 }
261 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000262 }
263
Dan Gohman1249adf2010-05-26 21:46:36 +0000264 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
265 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
266 AI != AE; ++AI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000267 Value *Obj = findValue(*AI, DL, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000268 Assert(!isa<AllocaInst>(Obj),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000269 "Undefined behavior: Call with \"tail\" keyword references "
270 "alloca",
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000271 &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000272 }
273
Dan Gohman98bc4372010-04-08 18:47:09 +0000274
275 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
276 switch (II->getIntrinsicID()) {
277 default: break;
278
279 // TODO: Check more intrinsics
280
281 case Intrinsic::memcpy: {
282 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000283 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000284 visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
285 MCI->getAlignment(), nullptr, MemRef::Write);
286 visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
287 MCI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000288
Dan Gohman9ba08a42010-04-09 01:39:53 +0000289 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
290 // isn't expressive enough for what we really want to do. Known partial
291 // overlap is not distinguished from the case where nothing is known.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000292 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000293 if (const ConstantInt *Len =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 dyn_cast<ConstantInt>(findValue(MCI->getLength(), DL,
295 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000296 if (Len->getValue().isIntN(32))
297 Size = Len->getValue().getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000298 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000299 MustAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000300 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000301 break;
302 }
303 case Intrinsic::memmove: {
304 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000305 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000306 visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
307 MMI->getAlignment(), nullptr, MemRef::Write);
308 visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
309 MMI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000310 break;
311 }
312 case Intrinsic::memset: {
313 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000314 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000315 visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
316 MSI->getAlignment(), nullptr, MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000317 break;
318 }
319
320 case Intrinsic::vastart:
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000321 Assert(I.getParent()->getParent()->isVarArg(),
322 "Undefined behavior: va_start called in a non-varargs function",
323 &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000324
Chandler Carruthecbd1682015-06-17 07:21:38 +0000325 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
326 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000327 break;
328 case Intrinsic::vacopy:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000329 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
330 nullptr, MemRef::Write);
331 visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
332 nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000333 break;
334 case Intrinsic::vaend:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000335 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
336 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000337 break;
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000338
339 case Intrinsic::stackrestore:
340 // Stackrestore doesn't read or write memory, but it sets the
341 // stack pointer, which the compiler may read from or write to
342 // at any time, so check it for both readability and writeability.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000343 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
344 nullptr, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000345 break;
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000346
347 case Intrinsic::eh_begincatch:
348 visitEHBeginCatch(II);
349 break;
350 case Intrinsic::eh_endcatch:
351 visitEHEndCatch(II);
352 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000353 }
354}
355
356void Lint::visitCallInst(CallInst &I) {
357 return visitCallSite(&I);
358}
359
360void Lint::visitInvokeInst(InvokeInst &I) {
361 return visitCallSite(&I);
362}
363
364void Lint::visitReturnInst(ReturnInst &I) {
365 Function *F = I.getParent()->getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000366 Assert(!F->doesNotReturn(),
367 "Unusual: Return statement in function with noreturn attribute", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000368
369 if (Value *V = I.getReturnValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000370 Value *Obj =
371 findValue(V, F->getParent()->getDataLayout(), /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000372 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000373 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000374}
375
Dan Gohman0fa67e42010-05-28 21:43:57 +0000376// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000377// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000378void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000379 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000380 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000381 // If no memory is being referenced, it doesn't matter if the pointer
382 // is valid.
383 if (Size == 0)
384 return;
385
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000386 Value *UnderlyingObject =
387 findValue(Ptr, I.getModule()->getDataLayout(), /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000388 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
389 "Undefined behavior: Null pointer dereference", &I);
390 Assert(!isa<UndefValue>(UnderlyingObject),
391 "Undefined behavior: Undef pointer dereference", &I);
392 Assert(!isa<ConstantInt>(UnderlyingObject) ||
393 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
394 "Unusual: All-ones pointer dereference", &I);
395 Assert(!isa<ConstantInt>(UnderlyingObject) ||
396 !cast<ConstantInt>(UnderlyingObject)->isOne(),
397 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000398
Dan Gohman299e7b92010-04-30 19:05:00 +0000399 if (Flags & MemRef::Write) {
400 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000401 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
402 &I);
403 Assert(!isa<Function>(UnderlyingObject) &&
404 !isa<BlockAddress>(UnderlyingObject),
405 "Undefined behavior: Write to text section", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000406 }
407 if (Flags & MemRef::Read) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000408 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
409 &I);
410 Assert(!isa<BlockAddress>(UnderlyingObject),
411 "Undefined behavior: Load from block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000412 }
413 if (Flags & MemRef::Callee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000414 Assert(!isa<BlockAddress>(UnderlyingObject),
415 "Undefined behavior: Call to block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000416 }
417 if (Flags & MemRef::Branchee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000418 Assert(!isa<Constant>(UnderlyingObject) ||
419 isa<BlockAddress>(UnderlyingObject),
420 "Undefined behavior: Branch to non-blockaddress", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000421 }
422
Duncan Sandsa221eea2012-09-26 07:45:36 +0000423 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000424 // Only handles memory references that read/write something simple like an
425 // alloca instruction or a global variable.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000426 auto &DL = I.getModule()->getDataLayout();
Dan Gohman20a2ae92013-01-31 02:00:45 +0000427 int64_t Offset = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000428 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
Dan Gohman20a2ae92013-01-31 02:00:45 +0000429 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
430 // something we can handle and if so extract the size of this base object
431 // along with its alignment.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000432 uint64_t BaseSize = MemoryLocation::UnknownSize;
Dan Gohman20a2ae92013-01-31 02:00:45 +0000433 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000434
Dan Gohman20a2ae92013-01-31 02:00:45 +0000435 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
436 Type *ATy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000437 if (!AI->isArrayAllocation() && ATy->isSized())
438 BaseSize = DL.getTypeAllocSize(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000439 BaseAlign = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 if (BaseAlign == 0 && ATy->isSized())
441 BaseAlign = DL.getABITypeAlignment(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000442 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
443 // If the global may be defined differently in another compilation unit
444 // then don't warn about funky memory accesses.
445 if (GV->hasDefinitiveInitializer()) {
446 Type *GTy = GV->getType()->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000447 if (GTy->isSized())
448 BaseSize = DL.getTypeAllocSize(GTy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000449 BaseAlign = GV->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000450 if (BaseAlign == 0 && GTy->isSized())
451 BaseAlign = DL.getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000452 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000453 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000454
455 // Accesses from before the start or after the end of the object are not
456 // defined.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000457 Assert(Size == MemoryLocation::UnknownSize ||
458 BaseSize == MemoryLocation::UnknownSize ||
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000459 (Offset >= 0 && Offset + Size <= BaseSize),
460 "Undefined behavior: Buffer overflow", &I);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000461
462 // Accesses that say that the memory is more aligned than it is are not
463 // defined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000464 if (Align == 0 && Ty && Ty->isSized())
465 Align = DL.getABITypeAlignment(Ty);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000466 Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
467 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000468 }
469}
470
471void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000472 visitMemoryReference(I, I.getPointerOperand(),
473 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
474 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000475}
476
477void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000478 visitMemoryReference(I, I.getPointerOperand(),
479 AA->getTypeStoreSize(I.getOperand(0)->getType()),
480 I.getAlignment(),
481 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000482}
483
Dan Gohman9ba08a42010-04-09 01:39:53 +0000484void Lint::visitXor(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000485 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
486 "Undefined result: xor(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000487}
488
489void Lint::visitSub(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000490 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
491 "Undefined result: sub(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000492}
493
Dan Gohman7808d492010-04-08 23:05:57 +0000494void Lint::visitLShr(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000495 if (ConstantInt *CI = dyn_cast<ConstantInt>(
496 findValue(I.getOperand(1), I.getModule()->getDataLayout(),
497 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000498 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
499 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000500}
501
502void Lint::visitAShr(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
504 I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000505 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
506 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000507}
508
509void Lint::visitShl(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000510 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
511 I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000512 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
513 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000514}
515
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000516static bool
517allPredsCameFromLandingPad(BasicBlock *BB,
518 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
519 VisitedBlocks.insert(BB);
520 if (BB->isLandingPad())
521 return true;
522 // If we find a block with no predecessors, the search failed.
523 if (pred_empty(BB))
524 return false;
525 for (BasicBlock *Pred : predecessors(BB)) {
526 if (VisitedBlocks.count(Pred))
527 continue;
528 if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
529 return false;
530 }
531 return true;
532}
533
534static bool
535allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
536 IntrinsicInst **SecondBeginCatch,
537 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
538 VisitedBlocks.insert(BB);
539 for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
540 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
541 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
542 return true;
543 // If we find another begincatch while looking for an endcatch,
544 // that's also an error.
545 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
546 *SecondBeginCatch = IC;
547 return false;
548 }
549 }
550
551 // If we reach a block with no successors while searching, the
552 // search has failed.
553 if (succ_empty(BB))
554 return false;
555 // Otherwise, search all of the successors.
556 for (BasicBlock *Succ : successors(BB)) {
557 if (VisitedBlocks.count(Succ))
558 continue;
559 if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
560 VisitedBlocks))
561 return false;
562 }
563 return true;
564}
565
566void Lint::visitEHBeginCatch(IntrinsicInst *II) {
567 // The checks in this function make a potentially dubious assumption about
568 // the CFG, namely that any block involved in a catch is only used for the
569 // catch. This will very likely be true of IR generated by a front end,
570 // but it may cease to be true, for example, if the IR is run through a
571 // pass which combines similar blocks.
572 //
573 // In general, if we encounter a block the isn't dominated by the catch
574 // block while we are searching the catch block's successors for a call
575 // to end catch intrinsic, then it is possible that it will be legal for
576 // a path through this block to never reach a call to llvm.eh.endcatch.
577 // An analogous statement could be made about our search for a landing
578 // pad among the catch block's predecessors.
579 //
580 // What is actually required is that no path is possible at runtime that
581 // reaches a call to llvm.eh.begincatch without having previously visited
582 // a landingpad instruction and that no path is possible at runtime that
583 // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
584 // (mentally adjusting for the fact that in reality these calls will be
585 // removed before code generation).
586 //
587 // Because this is a lint check, we take a pessimistic approach and warn if
588 // the control flow is potentially incorrect.
589
590 SmallSet<BasicBlock *, 4> VisitedBlocks;
591 BasicBlock *CatchBB = II->getParent();
592
593 // The begin catch must occur in a landing pad block or all paths
594 // to it must have come from a landing pad.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000595 Assert(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
596 "llvm.eh.begincatch may be reachable without passing a landingpad",
597 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000598
599 // Reset the visited block list.
600 VisitedBlocks.clear();
601
602 IntrinsicInst *SecondBeginCatch = nullptr;
603
604 // This has to be called before it is asserted. Otherwise, the first assert
605 // below can never be hit.
606 bool EndCatchFound = allSuccessorsReachEndCatch(
607 CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
608 &SecondBeginCatch, VisitedBlocks);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000609 Assert(
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000610 SecondBeginCatch == nullptr,
611 "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
612 II, SecondBeginCatch);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000613 Assert(EndCatchFound,
614 "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
615 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000616}
617
618static bool allPredCameFromBeginCatch(
619 BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
620 IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
621 VisitedBlocks.insert(BB);
622 // Look for a begincatch in this block.
623 for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
624 ++RI) {
625 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
626 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
627 return true;
628 // If we find another end catch before we find a begin catch, that's
629 // an error.
630 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
631 *SecondEndCatch = IC;
632 return false;
633 }
634 // If we encounter a landingpad instruction, the search failed.
635 if (isa<LandingPadInst>(*RI))
636 return false;
637 }
638 // If while searching we find a block with no predeccesors,
639 // the search failed.
640 if (pred_empty(BB))
641 return false;
642 // Search any predecessors we haven't seen before.
643 for (BasicBlock *Pred : predecessors(BB)) {
644 if (VisitedBlocks.count(Pred))
645 continue;
646 if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
647 VisitedBlocks))
648 return false;
649 }
650 return true;
651}
652
653void Lint::visitEHEndCatch(IntrinsicInst *II) {
654 // The check in this function makes a potentially dubious assumption about
655 // the CFG, namely that any block involved in a catch is only used for the
656 // catch. This will very likely be true of IR generated by a front end,
657 // but it may cease to be true, for example, if the IR is run through a
658 // pass which combines similar blocks.
659 //
660 // In general, if we encounter a block the isn't post-dominated by the
661 // end catch block while we are searching the end catch block's predecessors
662 // for a call to the begin catch intrinsic, then it is possible that it will
663 // be legal for a path to reach the end catch block without ever having
664 // called llvm.eh.begincatch.
665 //
666 // What is actually required is that no path is possible at runtime that
667 // reaches a call to llvm.eh.endcatch without having previously visited
668 // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
669 // reality these calls will be removed before code generation).
670 //
671 // Because this is a lint check, we take a pessimistic approach and warn if
672 // the control flow is potentially incorrect.
673
674 BasicBlock *EndCatchBB = II->getParent();
675
676 // Alls paths to the end catch call must pass through a begin catch call.
677
678 // If llvm.eh.begincatch wasn't called in the current block, we'll use this
679 // lambda to recursively look for it in predecessors.
680 SmallSet<BasicBlock *, 4> VisitedBlocks;
681 IntrinsicInst *SecondEndCatch = nullptr;
682
683 // This has to be called before it is asserted. Otherwise, the first assert
684 // below can never be hit.
685 bool BeginCatchFound =
686 allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
687 &SecondEndCatch, VisitedBlocks);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000688 Assert(
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000689 SecondEndCatch == nullptr,
690 "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
691 II, SecondEndCatch);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000692 Assert(BeginCatchFound,
693 "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
694 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000695}
696
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000697static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000698 AssumptionCache *AC) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000699 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000700 if (isa<UndefValue>(V))
701 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000702
Matt Arsenault5faa6692013-08-26 23:29:33 +0000703 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
704 if (!VecTy) {
705 unsigned BitWidth = V->getType()->getIntegerBitWidth();
706 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +0000707 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
708 dyn_cast<Instruction>(V), DT);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000709 return KnownZero.isAllOnesValue();
710 }
711
712 // Per-component check doesn't work with zeroinitializer
713 Constant *C = dyn_cast<Constant>(V);
714 if (!C)
715 return false;
716
717 if (C->isZeroValue())
718 return true;
719
720 // For a vector, KnownZero will only be true if all values are zero, so check
721 // this per component
722 unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
723 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
724 Constant *Elem = C->getAggregateElement(I);
725 if (isa<UndefValue>(Elem))
726 return true;
727
728 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000729 computeKnownBits(Elem, KnownZero, KnownOne, DL);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000730 if (KnownZero.isAllOnesValue())
731 return true;
732 }
733
734 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000735}
736
737void Lint::visitSDiv(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000738 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000739 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000740}
741
742void Lint::visitUDiv(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000743 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000744 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000745}
746
747void Lint::visitSRem(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000748 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000749 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000750}
751
752void Lint::visitURem(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000753 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000754 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000755}
756
757void Lint::visitAllocaInst(AllocaInst &I) {
758 if (isa<ConstantInt>(I.getArraySize()))
759 // This isn't undefined behavior, it's just an obvious pessimization.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000760 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
761 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000762
763 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000764}
765
766void Lint::visitVAArgInst(VAArgInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000767 visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000768 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000769}
770
771void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000772 visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000773 nullptr, MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000774
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000775 Assert(I.getNumDestinations() != 0,
776 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000777}
778
Dan Gohman7808d492010-04-08 23:05:57 +0000779void Lint::visitExtractElementInst(ExtractElementInst &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000780 if (ConstantInt *CI = dyn_cast<ConstantInt>(
781 findValue(I.getIndexOperand(), I.getModule()->getDataLayout(),
782 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000783 Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
784 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000785}
786
787void Lint::visitInsertElementInst(InsertElementInst &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000788 if (ConstantInt *CI = dyn_cast<ConstantInt>(
789 findValue(I.getOperand(2), I.getModule()->getDataLayout(),
790 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000791 Assert(CI->getValue().ult(I.getType()->getNumElements()),
792 "Undefined result: insertelement index out of range", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000793}
794
795void Lint::visitUnreachableInst(UnreachableInst &I) {
796 // This isn't undefined behavior, it's merely suspicious.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000797 Assert(&I == I.getParent()->begin() ||
798 std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
799 "Unusual: unreachable immediately preceded by instruction without "
800 "side effects",
801 &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000802}
803
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000804/// findValue - Look through bitcasts and simple memory reference patterns
805/// to identify an equivalent, but more informative, value. If OffsetOk
806/// is true, look through getelementptrs with non-zero offsets too.
807///
808/// Most analysis passes don't require this logic, because instcombine
809/// will simplify most of these kinds of things away. But it's a goal of
810/// this Lint pass to be useful even on non-optimized IR.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000811Value *Lint::findValue(Value *V, const DataLayout &DL, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000812 SmallPtrSet<Value *, 4> Visited;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000813 return findValueImpl(V, DL, OffsetOk, Visited);
Dan Gohman862f0342010-05-28 16:45:33 +0000814}
815
816/// findValueImpl - Implementation helper for findValue.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000817Value *Lint::findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000818 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000819 // Detect self-referential values.
David Blaikie70573dc2014-11-19 07:49:26 +0000820 if (!Visited.insert(V).second)
Dan Gohman862f0342010-05-28 16:45:33 +0000821 return UndefValue::get(V->getType());
822
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000823 // TODO: Look through sext or zext cast, when the result is known to
824 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000825 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000826 // TODO: Look through calls with unique return values.
827 // TODO: Look through vector insert/extract/shuffle.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000828 V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000829 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
830 BasicBlock::iterator BBI = L;
831 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000832 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000833 for (;;) {
David Blaikie70573dc2014-11-19 07:49:26 +0000834 if (!VisitedBlocks.insert(BB).second)
835 break;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000836 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
837 BB, BBI, 6, AA))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000838 return findValueImpl(U, DL, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000839 if (BBI != BB->begin()) break;
840 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000841 if (!BB) break;
842 BBI = BB->end();
843 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000844 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000845 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000846 if (W != V)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000847 return findValueImpl(W, DL, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000848 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Matt Arsenaulta236ea52014-03-06 17:33:55 +0000849 if (CI->isNoopCast(DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000850 return findValueImpl(CI->getOperand(0), DL, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000851 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
852 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000853 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000854 if (W != V)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000855 return findValueImpl(W, DL, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000856 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
857 // Same as above, but for ConstantExpr instead of Instruction.
858 if (Instruction::isCast(CE->getOpcode())) {
859 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000860 CE->getOperand(0)->getType(), CE->getType(),
861 DL.getIntPtrType(V->getType())))
862 return findValueImpl(CE->getOperand(0), DL, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000863 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000864 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000865 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000866 if (W != V)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000867 return findValueImpl(W, DL, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000868 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000869 }
870
871 // As a last resort, try SimplifyInstruction or constant folding.
872 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000873 if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000874 return findValueImpl(W, DL, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000875 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000876 if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000877 if (W != V)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000878 return findValueImpl(W, DL, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000879 }
880
881 return V;
882}
883
Dan Gohman98bc4372010-04-08 18:47:09 +0000884//===----------------------------------------------------------------------===//
885// Implement the public interfaces to this file...
886//===----------------------------------------------------------------------===//
887
888FunctionPass *llvm::createLintPass() {
889 return new Lint();
890}
891
892/// lintFunction - Check a function for errors, printing messages on stderr.
893///
894void llvm::lintFunction(const Function &f) {
895 Function &F = const_cast<Function&>(f);
896 assert(!F.isDeclaration() && "Cannot lint external functions");
897
Chandler Carruth30d69c22015-02-13 10:01:29 +0000898 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman98bc4372010-04-08 18:47:09 +0000899 Lint *V = new Lint();
900 FPM.add(V);
901 FPM.run(F);
902}
903
904/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000905///
Dan Gohman084bcb12010-05-26 22:28:53 +0000906void llvm::lintModule(const Module &M) {
Chandler Carruth30d69c22015-02-13 10:01:29 +0000907 legacy::PassManager PM;
Dan Gohman98bc4372010-04-08 18:47:09 +0000908 Lint *V = new Lint();
909 PM.add(V);
910 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000911}