blob: 56065db28144c40cc9f978fafc086d20d0440533 [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
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000101 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman862f0342010-05-28 16:45:33 +0000102 Value *findValueImpl(Value *V, 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;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000110 const DataLayout *DL;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000111 TargetLibraryInfo *TLI;
Dan Gohman98bc4372010-04-08 18:47:09 +0000112
Alp Tokere69170a2014-06-26 22:52:05 +0000113 std::string Messages;
114 raw_string_ostream MessagesStr;
Dan Gohman98bc4372010-04-08 18:47:09 +0000115
116 static char ID; // Pass identification, replacement for typeid
Alp Tokere69170a2014-06-26 22:52:05 +0000117 Lint() : FunctionPass(ID), MessagesStr(Messages) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000118 initializeLintPass(*PassRegistry::getPassRegistry());
119 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000120
Craig Toppere9ba7592014-03-05 07:30:04 +0000121 bool runOnFunction(Function &F) override;
Dan Gohman98bc4372010-04-08 18:47:09 +0000122
Craig Toppere9ba7592014-03-05 07:30:04 +0000123 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman98bc4372010-04-08 18:47:09 +0000124 AU.setPreservesAll();
125 AU.addRequired<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000126 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000127 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000128 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000129 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000130 void print(raw_ostream &O, const Module *M) const override {}
Dan Gohman98bc4372010-04-08 18:47:09 +0000131
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000132 void WriteValues(ArrayRef<const Value *> Vs) {
133 for (const Value *V : Vs) {
134 if (!V)
135 continue;
136 if (isa<Instruction>(V)) {
137 MessagesStr << *V << '\n';
138 } else {
139 V->printAsOperand(MessagesStr, true, Mod);
140 MessagesStr << '\n';
141 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000142 }
143 }
144
Dan Gohman98bc4372010-04-08 18:47:09 +0000145 // CheckFailed - A check failed, so print out the condition and the message
146 // that failed. This provides a nice place to put a breakpoint if you want
147 // to see why something is not correct.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000148 template <typename... Ts>
149 void CheckFailed(const Twine &Message, const Ts &...Vs) {
150 MessagesStr << Message << '\n';
151 WriteValues({Vs...});
Dan Gohman98bc4372010-04-08 18:47:09 +0000152 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000153 };
154}
155
156char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000157INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
158 false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +0000159INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000160INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000161INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000162INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
163INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
164 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000165
166// Assert - We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000167#define Assert(C, ...) \
168 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
Dan Gohman98bc4372010-04-08 18:47:09 +0000169
170// Lint::run - This is the main Analysis entry point for a
171// function.
172//
173bool Lint::runOnFunction(Function &F) {
174 Mod = F.getParent();
175 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000176 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000177 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Mehdi Amini46a43552015-03-04 18:43:29 +0000178 DL = &F.getParent()->getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000179 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman98bc4372010-04-08 18:47:09 +0000180 visit(F);
181 dbgs() << MessagesStr.str();
Alp Tokere69170a2014-06-26 22:52:05 +0000182 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000183 return false;
184}
185
Dan Gohman9ba08a42010-04-09 01:39:53 +0000186void Lint::visitFunction(Function &F) {
187 // This isn't undefined behavior, it's just a little unusual, and it's a
188 // fairly common mistake to neglect to name a function.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000189 Assert(F.hasName() || F.hasLocalLinkage(),
190 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000191
192 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000193}
194
195void Lint::visitCallSite(CallSite CS) {
196 Instruction &I = *CS.getInstruction();
197 Value *Callee = CS.getCalledValue();
198
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000199 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000200 0, nullptr, MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000201
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000202 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000203 Assert(CS.getCallingConv() == F->getCallingConv(),
204 "Undefined behavior: Caller and callee calling convention differ",
205 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000206
Chris Lattner229907c2011-07-18 04:54:35 +0000207 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000208 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000209
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000210 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
211 : FT->getNumParams() == NumActualArgs,
212 "Undefined behavior: Call argument count mismatches callee "
213 "argument count",
214 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000215
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000216 Assert(FT->getReturnType() == I.getType(),
217 "Undefined behavior: Call return type mismatches "
218 "callee return type",
219 &I);
Dan Gohmanc128e702010-07-12 18:02:04 +0000220
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++;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000229 Assert(Formal->getType() == Actual->getType(),
230 "Undefined behavior: Call argument type mismatches "
231 "callee parameter type",
232 &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000233
Dan Gohman3cb55a12010-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 Gohman0fa67e42010-05-28 21:43:57 +0000237 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000238 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000239 if (AI != BI && (*BI)->getType()->isPointerTy()) {
240 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000241 Assert(Result != AliasAnalysis::MustAlias &&
242 Result != AliasAnalysis::PartialAlias,
243 "Unusual: noalias argument aliases another argument", &I);
Dan Gohman201acdb2010-12-10 20:04:06 +0000244 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000245
246 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000247 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000248 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000249 cast<PointerType>(Formal->getType())->getElementType();
250 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000251 DL ? DL->getABITypeAlignment(Ty) : 0,
Dan Gohman0fa67e42010-05-28 21:43:57 +0000252 Ty, MemRef::Read | MemRef::Write);
253 }
254 }
255 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000256 }
257
Dan Gohman1249adf2010-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 Gohman54d7aaa2010-05-28 16:21:24 +0000261 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000262 Assert(!isa<AllocaInst>(Obj),
263 "Undefined behavior: Call with \"tail\" keyword references alloca",
264 &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000265 }
266
Dan Gohman98bc4372010-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 Gohman0fa67e42010-05-28 21:43:57 +0000276 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000277 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000278 MCI->getAlignment(), nullptr,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000279 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000280 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000281 MCI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000282 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000283
Dan Gohman9ba08a42010-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 Gohmanf372cf82010-10-19 22:54:46 +0000287 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000288 if (const ConstantInt *Len =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000289 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
290 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000291 if (Len->getValue().isIntN(32))
292 Size = Len->getValue().getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000293 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
294 AliasAnalysis::MustAlias,
295 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000296 break;
297 }
298 case Intrinsic::memmove: {
299 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000300 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000301 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000302 MMI->getAlignment(), nullptr,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000303 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000304 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000305 MMI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000306 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000307 break;
308 }
309 case Intrinsic::memset: {
310 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000311 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000312 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000313 MSI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000314 MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000315 break;
316 }
317
318 case Intrinsic::vastart:
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000319 Assert(I.getParent()->getParent()->isVarArg(),
320 "Undefined behavior: va_start called in a non-varargs function",
321 &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000322
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000323 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000324 0, nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000325 break;
326 case Intrinsic::vacopy:
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000327 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000328 0, nullptr, MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000329 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000330 0, nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000331 break;
332 case Intrinsic::vaend:
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000333 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000334 0, nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000335 break;
Dan Gohmana20a5cd2010-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 Gohman14fe8cf22010-10-19 17:06:23 +0000341 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000342 0, nullptr, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000343 break;
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000344
345 case Intrinsic::eh_begincatch:
346 visitEHBeginCatch(II);
347 break;
348 case Intrinsic::eh_endcatch:
349 visitEHEndCatch(II);
350 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000351 }
352}
353
354void Lint::visitCallInst(CallInst &I) {
355 return visitCallSite(&I);
356}
357
358void Lint::visitInvokeInst(InvokeInst &I) {
359 return visitCallSite(&I);
360}
361
362void Lint::visitReturnInst(ReturnInst &I) {
363 Function *F = I.getParent()->getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000364 Assert(!F->doesNotReturn(),
365 "Unusual: Return statement in function with noreturn attribute", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000366
367 if (Value *V = I.getReturnValue()) {
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000368 Value *Obj = findValue(V, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000369 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000370 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000371}
372
Dan Gohman0fa67e42010-05-28 21:43:57 +0000373// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000374// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000375void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000376 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000377 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000378 // If no memory is being referenced, it doesn't matter if the pointer
379 // is valid.
380 if (Size == 0)
381 return;
382
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000383 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000384 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
385 "Undefined behavior: Null pointer dereference", &I);
386 Assert(!isa<UndefValue>(UnderlyingObject),
387 "Undefined behavior: Undef pointer dereference", &I);
388 Assert(!isa<ConstantInt>(UnderlyingObject) ||
389 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
390 "Unusual: All-ones pointer dereference", &I);
391 Assert(!isa<ConstantInt>(UnderlyingObject) ||
392 !cast<ConstantInt>(UnderlyingObject)->isOne(),
393 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000394
Dan Gohman299e7b92010-04-30 19:05:00 +0000395 if (Flags & MemRef::Write) {
396 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000397 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
398 &I);
399 Assert(!isa<Function>(UnderlyingObject) &&
400 !isa<BlockAddress>(UnderlyingObject),
401 "Undefined behavior: Write to text section", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000402 }
403 if (Flags & MemRef::Read) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000404 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
405 &I);
406 Assert(!isa<BlockAddress>(UnderlyingObject),
407 "Undefined behavior: Load from block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000408 }
409 if (Flags & MemRef::Callee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000410 Assert(!isa<BlockAddress>(UnderlyingObject),
411 "Undefined behavior: Call to block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000412 }
413 if (Flags & MemRef::Branchee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000414 Assert(!isa<Constant>(UnderlyingObject) ||
415 isa<BlockAddress>(UnderlyingObject),
416 "Undefined behavior: Branch to non-blockaddress", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000417 }
418
Duncan Sandsa221eea2012-09-26 07:45:36 +0000419 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000420 // Only handles memory references that read/write something simple like an
421 // alloca instruction or a global variable.
422 int64_t Offset = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000423 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
Dan Gohman20a2ae92013-01-31 02:00:45 +0000424 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
425 // something we can handle and if so extract the size of this base object
426 // along with its alignment.
427 uint64_t BaseSize = AliasAnalysis::UnknownSize;
428 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000429
Dan Gohman20a2ae92013-01-31 02:00:45 +0000430 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
431 Type *ATy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000432 if (DL && !AI->isArrayAllocation() && ATy->isSized())
433 BaseSize = DL->getTypeAllocSize(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000434 BaseAlign = AI->getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000435 if (DL && BaseAlign == 0 && ATy->isSized())
436 BaseAlign = DL->getABITypeAlignment(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000437 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
438 // If the global may be defined differently in another compilation unit
439 // then don't warn about funky memory accesses.
440 if (GV->hasDefinitiveInitializer()) {
441 Type *GTy = GV->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000442 if (DL && GTy->isSized())
443 BaseSize = DL->getTypeAllocSize(GTy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000444 BaseAlign = GV->getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000445 if (DL && BaseAlign == 0 && GTy->isSized())
446 BaseAlign = DL->getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000447 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000448 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000449
450 // Accesses from before the start or after the end of the object are not
451 // defined.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000452 Assert(Size == AliasAnalysis::UnknownSize ||
453 BaseSize == AliasAnalysis::UnknownSize ||
454 (Offset >= 0 && Offset + Size <= BaseSize),
455 "Undefined behavior: Buffer overflow", &I);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000456
457 // Accesses that say that the memory is more aligned than it is are not
458 // defined.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000459 if (DL && Align == 0 && Ty && Ty->isSized())
460 Align = DL->getABITypeAlignment(Ty);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000461 Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
462 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000463 }
464}
465
466void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000467 visitMemoryReference(I, I.getPointerOperand(),
468 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
469 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000470}
471
472void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000473 visitMemoryReference(I, I.getPointerOperand(),
474 AA->getTypeStoreSize(I.getOperand(0)->getType()),
475 I.getAlignment(),
476 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000477}
478
Dan Gohman9ba08a42010-04-09 01:39:53 +0000479void Lint::visitXor(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000480 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
481 "Undefined result: xor(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000482}
483
484void Lint::visitSub(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000485 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
486 "Undefined result: sub(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000487}
488
Dan Gohman7808d492010-04-08 23:05:57 +0000489void Lint::visitLShr(BinaryOperator &I) {
490 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000491 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000492 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
493 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000494}
495
496void Lint::visitAShr(BinaryOperator &I) {
497 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000498 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000499 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
500 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000501}
502
503void Lint::visitShl(BinaryOperator &I) {
504 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000505 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000506 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
507 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000508}
509
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000510static bool
511allPredsCameFromLandingPad(BasicBlock *BB,
512 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
513 VisitedBlocks.insert(BB);
514 if (BB->isLandingPad())
515 return true;
516 // If we find a block with no predecessors, the search failed.
517 if (pred_empty(BB))
518 return false;
519 for (BasicBlock *Pred : predecessors(BB)) {
520 if (VisitedBlocks.count(Pred))
521 continue;
522 if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
523 return false;
524 }
525 return true;
526}
527
528static bool
529allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
530 IntrinsicInst **SecondBeginCatch,
531 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
532 VisitedBlocks.insert(BB);
533 for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
534 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
535 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
536 return true;
537 // If we find another begincatch while looking for an endcatch,
538 // that's also an error.
539 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
540 *SecondBeginCatch = IC;
541 return false;
542 }
543 }
544
545 // If we reach a block with no successors while searching, the
546 // search has failed.
547 if (succ_empty(BB))
548 return false;
549 // Otherwise, search all of the successors.
550 for (BasicBlock *Succ : successors(BB)) {
551 if (VisitedBlocks.count(Succ))
552 continue;
553 if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
554 VisitedBlocks))
555 return false;
556 }
557 return true;
558}
559
560void Lint::visitEHBeginCatch(IntrinsicInst *II) {
561 // The checks in this function make a potentially dubious assumption about
562 // the CFG, namely that any block involved in a catch is only used for the
563 // catch. This will very likely be true of IR generated by a front end,
564 // but it may cease to be true, for example, if the IR is run through a
565 // pass which combines similar blocks.
566 //
567 // In general, if we encounter a block the isn't dominated by the catch
568 // block while we are searching the catch block's successors for a call
569 // to end catch intrinsic, then it is possible that it will be legal for
570 // a path through this block to never reach a call to llvm.eh.endcatch.
571 // An analogous statement could be made about our search for a landing
572 // pad among the catch block's predecessors.
573 //
574 // What is actually required is that no path is possible at runtime that
575 // reaches a call to llvm.eh.begincatch without having previously visited
576 // a landingpad instruction and that no path is possible at runtime that
577 // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
578 // (mentally adjusting for the fact that in reality these calls will be
579 // removed before code generation).
580 //
581 // Because this is a lint check, we take a pessimistic approach and warn if
582 // the control flow is potentially incorrect.
583
584 SmallSet<BasicBlock *, 4> VisitedBlocks;
585 BasicBlock *CatchBB = II->getParent();
586
587 // The begin catch must occur in a landing pad block or all paths
588 // to it must have come from a landing pad.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000589 Assert(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
590 "llvm.eh.begincatch may be reachable without passing a landingpad",
591 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000592
593 // Reset the visited block list.
594 VisitedBlocks.clear();
595
596 IntrinsicInst *SecondBeginCatch = nullptr;
597
598 // This has to be called before it is asserted. Otherwise, the first assert
599 // below can never be hit.
600 bool EndCatchFound = allSuccessorsReachEndCatch(
601 CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
602 &SecondBeginCatch, VisitedBlocks);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000603 Assert(
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000604 SecondBeginCatch == nullptr,
605 "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
606 II, SecondBeginCatch);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000607 Assert(EndCatchFound,
608 "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
609 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000610}
611
612static bool allPredCameFromBeginCatch(
613 BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
614 IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
615 VisitedBlocks.insert(BB);
616 // Look for a begincatch in this block.
617 for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
618 ++RI) {
619 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
620 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
621 return true;
622 // If we find another end catch before we find a begin catch, that's
623 // an error.
624 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
625 *SecondEndCatch = IC;
626 return false;
627 }
628 // If we encounter a landingpad instruction, the search failed.
629 if (isa<LandingPadInst>(*RI))
630 return false;
631 }
632 // If while searching we find a block with no predeccesors,
633 // the search failed.
634 if (pred_empty(BB))
635 return false;
636 // Search any predecessors we haven't seen before.
637 for (BasicBlock *Pred : predecessors(BB)) {
638 if (VisitedBlocks.count(Pred))
639 continue;
640 if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
641 VisitedBlocks))
642 return false;
643 }
644 return true;
645}
646
647void Lint::visitEHEndCatch(IntrinsicInst *II) {
648 // The check in this function makes a potentially dubious assumption about
649 // the CFG, namely that any block involved in a catch is only used for the
650 // catch. This will very likely be true of IR generated by a front end,
651 // but it may cease to be true, for example, if the IR is run through a
652 // pass which combines similar blocks.
653 //
654 // In general, if we encounter a block the isn't post-dominated by the
655 // end catch block while we are searching the end catch block's predecessors
656 // for a call to the begin catch intrinsic, then it is possible that it will
657 // be legal for a path to reach the end catch block without ever having
658 // called llvm.eh.begincatch.
659 //
660 // What is actually required is that no path is possible at runtime that
661 // reaches a call to llvm.eh.endcatch without having previously visited
662 // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
663 // reality these calls will be removed before code generation).
664 //
665 // Because this is a lint check, we take a pessimistic approach and warn if
666 // the control flow is potentially incorrect.
667
668 BasicBlock *EndCatchBB = II->getParent();
669
670 // Alls paths to the end catch call must pass through a begin catch call.
671
672 // If llvm.eh.begincatch wasn't called in the current block, we'll use this
673 // lambda to recursively look for it in predecessors.
674 SmallSet<BasicBlock *, 4> VisitedBlocks;
675 IntrinsicInst *SecondEndCatch = nullptr;
676
677 // This has to be called before it is asserted. Otherwise, the first assert
678 // below can never be hit.
679 bool BeginCatchFound =
680 allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
681 &SecondEndCatch, VisitedBlocks);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000682 Assert(
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000683 SecondEndCatch == nullptr,
684 "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
685 II, SecondEndCatch);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000686 Assert(BeginCatchFound,
687 "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
688 II);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000689}
690
Hal Finkel60db0582014-09-07 18:57:58 +0000691static bool isZero(Value *V, const DataLayout *DL, DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000692 AssumptionCache *AC) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000693 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000694 if (isa<UndefValue>(V))
695 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000696
Matt Arsenault5faa6692013-08-26 23:29:33 +0000697 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
698 if (!VecTy) {
699 unsigned BitWidth = V->getType()->getIntegerBitWidth();
700 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +0000701 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
702 dyn_cast<Instruction>(V), DT);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000703 return KnownZero.isAllOnesValue();
704 }
705
706 // Per-component check doesn't work with zeroinitializer
707 Constant *C = dyn_cast<Constant>(V);
708 if (!C)
709 return false;
710
711 if (C->isZeroValue())
712 return true;
713
714 // For a vector, KnownZero will only be true if all values are zero, so check
715 // this per component
716 unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
717 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
718 Constant *Elem = C->getAggregateElement(I);
719 if (isa<UndefValue>(Elem))
720 return true;
721
722 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000723 computeKnownBits(Elem, KnownZero, KnownOne, DL);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000724 if (KnownZero.isAllOnesValue())
725 return true;
726 }
727
728 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000729}
730
731void Lint::visitSDiv(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000732 Assert(!isZero(I.getOperand(1), DL, DT, AC),
733 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000734}
735
736void Lint::visitUDiv(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000737 Assert(!isZero(I.getOperand(1), DL, DT, AC),
738 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000739}
740
741void Lint::visitSRem(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000742 Assert(!isZero(I.getOperand(1), DL, DT, AC),
743 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000744}
745
746void Lint::visitURem(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000747 Assert(!isZero(I.getOperand(1), DL, DT, AC),
748 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000749}
750
751void Lint::visitAllocaInst(AllocaInst &I) {
752 if (isa<ConstantInt>(I.getArraySize()))
753 // This isn't undefined behavior, it's just an obvious pessimization.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000754 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
755 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000756
757 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000758}
759
760void Lint::visitVAArgInst(VAArgInst &I) {
Craig Topper9f008862014-04-15 04:59:12 +0000761 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
762 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000763}
764
765void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Craig Topper9f008862014-04-15 04:59:12 +0000766 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
767 nullptr, MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000768
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000769 Assert(I.getNumDestinations() != 0,
770 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000771}
772
Dan Gohman7808d492010-04-08 23:05:57 +0000773void Lint::visitExtractElementInst(ExtractElementInst &I) {
774 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000775 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
776 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000777 Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
778 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000779}
780
781void Lint::visitInsertElementInst(InsertElementInst &I) {
782 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000783 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
784 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000785 Assert(CI->getValue().ult(I.getType()->getNumElements()),
786 "Undefined result: insertelement index out of range", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000787}
788
789void Lint::visitUnreachableInst(UnreachableInst &I) {
790 // This isn't undefined behavior, it's merely suspicious.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000791 Assert(&I == I.getParent()->begin() ||
792 std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
793 "Unusual: unreachable immediately preceded by instruction without "
794 "side effects",
795 &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000796}
797
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000798/// findValue - Look through bitcasts and simple memory reference patterns
799/// to identify an equivalent, but more informative, value. If OffsetOk
800/// is true, look through getelementptrs with non-zero offsets too.
801///
802/// Most analysis passes don't require this logic, because instcombine
803/// will simplify most of these kinds of things away. But it's a goal of
804/// this Lint pass to be useful even on non-optimized IR.
805Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000806 SmallPtrSet<Value *, 4> Visited;
807 return findValueImpl(V, OffsetOk, Visited);
808}
809
810/// findValueImpl - Implementation helper for findValue.
811Value *Lint::findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000812 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000813 // Detect self-referential values.
David Blaikie70573dc2014-11-19 07:49:26 +0000814 if (!Visited.insert(V).second)
Dan Gohman862f0342010-05-28 16:45:33 +0000815 return UndefValue::get(V->getType());
816
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000817 // TODO: Look through sext or zext cast, when the result is known to
818 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000819 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000820 // TODO: Look through calls with unique return values.
821 // TODO: Look through vector insert/extract/shuffle.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000822 V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000823 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
824 BasicBlock::iterator BBI = L;
825 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000826 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000827 for (;;) {
David Blaikie70573dc2014-11-19 07:49:26 +0000828 if (!VisitedBlocks.insert(BB).second)
829 break;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000830 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
831 BB, BBI, 6, AA))
Dan Gohman862f0342010-05-28 16:45:33 +0000832 return findValueImpl(U, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000833 if (BBI != BB->begin()) break;
834 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000835 if (!BB) break;
836 BBI = BB->end();
837 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000838 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000839 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000840 if (W != V)
841 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000842 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Matt Arsenaulta236ea52014-03-06 17:33:55 +0000843 if (CI->isNoopCast(DL))
Dan Gohman862f0342010-05-28 16:45:33 +0000844 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000845 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
846 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000847 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000848 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000849 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000850 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
851 // Same as above, but for ConstantExpr instead of Instruction.
852 if (Instruction::isCast(CE->getOpcode())) {
853 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
854 CE->getOperand(0)->getType(),
855 CE->getType(),
Matt Arsenaulta236ea52014-03-06 17:33:55 +0000856 DL ? DL->getIntPtrType(V->getType()) :
Dan Gohman0fa67e42010-05-28 21:43:57 +0000857 Type::getInt64Ty(V->getContext())))
858 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
859 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000860 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000861 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000862 if (W != V)
863 return findValueImpl(W, OffsetOk, Visited);
864 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000865 }
866
867 // As a last resort, try SimplifyInstruction or constant folding.
868 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000869 if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
Duncan Sands64e41cf2010-11-17 08:35:29 +0000870 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000871 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000872 if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000873 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000874 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000875 }
876
877 return V;
878}
879
Dan Gohman98bc4372010-04-08 18:47:09 +0000880//===----------------------------------------------------------------------===//
881// Implement the public interfaces to this file...
882//===----------------------------------------------------------------------===//
883
884FunctionPass *llvm::createLintPass() {
885 return new Lint();
886}
887
888/// lintFunction - Check a function for errors, printing messages on stderr.
889///
890void llvm::lintFunction(const Function &f) {
891 Function &F = const_cast<Function&>(f);
892 assert(!F.isDeclaration() && "Cannot lint external functions");
893
Chandler Carruth30d69c22015-02-13 10:01:29 +0000894 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman98bc4372010-04-08 18:47:09 +0000895 Lint *V = new Lint();
896 FPM.add(V);
897 FPM.run(F);
898}
899
900/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000901///
Dan Gohman084bcb12010-05-26 22:28:53 +0000902void llvm::lintModule(const Module &M) {
Chandler Carruth30d69c22015-02-13 10:01:29 +0000903 legacy::PassManager PM;
Dan Gohman98bc4372010-04-08 18:47:09 +0000904 Lint *V = new Lint();
905 PM.add(V);
906 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000907}