blob: 874ed0abb99a27e17f5a327935e0933fcb840c2d [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 {
62 static unsigned Read = 1;
63 static unsigned Write = 2;
64 static unsigned Callee = 4;
65 static unsigned Branchee = 8;
66 }
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
132 void WriteValue(const Value *V) {
133 if (!V) return;
134 if (isa<Instruction>(V)) {
135 MessagesStr << *V << '\n';
136 } else {
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000137 V->printAsOperand(MessagesStr, true, Mod);
Dan Gohman98bc4372010-04-08 18:47:09 +0000138 MessagesStr << '\n';
139 }
140 }
141
Dan Gohman98bc4372010-04-08 18:47:09 +0000142 // CheckFailed - A check failed, so print out the condition and the message
143 // that failed. This provides a nice place to put a breakpoint if you want
144 // to see why something is not correct.
145 void CheckFailed(const Twine &Message,
Craig Topper9f008862014-04-15 04:59:12 +0000146 const Value *V1 = nullptr, const Value *V2 = nullptr,
147 const Value *V3 = nullptr, const Value *V4 = nullptr) {
Dan Gohman98bc4372010-04-08 18:47:09 +0000148 MessagesStr << Message.str() << "\n";
149 WriteValue(V1);
150 WriteValue(V2);
151 WriteValue(V3);
152 WriteValue(V4);
153 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000154 };
155}
156
157char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000158INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
159 false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +0000160INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000161INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000162INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000163INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
164INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
165 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000166
167// Assert - We know that cond should be true, if not print an error message.
168#define Assert(C, M) \
169 do { if (!(C)) { CheckFailed(M); return; } } while (0)
170#define Assert1(C, M, V1) \
171 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
172#define Assert2(C, M, V1, V2) \
173 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
174#define Assert3(C, M, V1, V2, V3) \
175 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
176#define Assert4(C, M, V1, V2, V3, V4) \
177 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
178
179// Lint::run - This is the main Analysis entry point for a
180// function.
181//
182bool Lint::runOnFunction(Function &F) {
183 Mod = F.getParent();
184 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000185 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000186 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Rafael Espindola93512512014-02-25 17:30:31 +0000187 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +0000188 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000189 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman98bc4372010-04-08 18:47:09 +0000190 visit(F);
191 dbgs() << MessagesStr.str();
Alp Tokere69170a2014-06-26 22:52:05 +0000192 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000193 return false;
194}
195
Dan Gohman9ba08a42010-04-09 01:39:53 +0000196void Lint::visitFunction(Function &F) {
197 // This isn't undefined behavior, it's just a little unusual, and it's a
198 // fairly common mistake to neglect to name a function.
199 Assert1(F.hasName() || F.hasLocalLinkage(),
200 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000201
202 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000203}
204
205void Lint::visitCallSite(CallSite CS) {
206 Instruction &I = *CS.getInstruction();
207 Value *Callee = CS.getCalledValue();
208
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000209 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000210 0, nullptr, MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000211
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000212 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman98bc4372010-04-08 18:47:09 +0000213 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000214 "Undefined behavior: Caller and callee calling convention differ",
215 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000216
Chris Lattner229907c2011-07-18 04:54:35 +0000217 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000218 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000219
220 Assert1(FT->isVarArg() ?
221 FT->getNumParams() <= NumActualArgs :
222 FT->getNumParams() == NumActualArgs,
Dan Gohman9ba08a42010-04-09 01:39:53 +0000223 "Undefined behavior: Call argument count mismatches callee "
224 "argument count", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000225
Dan Gohmanc128e702010-07-12 18:02:04 +0000226 Assert1(FT->getReturnType() == I.getType(),
227 "Undefined behavior: Call return type mismatches "
228 "callee return type", &I);
229
Dan Gohman0fa67e42010-05-28 21:43:57 +0000230 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman1e33b182010-07-06 15:23:00 +0000231 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000232 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
233 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
234 for (; AI != AE; ++AI) {
235 Value *Actual = *AI;
236 if (PI != PE) {
237 Argument *Formal = PI++;
238 Assert1(Formal->getType() == Actual->getType(),
239 "Undefined behavior: Call argument type mismatches "
240 "callee parameter type", &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000241
Dan Gohman3cb55a12010-12-13 22:53:18 +0000242 // Check that noalias arguments don't alias other arguments. This is
243 // not fully precise because we don't know the sizes of the dereferenced
244 // memory regions.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000245 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000246 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000247 if (AI != BI && (*BI)->getType()->isPointerTy()) {
248 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
249 Assert1(Result != AliasAnalysis::MustAlias &&
250 Result != AliasAnalysis::PartialAlias,
251 "Unusual: noalias argument aliases another argument", &I);
252 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000253
254 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000255 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000256 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000257 cast<PointerType>(Formal->getType())->getElementType();
258 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000259 DL ? DL->getABITypeAlignment(Ty) : 0,
Dan Gohman0fa67e42010-05-28 21:43:57 +0000260 Ty, MemRef::Read | MemRef::Write);
261 }
262 }
263 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000264 }
265
Dan Gohman1249adf2010-05-26 21:46:36 +0000266 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
267 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
268 AI != AE; ++AI) {
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000269 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohmancef9fc32010-05-28 16:34:49 +0000270 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman1249adf2010-05-26 21:46:36 +0000271 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohmancef9fc32010-05-28 16:34:49 +0000272 "alloca", &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000273 }
274
Dan Gohman98bc4372010-04-08 18:47:09 +0000275
276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
277 switch (II->getIntrinsicID()) {
278 default: break;
279
280 // TODO: Check more intrinsics
281
282 case Intrinsic::memcpy: {
283 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000284 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000285 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000286 MCI->getAlignment(), nullptr,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000287 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000288 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000289 MCI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000290 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000291
Dan Gohman9ba08a42010-04-09 01:39:53 +0000292 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
293 // isn't expressive enough for what we really want to do. Known partial
294 // overlap is not distinguished from the case where nothing is known.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000295 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000296 if (const ConstantInt *Len =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000297 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
298 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000299 if (Len->getValue().isIntN(32))
300 Size = Len->getValue().getZExtValue();
301 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
302 AliasAnalysis::MustAlias,
Dan Gohman9ba08a42010-04-09 01:39:53 +0000303 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000304 break;
305 }
306 case Intrinsic::memmove: {
307 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000308 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000309 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000310 MMI->getAlignment(), nullptr,
Dan Gohmanc575ec62010-05-28 17:44:00 +0000311 MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000312 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000313 MMI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000314 MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000315 break;
316 }
317 case Intrinsic::memset: {
318 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000319 // TODO: If the size is known, use it.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000320 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000321 MSI->getAlignment(), nullptr,
Dan Gohman299e7b92010-04-30 19:05:00 +0000322 MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000323 break;
324 }
325
326 case Intrinsic::vastart:
Dan Gohman9ba08a42010-04-09 01:39:53 +0000327 Assert1(I.getParent()->getParent()->isVarArg(),
328 "Undefined behavior: va_start called in a non-varargs function",
329 &I);
330
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000331 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000332 0, nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000333 break;
334 case Intrinsic::vacopy:
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000335 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000336 0, nullptr, MemRef::Write);
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000337 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000338 0, nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000339 break;
340 case Intrinsic::vaend:
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 Gohman98bc4372010-04-08 18:47:09 +0000343 break;
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000344
345 case Intrinsic::stackrestore:
346 // Stackrestore doesn't read or write memory, but it sets the
347 // stack pointer, which the compiler may read from or write to
348 // at any time, so check it for both readability and writeability.
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000349 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
Craig Topper9f008862014-04-15 04:59:12 +0000350 0, nullptr, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000351 break;
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000352
353 case Intrinsic::eh_begincatch:
354 visitEHBeginCatch(II);
355 break;
356 case Intrinsic::eh_endcatch:
357 visitEHEndCatch(II);
358 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000359 }
360}
361
362void Lint::visitCallInst(CallInst &I) {
363 return visitCallSite(&I);
364}
365
366void Lint::visitInvokeInst(InvokeInst &I) {
367 return visitCallSite(&I);
368}
369
370void Lint::visitReturnInst(ReturnInst &I) {
371 Function *F = I.getParent()->getParent();
372 Assert1(!F->doesNotReturn(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000373 "Unusual: Return statement in function with noreturn attribute",
374 &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000375
376 if (Value *V = I.getReturnValue()) {
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000377 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohmancef9fc32010-05-28 16:34:49 +0000378 Assert1(!isa<AllocaInst>(Obj),
379 "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000380 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000381}
382
Dan Gohman0fa67e42010-05-28 21:43:57 +0000383// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000384// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000385void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000386 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000387 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000388 // If no memory is being referenced, it doesn't matter if the pointer
389 // is valid.
390 if (Size == 0)
391 return;
392
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000393 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000394 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
395 "Undefined behavior: Null pointer dereference", &I);
396 Assert1(!isa<UndefValue>(UnderlyingObject),
397 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000398 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
399 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
400 "Unusual: All-ones pointer dereference", &I);
401 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
402 !cast<ConstantInt>(UnderlyingObject)->isOne(),
403 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000404
Dan Gohman299e7b92010-04-30 19:05:00 +0000405 if (Flags & MemRef::Write) {
406 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
407 Assert1(!GV->isConstant(),
408 "Undefined behavior: Write to read-only memory", &I);
409 Assert1(!isa<Function>(UnderlyingObject) &&
410 !isa<BlockAddress>(UnderlyingObject),
411 "Undefined behavior: Write to text section", &I);
412 }
413 if (Flags & MemRef::Read) {
414 Assert1(!isa<Function>(UnderlyingObject),
415 "Unusual: Load from function body", &I);
416 Assert1(!isa<BlockAddress>(UnderlyingObject),
417 "Undefined behavior: Load from block address", &I);
418 }
419 if (Flags & MemRef::Callee) {
420 Assert1(!isa<BlockAddress>(UnderlyingObject),
421 "Undefined behavior: Call to block address", &I);
422 }
423 if (Flags & MemRef::Branchee) {
424 Assert1(!isa<Constant>(UnderlyingObject) ||
425 isa<BlockAddress>(UnderlyingObject),
426 "Undefined behavior: Branch to non-blockaddress", &I);
427 }
428
Duncan Sandsa221eea2012-09-26 07:45:36 +0000429 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000430 // Only handles memory references that read/write something simple like an
431 // alloca instruction or a global variable.
432 int64_t Offset = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000433 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
Dan Gohman20a2ae92013-01-31 02:00:45 +0000434 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
435 // something we can handle and if so extract the size of this base object
436 // along with its alignment.
437 uint64_t BaseSize = AliasAnalysis::UnknownSize;
438 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000439
Dan Gohman20a2ae92013-01-31 02:00:45 +0000440 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
441 Type *ATy = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000442 if (DL && !AI->isArrayAllocation() && ATy->isSized())
443 BaseSize = DL->getTypeAllocSize(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000444 BaseAlign = AI->getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000445 if (DL && BaseAlign == 0 && ATy->isSized())
446 BaseAlign = DL->getABITypeAlignment(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000447 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
448 // If the global may be defined differently in another compilation unit
449 // then don't warn about funky memory accesses.
450 if (GV->hasDefinitiveInitializer()) {
451 Type *GTy = GV->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000452 if (DL && GTy->isSized())
453 BaseSize = DL->getTypeAllocSize(GTy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000454 BaseAlign = GV->getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000455 if (DL && BaseAlign == 0 && GTy->isSized())
456 BaseAlign = DL->getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000457 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000458 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000459
460 // Accesses from before the start or after the end of the object are not
461 // defined.
462 Assert1(Size == AliasAnalysis::UnknownSize ||
463 BaseSize == AliasAnalysis::UnknownSize ||
464 (Offset >= 0 && Offset + Size <= BaseSize),
465 "Undefined behavior: Buffer overflow", &I);
466
467 // Accesses that say that the memory is more aligned than it is are not
468 // defined.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000469 if (DL && Align == 0 && Ty && Ty->isSized())
470 Align = DL->getABITypeAlignment(Ty);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000471 Assert1(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
472 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000473 }
474}
475
476void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000477 visitMemoryReference(I, I.getPointerOperand(),
478 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
479 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000480}
481
482void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000483 visitMemoryReference(I, I.getPointerOperand(),
484 AA->getTypeStoreSize(I.getOperand(0)->getType()),
485 I.getAlignment(),
486 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000487}
488
Dan Gohman9ba08a42010-04-09 01:39:53 +0000489void Lint::visitXor(BinaryOperator &I) {
490 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
491 !isa<UndefValue>(I.getOperand(1)),
492 "Undefined result: xor(undef, undef)", &I);
493}
494
495void Lint::visitSub(BinaryOperator &I) {
496 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
497 !isa<UndefValue>(I.getOperand(1)),
498 "Undefined result: sub(undef, undef)", &I);
499}
500
Dan Gohman7808d492010-04-08 23:05:57 +0000501void Lint::visitLShr(BinaryOperator &I) {
502 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000503 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000504 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000505 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000506}
507
508void Lint::visitAShr(BinaryOperator &I) {
509 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000510 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000511 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000512 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000513}
514
515void Lint::visitShl(BinaryOperator &I) {
516 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000517 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000518 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000519 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000520}
521
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000522static bool
523allPredsCameFromLandingPad(BasicBlock *BB,
524 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
525 VisitedBlocks.insert(BB);
526 if (BB->isLandingPad())
527 return true;
528 // If we find a block with no predecessors, the search failed.
529 if (pred_empty(BB))
530 return false;
531 for (BasicBlock *Pred : predecessors(BB)) {
532 if (VisitedBlocks.count(Pred))
533 continue;
534 if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
535 return false;
536 }
537 return true;
538}
539
540static bool
541allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
542 IntrinsicInst **SecondBeginCatch,
543 SmallSet<BasicBlock *, 4> &VisitedBlocks) {
544 VisitedBlocks.insert(BB);
545 for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
546 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
547 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
548 return true;
549 // If we find another begincatch while looking for an endcatch,
550 // that's also an error.
551 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
552 *SecondBeginCatch = IC;
553 return false;
554 }
555 }
556
557 // If we reach a block with no successors while searching, the
558 // search has failed.
559 if (succ_empty(BB))
560 return false;
561 // Otherwise, search all of the successors.
562 for (BasicBlock *Succ : successors(BB)) {
563 if (VisitedBlocks.count(Succ))
564 continue;
565 if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
566 VisitedBlocks))
567 return false;
568 }
569 return true;
570}
571
572void Lint::visitEHBeginCatch(IntrinsicInst *II) {
573 // The checks in this function make a potentially dubious assumption about
574 // the CFG, namely that any block involved in a catch is only used for the
575 // catch. This will very likely be true of IR generated by a front end,
576 // but it may cease to be true, for example, if the IR is run through a
577 // pass which combines similar blocks.
578 //
579 // In general, if we encounter a block the isn't dominated by the catch
580 // block while we are searching the catch block's successors for a call
581 // to end catch intrinsic, then it is possible that it will be legal for
582 // a path through this block to never reach a call to llvm.eh.endcatch.
583 // An analogous statement could be made about our search for a landing
584 // pad among the catch block's predecessors.
585 //
586 // What is actually required is that no path is possible at runtime that
587 // reaches a call to llvm.eh.begincatch without having previously visited
588 // a landingpad instruction and that no path is possible at runtime that
589 // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
590 // (mentally adjusting for the fact that in reality these calls will be
591 // removed before code generation).
592 //
593 // Because this is a lint check, we take a pessimistic approach and warn if
594 // the control flow is potentially incorrect.
595
596 SmallSet<BasicBlock *, 4> VisitedBlocks;
597 BasicBlock *CatchBB = II->getParent();
598
599 // The begin catch must occur in a landing pad block or all paths
600 // to it must have come from a landing pad.
601 Assert1(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
602 "llvm.eh.begincatch may be reachable without passing a landingpad",
603 II);
604
605 // Reset the visited block list.
606 VisitedBlocks.clear();
607
608 IntrinsicInst *SecondBeginCatch = nullptr;
609
610 // This has to be called before it is asserted. Otherwise, the first assert
611 // below can never be hit.
612 bool EndCatchFound = allSuccessorsReachEndCatch(
613 CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
614 &SecondBeginCatch, VisitedBlocks);
615 Assert2(
616 SecondBeginCatch == nullptr,
617 "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
618 II, SecondBeginCatch);
619 Assert1(EndCatchFound,
620 "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
621 II);
622}
623
624static bool allPredCameFromBeginCatch(
625 BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
626 IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
627 VisitedBlocks.insert(BB);
628 // Look for a begincatch in this block.
629 for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
630 ++RI) {
631 IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
632 if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
633 return true;
634 // If we find another end catch before we find a begin catch, that's
635 // an error.
636 if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
637 *SecondEndCatch = IC;
638 return false;
639 }
640 // If we encounter a landingpad instruction, the search failed.
641 if (isa<LandingPadInst>(*RI))
642 return false;
643 }
644 // If while searching we find a block with no predeccesors,
645 // the search failed.
646 if (pred_empty(BB))
647 return false;
648 // Search any predecessors we haven't seen before.
649 for (BasicBlock *Pred : predecessors(BB)) {
650 if (VisitedBlocks.count(Pred))
651 continue;
652 if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
653 VisitedBlocks))
654 return false;
655 }
656 return true;
657}
658
659void Lint::visitEHEndCatch(IntrinsicInst *II) {
660 // The check in this function makes a potentially dubious assumption about
661 // the CFG, namely that any block involved in a catch is only used for the
662 // catch. This will very likely be true of IR generated by a front end,
663 // but it may cease to be true, for example, if the IR is run through a
664 // pass which combines similar blocks.
665 //
666 // In general, if we encounter a block the isn't post-dominated by the
667 // end catch block while we are searching the end catch block's predecessors
668 // for a call to the begin catch intrinsic, then it is possible that it will
669 // be legal for a path to reach the end catch block without ever having
670 // called llvm.eh.begincatch.
671 //
672 // What is actually required is that no path is possible at runtime that
673 // reaches a call to llvm.eh.endcatch without having previously visited
674 // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
675 // reality these calls will be removed before code generation).
676 //
677 // Because this is a lint check, we take a pessimistic approach and warn if
678 // the control flow is potentially incorrect.
679
680 BasicBlock *EndCatchBB = II->getParent();
681
682 // Alls paths to the end catch call must pass through a begin catch call.
683
684 // If llvm.eh.begincatch wasn't called in the current block, we'll use this
685 // lambda to recursively look for it in predecessors.
686 SmallSet<BasicBlock *, 4> VisitedBlocks;
687 IntrinsicInst *SecondEndCatch = nullptr;
688
689 // This has to be called before it is asserted. Otherwise, the first assert
690 // below can never be hit.
691 bool BeginCatchFound =
692 allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
693 &SecondEndCatch, VisitedBlocks);
694 Assert2(
695 SecondEndCatch == nullptr,
696 "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
697 II, SecondEndCatch);
698 Assert1(
699 BeginCatchFound,
700 "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
701 II);
702}
703
Hal Finkel60db0582014-09-07 18:57:58 +0000704static bool isZero(Value *V, const DataLayout *DL, DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000705 AssumptionCache *AC) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000706 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000707 if (isa<UndefValue>(V))
708 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000709
Matt Arsenault5faa6692013-08-26 23:29:33 +0000710 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
711 if (!VecTy) {
712 unsigned BitWidth = V->getType()->getIntegerBitWidth();
713 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +0000714 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
715 dyn_cast<Instruction>(V), DT);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000716 return KnownZero.isAllOnesValue();
717 }
718
719 // Per-component check doesn't work with zeroinitializer
720 Constant *C = dyn_cast<Constant>(V);
721 if (!C)
722 return false;
723
724 if (C->isZeroValue())
725 return true;
726
727 // For a vector, KnownZero will only be true if all values are zero, so check
728 // this per component
729 unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
730 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
731 Constant *Elem = C->getAggregateElement(I);
732 if (isa<UndefValue>(Elem))
733 return true;
734
735 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000736 computeKnownBits(Elem, KnownZero, KnownOne, DL);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000737 if (KnownZero.isAllOnesValue())
738 return true;
739 }
740
741 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000742}
743
744void Lint::visitSDiv(BinaryOperator &I) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000745 Assert1(!isZero(I.getOperand(1), DL, DT, AC),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000746 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000747}
748
749void Lint::visitUDiv(BinaryOperator &I) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000750 Assert1(!isZero(I.getOperand(1), DL, DT, AC),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000751 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000752}
753
754void Lint::visitSRem(BinaryOperator &I) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000755 Assert1(!isZero(I.getOperand(1), DL, DT, AC),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000756 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000757}
758
759void Lint::visitURem(BinaryOperator &I) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000760 Assert1(!isZero(I.getOperand(1), DL, DT, AC),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000761 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000762}
763
764void Lint::visitAllocaInst(AllocaInst &I) {
765 if (isa<ConstantInt>(I.getArraySize()))
766 // This isn't undefined behavior, it's just an obvious pessimization.
767 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000768 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000769
770 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000771}
772
773void Lint::visitVAArgInst(VAArgInst &I) {
Craig Topper9f008862014-04-15 04:59:12 +0000774 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
775 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000776}
777
778void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Craig Topper9f008862014-04-15 04:59:12 +0000779 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
780 nullptr, MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000781
782 Assert1(I.getNumDestinations() != 0,
783 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000784}
785
Dan Gohman7808d492010-04-08 23:05:57 +0000786void Lint::visitExtractElementInst(ExtractElementInst &I) {
787 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000788 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
789 /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000790 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000791 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000792}
793
794void Lint::visitInsertElementInst(InsertElementInst &I) {
795 if (ConstantInt *CI =
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000796 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
797 /*OffsetOk=*/false)))
Dan Gohman7808d492010-04-08 23:05:57 +0000798 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000799 "Undefined result: insertelement index out of range", &I);
800}
801
802void Lint::visitUnreachableInst(UnreachableInst &I) {
803 // This isn't undefined behavior, it's merely suspicious.
804 Assert1(&I == I.getParent()->begin() ||
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000805 std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
Dan Gohman9ba08a42010-04-09 01:39:53 +0000806 "Unusual: unreachable immediately preceded by instruction without "
807 "side effects", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000808}
809
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000810/// findValue - Look through bitcasts and simple memory reference patterns
811/// to identify an equivalent, but more informative, value. If OffsetOk
812/// is true, look through getelementptrs with non-zero offsets too.
813///
814/// Most analysis passes don't require this logic, because instcombine
815/// will simplify most of these kinds of things away. But it's a goal of
816/// this Lint pass to be useful even on non-optimized IR.
817Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000818 SmallPtrSet<Value *, 4> Visited;
819 return findValueImpl(V, OffsetOk, Visited);
820}
821
822/// findValueImpl - Implementation helper for findValue.
823Value *Lint::findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000824 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000825 // Detect self-referential values.
David Blaikie70573dc2014-11-19 07:49:26 +0000826 if (!Visited.insert(V).second)
Dan Gohman862f0342010-05-28 16:45:33 +0000827 return UndefValue::get(V->getType());
828
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000829 // TODO: Look through sext or zext cast, when the result is known to
830 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000831 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000832 // TODO: Look through calls with unique return values.
833 // TODO: Look through vector insert/extract/shuffle.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000834 V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000835 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
836 BasicBlock::iterator BBI = L;
837 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000838 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000839 for (;;) {
David Blaikie70573dc2014-11-19 07:49:26 +0000840 if (!VisitedBlocks.insert(BB).second)
841 break;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000842 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
843 BB, BBI, 6, AA))
Dan Gohman862f0342010-05-28 16:45:33 +0000844 return findValueImpl(U, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000845 if (BBI != BB->begin()) break;
846 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000847 if (!BB) break;
848 BBI = BB->end();
849 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000850 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000851 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000852 if (W != V)
853 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000854 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Matt Arsenaulta236ea52014-03-06 17:33:55 +0000855 if (CI->isNoopCast(DL))
Dan Gohman862f0342010-05-28 16:45:33 +0000856 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000857 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
858 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000859 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000860 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000861 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000862 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
863 // Same as above, but for ConstantExpr instead of Instruction.
864 if (Instruction::isCast(CE->getOpcode())) {
865 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
866 CE->getOperand(0)->getType(),
867 CE->getType(),
Matt Arsenaulta236ea52014-03-06 17:33:55 +0000868 DL ? DL->getIntPtrType(V->getType()) :
Dan Gohman0fa67e42010-05-28 21:43:57 +0000869 Type::getInt64Ty(V->getContext())))
870 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
871 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000872 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000873 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000874 if (W != V)
875 return findValueImpl(W, OffsetOk, Visited);
876 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000877 }
878
879 // As a last resort, try SimplifyInstruction or constant folding.
880 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000881 if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
Duncan Sands64e41cf2010-11-17 08:35:29 +0000882 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000883 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000884 if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000885 if (W != V)
Dan Gohman862f0342010-05-28 16:45:33 +0000886 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000887 }
888
889 return V;
890}
891
Dan Gohman98bc4372010-04-08 18:47:09 +0000892//===----------------------------------------------------------------------===//
893// Implement the public interfaces to this file...
894//===----------------------------------------------------------------------===//
895
896FunctionPass *llvm::createLintPass() {
897 return new Lint();
898}
899
900/// lintFunction - Check a function for errors, printing messages on stderr.
901///
902void llvm::lintFunction(const Function &f) {
903 Function &F = const_cast<Function&>(f);
904 assert(!F.isDeclaration() && "Cannot lint external functions");
905
Chandler Carruth30d69c22015-02-13 10:01:29 +0000906 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman98bc4372010-04-08 18:47:09 +0000907 Lint *V = new Lint();
908 FPM.add(V);
909 FPM.run(F);
910}
911
912/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000913///
Dan Gohman084bcb12010-05-26 22:28:53 +0000914void llvm::lintModule(const Module &M) {
Chandler Carruth30d69c22015-02-13 10:01:29 +0000915 legacy::PassManager PM;
Dan Gohman98bc4372010-04-08 18:47:09 +0000916 Lint *V = new Lint();
917 PM.add(V);
918 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000919}