blob: ada600a69b872d92ddd133bc89f55e82d5c9d40b [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"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000038#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/Twine.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000042#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000043#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000046#include "llvm/Analysis/Loads.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000047#include "llvm/Analysis/MemoryLocation.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000050#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000051#include "llvm/IR/Argument.h"
52#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000053#include "llvm/IR/CallSite.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000054#include "llvm/IR/Constant.h"
55#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/DataLayout.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000057#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000058#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Function.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000060#include "llvm/IR/GlobalVariable.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000061#include "llvm/IR/InstVisitor.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000062#include "llvm/IR/InstrTypes.h"
63#include "llvm/IR/Instruction.h"
64#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000066#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000067#include "llvm/IR/Module.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Pass.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000071#include "llvm/Support/Casting.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000072#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000073#include "llvm/Support/KnownBits.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000074#include "llvm/Support/MathExtras.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000075#include "llvm/Support/raw_ostream.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000076#include <cassert>
77#include <cstdint>
78#include <iterator>
79#include <string>
80
Dan Gohman98bc4372010-04-08 18:47:09 +000081using namespace llvm;
82
83namespace {
Dan Gohman299e7b92010-04-30 19:05:00 +000084 namespace MemRef {
Benjamin Kramer57a3d082015-03-08 16:07:39 +000085 static const unsigned Read = 1;
86 static const unsigned Write = 2;
87 static const unsigned Callee = 4;
88 static const unsigned Branchee = 8;
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000089 } // end namespace MemRef
Dan Gohman299e7b92010-04-30 19:05:00 +000090
Dan Gohman98bc4372010-04-08 18:47:09 +000091 class Lint : public FunctionPass, public InstVisitor<Lint> {
92 friend class InstVisitor<Lint>;
93
Dan Gohman9ba08a42010-04-09 01:39:53 +000094 void visitFunction(Function &F);
95
Dan Gohman98bc4372010-04-08 18:47:09 +000096 void visitCallSite(CallSite CS);
Dan Gohman0fa67e42010-05-28 21:43:57 +000097 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohmanf372cf82010-10-19 22:54:46 +000098 uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +000099 Type *Ty, unsigned Flags);
Andrew Kaylor78b53db2015-02-10 19:52:43 +0000100 void visitEHBeginCatch(IntrinsicInst *II);
101 void visitEHEndCatch(IntrinsicInst *II);
Dan Gohman98bc4372010-04-08 18:47:09 +0000102
Dan Gohman98bc4372010-04-08 18:47:09 +0000103 void visitCallInst(CallInst &I);
104 void visitInvokeInst(InvokeInst &I);
105 void visitReturnInst(ReturnInst &I);
106 void visitLoadInst(LoadInst &I);
107 void visitStoreInst(StoreInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000108 void visitXor(BinaryOperator &I);
109 void visitSub(BinaryOperator &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000110 void visitLShr(BinaryOperator &I);
111 void visitAShr(BinaryOperator &I);
112 void visitShl(BinaryOperator &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000113 void visitSDiv(BinaryOperator &I);
114 void visitUDiv(BinaryOperator &I);
115 void visitSRem(BinaryOperator &I);
116 void visitURem(BinaryOperator &I);
117 void visitAllocaInst(AllocaInst &I);
118 void visitVAArgInst(VAArgInst &I);
119 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000120 void visitExtractElementInst(ExtractElementInst &I);
121 void visitInsertElementInst(InsertElementInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000122 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000123
Chandler Carruth50fee932015-08-06 02:05:46 +0000124 Value *findValue(Value *V, bool OffsetOk) const;
125 Value *findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000126 SmallPtrSetImpl<Value *> &Visited) const;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000127
Dan Gohman98bc4372010-04-08 18:47:09 +0000128 public:
129 Module *Mod;
Chandler Carruth50fee932015-08-06 02:05:46 +0000130 const DataLayout *DL;
Dan Gohman98bc4372010-04-08 18:47:09 +0000131 AliasAnalysis *AA;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000132 AssumptionCache *AC;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000133 DominatorTree *DT;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000134 TargetLibraryInfo *TLI;
Dan Gohman98bc4372010-04-08 18:47:09 +0000135
Alp Tokere69170a2014-06-26 22:52:05 +0000136 std::string Messages;
137 raw_string_ostream MessagesStr;
Dan Gohman98bc4372010-04-08 18:47:09 +0000138
139 static char ID; // Pass identification, replacement for typeid
Alp Tokere69170a2014-06-26 22:52:05 +0000140 Lint() : FunctionPass(ID), MessagesStr(Messages) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000141 initializeLintPass(*PassRegistry::getPassRegistry());
142 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000143
Craig Toppere9ba7592014-03-05 07:30:04 +0000144 bool runOnFunction(Function &F) override;
Dan Gohman98bc4372010-04-08 18:47:09 +0000145
Craig Toppere9ba7592014-03-05 07:30:04 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman98bc4372010-04-08 18:47:09 +0000147 AU.setPreservesAll();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000148 AU.addRequired<AAResultsWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000149 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000150 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000151 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000152 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000153 void print(raw_ostream &O, const Module *M) const override {}
Dan Gohman98bc4372010-04-08 18:47:09 +0000154
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000155 void WriteValues(ArrayRef<const Value *> Vs) {
156 for (const Value *V : Vs) {
157 if (!V)
158 continue;
159 if (isa<Instruction>(V)) {
160 MessagesStr << *V << '\n';
161 } else {
162 V->printAsOperand(MessagesStr, true, Mod);
163 MessagesStr << '\n';
164 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000165 }
166 }
167
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000168 /// \brief A check failed, so printout out the condition and the message.
169 ///
170 /// This provides a nice place to put a breakpoint if you want to see why
171 /// something is not correct.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000172 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
173
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000174 /// \brief A check failed (with values to print).
175 ///
176 /// This calls the Message-only version so that the above is easier to set
177 /// a breakpoint on.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000178 template <typename T1, typename... Ts>
179 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
180 CheckFailed(Message);
181 WriteValues({V1, Vs...});
Dan Gohman98bc4372010-04-08 18:47:09 +0000182 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000183 };
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000184} // end anonymous namespace
Dan Gohman98bc4372010-04-08 18:47:09 +0000185
186char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000187INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
188 false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000189INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000190INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000191INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000192INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000193INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
194 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000195
196// Assert - We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000197#define Assert(C, ...) \
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000198 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
Dan Gohman98bc4372010-04-08 18:47:09 +0000199
200// Lint::run - This is the main Analysis entry point for a
201// function.
202//
203bool Lint::runOnFunction(Function &F) {
204 Mod = F.getParent();
Chandler Carruth50fee932015-08-06 02:05:46 +0000205 DL = &F.getParent()->getDataLayout();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000206 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000207 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000208 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000209 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman98bc4372010-04-08 18:47:09 +0000210 visit(F);
211 dbgs() << MessagesStr.str();
Alp Tokere69170a2014-06-26 22:52:05 +0000212 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000213 return false;
214}
215
Dan Gohman9ba08a42010-04-09 01:39:53 +0000216void Lint::visitFunction(Function &F) {
217 // This isn't undefined behavior, it's just a little unusual, and it's a
218 // fairly common mistake to neglect to name a function.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000219 Assert(F.hasName() || F.hasLocalLinkage(),
220 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000221
222 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000223}
224
225void Lint::visitCallSite(CallSite CS) {
226 Instruction &I = *CS.getInstruction();
227 Value *Callee = CS.getCalledValue();
228
Chandler Carruthecbd1682015-06-17 07:21:38 +0000229 visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
230 MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000231
Chandler Carruth50fee932015-08-06 02:05:46 +0000232 if (Function *F = dyn_cast<Function>(findValue(Callee,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 /*OffsetOk=*/false))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000234 Assert(CS.getCallingConv() == F->getCallingConv(),
235 "Undefined behavior: Caller and callee calling convention differ",
236 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000237
Chris Lattner229907c2011-07-18 04:54:35 +0000238 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000239 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000240
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000241 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
242 : FT->getNumParams() == NumActualArgs,
243 "Undefined behavior: Call argument count mismatches callee "
244 "argument count",
245 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000246
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000247 Assert(FT->getReturnType() == I.getType(),
248 "Undefined behavior: Call return type mismatches "
249 "callee return type",
250 &I);
Dan Gohmanc128e702010-07-12 18:02:04 +0000251
Dan Gohman0fa67e42010-05-28 21:43:57 +0000252 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman1e33b182010-07-06 15:23:00 +0000253 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000254 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
255 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
256 for (; AI != AE; ++AI) {
257 Value *Actual = *AI;
258 if (PI != PE) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000259 Argument *Formal = &*PI++;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000260 Assert(Formal->getType() == Actual->getType(),
261 "Undefined behavior: Call argument type mismatches "
262 "callee parameter type",
263 &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000264
Dan Gohman3cb55a12010-12-13 22:53:18 +0000265 // Check that noalias arguments don't alias other arguments. This is
266 // not fully precise because we don't know the sizes of the dereferenced
267 // memory regions.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000268 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000269 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000270 if (AI != BI && (*BI)->getType()->isPointerTy()) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000271 AliasResult Result = AA->alias(*AI, *BI);
272 Assert(Result != MustAlias && Result != PartialAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000273 "Unusual: noalias argument aliases another argument", &I);
Dan Gohman201acdb2010-12-10 20:04:06 +0000274 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000275
276 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000277 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000278 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000279 cast<PointerType>(Formal->getType())->getElementType();
Chandler Carruth50fee932015-08-06 02:05:46 +0000280 visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
281 DL->getABITypeAlignment(Ty), Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000282 MemRef::Read | MemRef::Write);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000283 }
284 }
285 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000286 }
287
Dan Gohman1249adf2010-05-26 21:46:36 +0000288 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
289 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
290 AI != AE; ++AI) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000291 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000292 Assert(!isa<AllocaInst>(Obj),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000293 "Undefined behavior: Call with \"tail\" keyword references "
294 "alloca",
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000295 &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000296 }
297
Dan Gohman98bc4372010-04-08 18:47:09 +0000298
299 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
300 switch (II->getIntrinsicID()) {
301 default: break;
302
303 // TODO: Check more intrinsics
304
305 case Intrinsic::memcpy: {
306 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000307 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000308 visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000309 MCI->getAlignment(), nullptr, MemRef::Write);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000310 visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000311 MCI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000312
Dan Gohman9ba08a42010-04-09 01:39:53 +0000313 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
314 // isn't expressive enough for what we really want to do. Known partial
315 // overlap is not distinguished from the case where nothing is known.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000316 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000317 if (const ConstantInt *Len =
Chandler Carruth50fee932015-08-06 02:05:46 +0000318 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000320 if (Len->getValue().isIntN(32))
321 Size = Len->getValue().getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000322 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000323 MustAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000324 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000325 break;
326 }
327 case Intrinsic::memmove: {
328 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000329 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000330 visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000331 MMI->getAlignment(), nullptr, MemRef::Write);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000332 visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000333 MMI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000334 break;
335 }
336 case Intrinsic::memset: {
337 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000338 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000339 visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000340 MSI->getAlignment(), nullptr, MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000341 break;
342 }
343
344 case Intrinsic::vastart:
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000345 Assert(I.getParent()->getParent()->isVarArg(),
346 "Undefined behavior: va_start called in a non-varargs function",
347 &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000348
Chandler Carruthecbd1682015-06-17 07:21:38 +0000349 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
350 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000351 break;
352 case Intrinsic::vacopy:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000353 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
354 nullptr, MemRef::Write);
355 visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
356 nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000357 break;
358 case Intrinsic::vaend:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000359 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
360 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000361 break;
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000362
363 case Intrinsic::stackrestore:
364 // Stackrestore doesn't read or write memory, but it sets the
365 // stack pointer, which the compiler may read from or write to
366 // at any time, so check it for both readability and writeability.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000367 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
368 nullptr, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000369 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000370 }
371}
372
373void Lint::visitCallInst(CallInst &I) {
374 return visitCallSite(&I);
375}
376
377void Lint::visitInvokeInst(InvokeInst &I) {
378 return visitCallSite(&I);
379}
380
381void Lint::visitReturnInst(ReturnInst &I) {
382 Function *F = I.getParent()->getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000383 Assert(!F->doesNotReturn(),
384 "Unusual: Return statement in function with noreturn attribute", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000385
386 if (Value *V = I.getReturnValue()) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000387 Value *Obj = findValue(V, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000388 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000389 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000390}
391
Dan Gohman0fa67e42010-05-28 21:43:57 +0000392// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000393// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000394void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000395 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000396 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000397 // If no memory is being referenced, it doesn't matter if the pointer
398 // is valid.
399 if (Size == 0)
400 return;
401
Chandler Carruth50fee932015-08-06 02:05:46 +0000402 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000403 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
404 "Undefined behavior: Null pointer dereference", &I);
405 Assert(!isa<UndefValue>(UnderlyingObject),
406 "Undefined behavior: Undef pointer dereference", &I);
407 Assert(!isa<ConstantInt>(UnderlyingObject) ||
Craig Topper79ab6432017-07-06 18:39:47 +0000408 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000409 "Unusual: All-ones pointer dereference", &I);
410 Assert(!isa<ConstantInt>(UnderlyingObject) ||
411 !cast<ConstantInt>(UnderlyingObject)->isOne(),
412 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000413
Dan Gohman299e7b92010-04-30 19:05:00 +0000414 if (Flags & MemRef::Write) {
415 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000416 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
417 &I);
418 Assert(!isa<Function>(UnderlyingObject) &&
419 !isa<BlockAddress>(UnderlyingObject),
420 "Undefined behavior: Write to text section", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000421 }
422 if (Flags & MemRef::Read) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000423 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
424 &I);
425 Assert(!isa<BlockAddress>(UnderlyingObject),
426 "Undefined behavior: Load from block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000427 }
428 if (Flags & MemRef::Callee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000429 Assert(!isa<BlockAddress>(UnderlyingObject),
430 "Undefined behavior: Call to block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000431 }
432 if (Flags & MemRef::Branchee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000433 Assert(!isa<Constant>(UnderlyingObject) ||
434 isa<BlockAddress>(UnderlyingObject),
435 "Undefined behavior: Branch to non-blockaddress", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000436 }
437
Duncan Sandsa221eea2012-09-26 07:45:36 +0000438 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000439 // Only handles memory references that read/write something simple like an
440 // alloca instruction or a global variable.
441 int64_t Offset = 0;
Chandler Carruth50fee932015-08-06 02:05:46 +0000442 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
Dan Gohman20a2ae92013-01-31 02:00:45 +0000443 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
444 // something we can handle and if so extract the size of this base object
445 // along with its alignment.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000446 uint64_t BaseSize = MemoryLocation::UnknownSize;
Dan Gohman20a2ae92013-01-31 02:00:45 +0000447 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000448
Dan Gohman20a2ae92013-01-31 02:00:45 +0000449 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
450 Type *ATy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000451 if (!AI->isArrayAllocation() && ATy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000452 BaseSize = DL->getTypeAllocSize(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000453 BaseAlign = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000454 if (BaseAlign == 0 && ATy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000455 BaseAlign = DL->getABITypeAlignment(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000456 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
457 // If the global may be defined differently in another compilation unit
458 // then don't warn about funky memory accesses.
459 if (GV->hasDefinitiveInitializer()) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000460 Type *GTy = GV->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 if (GTy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000462 BaseSize = DL->getTypeAllocSize(GTy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000463 BaseAlign = GV->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000464 if (BaseAlign == 0 && GTy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000465 BaseAlign = DL->getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000466 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000467 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000468
469 // Accesses from before the start or after the end of the object are not
470 // defined.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000471 Assert(Size == MemoryLocation::UnknownSize ||
472 BaseSize == MemoryLocation::UnknownSize ||
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000473 (Offset >= 0 && Offset + Size <= BaseSize),
474 "Undefined behavior: Buffer overflow", &I);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000475
476 // Accesses that say that the memory is more aligned than it is are not
477 // defined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000478 if (Align == 0 && Ty && Ty->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000479 Align = DL->getABITypeAlignment(Ty);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000480 Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
481 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000482 }
483}
484
485void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000486 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000487 DL->getTypeStoreSize(I.getType()), I.getAlignment(),
Dan Gohman0fa67e42010-05-28 21:43:57 +0000488 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000489}
490
491void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000492 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000493 DL->getTypeStoreSize(I.getOperand(0)->getType()),
Dan Gohman0fa67e42010-05-28 21:43:57 +0000494 I.getAlignment(),
495 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000496}
497
Dan Gohman9ba08a42010-04-09 01:39:53 +0000498void Lint::visitXor(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000499 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
500 "Undefined result: xor(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000501}
502
503void Lint::visitSub(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000504 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
505 "Undefined result: sub(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000506}
507
Dan Gohman7808d492010-04-08 23:05:57 +0000508void Lint::visitLShr(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000509 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
510 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000511 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
512 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000513}
514
515void Lint::visitAShr(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000516 if (ConstantInt *CI =
517 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000518 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
519 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000520}
521
522void Lint::visitShl(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000523 if (ConstantInt *CI =
524 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000525 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
526 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000527}
528
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000529static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
530 AssumptionCache *AC) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000531 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000532 if (isa<UndefValue>(V))
533 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000534
Matt Arsenault5faa6692013-08-26 23:29:33 +0000535 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
536 if (!VecTy) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000537 KnownBits Known = computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
Craig Topperf0aeee02017-05-05 17:36:09 +0000538 return Known.isZero();
Matt Arsenault5faa6692013-08-26 23:29:33 +0000539 }
540
541 // Per-component check doesn't work with zeroinitializer
542 Constant *C = dyn_cast<Constant>(V);
543 if (!C)
544 return false;
545
546 if (C->isZeroValue())
547 return true;
548
549 // For a vector, KnownZero will only be true if all values are zero, so check
550 // this per component
Matt Arsenault5faa6692013-08-26 23:29:33 +0000551 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
552 Constant *Elem = C->getAggregateElement(I);
553 if (isa<UndefValue>(Elem))
554 return true;
555
Craig Topper8205a1a2017-05-24 16:53:07 +0000556 KnownBits Known = computeKnownBits(Elem, DL);
Craig Topperf0aeee02017-05-05 17:36:09 +0000557 if (Known.isZero())
Matt Arsenault5faa6692013-08-26 23:29:33 +0000558 return true;
559 }
560
561 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000562}
563
564void Lint::visitSDiv(BinaryOperator &I) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000565 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000566 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000567}
568
569void Lint::visitUDiv(BinaryOperator &I) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000570 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000571 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000572}
573
574void Lint::visitSRem(BinaryOperator &I) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000575 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000576 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000577}
578
579void Lint::visitURem(BinaryOperator &I) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000580 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000581 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000582}
583
584void Lint::visitAllocaInst(AllocaInst &I) {
585 if (isa<ConstantInt>(I.getArraySize()))
586 // This isn't undefined behavior, it's just an obvious pessimization.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000587 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
588 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000589
590 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000591}
592
593void Lint::visitVAArgInst(VAArgInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000594 visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000595 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000596}
597
598void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000599 visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000600 nullptr, MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000601
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000602 Assert(I.getNumDestinations() != 0,
603 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000604}
605
Dan Gohman7808d492010-04-08 23:05:57 +0000606void Lint::visitExtractElementInst(ExtractElementInst &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000607 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
608 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000609 Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
610 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000611}
612
613void Lint::visitInsertElementInst(InsertElementInst &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000614 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
615 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000616 Assert(CI->getValue().ult(I.getType()->getNumElements()),
617 "Undefined result: insertelement index out of range", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000618}
619
620void Lint::visitUnreachableInst(UnreachableInst &I) {
621 // This isn't undefined behavior, it's merely suspicious.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000622 Assert(&I == &I.getParent()->front() ||
623 std::prev(I.getIterator())->mayHaveSideEffects(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000624 "Unusual: unreachable immediately preceded by instruction without "
625 "side effects",
626 &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000627}
628
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000629/// findValue - Look through bitcasts and simple memory reference patterns
630/// to identify an equivalent, but more informative, value. If OffsetOk
631/// is true, look through getelementptrs with non-zero offsets too.
632///
633/// Most analysis passes don't require this logic, because instcombine
634/// will simplify most of these kinds of things away. But it's a goal of
635/// this Lint pass to be useful even on non-optimized IR.
Chandler Carruth50fee932015-08-06 02:05:46 +0000636Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000637 SmallPtrSet<Value *, 4> Visited;
Chandler Carruth50fee932015-08-06 02:05:46 +0000638 return findValueImpl(V, OffsetOk, Visited);
Dan Gohman862f0342010-05-28 16:45:33 +0000639}
640
641/// findValueImpl - Implementation helper for findValue.
Chandler Carruth50fee932015-08-06 02:05:46 +0000642Value *Lint::findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000643 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000644 // Detect self-referential values.
David Blaikie70573dc2014-11-19 07:49:26 +0000645 if (!Visited.insert(V).second)
Dan Gohman862f0342010-05-28 16:45:33 +0000646 return UndefValue::get(V->getType());
647
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000648 // TODO: Look through sext or zext cast, when the result is known to
649 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000650 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000651 // TODO: Look through calls with unique return values.
652 // TODO: Look through vector insert/extract/shuffle.
Chandler Carruth50fee932015-08-06 02:05:46 +0000653 V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000654 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000655 BasicBlock::iterator BBI = L->getIterator();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000656 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000657 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000658 for (;;) {
David Blaikie70573dc2014-11-19 07:49:26 +0000659 if (!VisitedBlocks.insert(BB).second)
660 break;
Larisse Voufo532bf712015-09-18 19:14:35 +0000661 if (Value *U =
Eduard Burtescue2a69172016-01-22 01:51:51 +0000662 FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
Chandler Carruth50fee932015-08-06 02:05:46 +0000663 return findValueImpl(U, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000664 if (BBI != BB->begin()) break;
665 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000666 if (!BB) break;
667 BBI = BB->end();
668 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000669 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000670 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000671 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000672 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000673 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000674 if (CI->isNoopCast(*DL))
675 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000676 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
677 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000678 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000679 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000680 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000681 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
682 // Same as above, but for ConstantExpr instead of Instruction.
683 if (Instruction::isCast(CE->getOpcode())) {
684 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000685 CE->getOperand(0)->getType(), CE->getType(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000686 DL->getIntPtrType(V->getType())))
687 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000688 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000689 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000690 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000691 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000692 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000693 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000694 }
695
696 // As a last resort, try SimplifyInstruction or constant folding.
697 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000698 if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC}))
Chandler Carruth50fee932015-08-06 02:05:46 +0000699 return findValueImpl(W, OffsetOk, Visited);
David Majnemerd536f232016-07-29 03:27:26 +0000700 } else if (auto *C = dyn_cast<Constant>(V)) {
701 if (Value *W = ConstantFoldConstant(C, *DL, TLI))
702 if (W && W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000703 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000704 }
705
706 return V;
707}
708
Dan Gohman98bc4372010-04-08 18:47:09 +0000709//===----------------------------------------------------------------------===//
710// Implement the public interfaces to this file...
711//===----------------------------------------------------------------------===//
712
713FunctionPass *llvm::createLintPass() {
714 return new Lint();
715}
716
717/// lintFunction - Check a function for errors, printing messages on stderr.
718///
719void llvm::lintFunction(const Function &f) {
720 Function &F = const_cast<Function&>(f);
721 assert(!F.isDeclaration() && "Cannot lint external functions");
722
Chandler Carruth30d69c22015-02-13 10:01:29 +0000723 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman98bc4372010-04-08 18:47:09 +0000724 Lint *V = new Lint();
725 FPM.add(V);
726 FPM.run(F);
727}
728
729/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000730///
Dan Gohman084bcb12010-05-26 22:28:53 +0000731void llvm::lintModule(const Module &M) {
Chandler Carruth30d69c22015-02-13 10:01:29 +0000732 legacy::PassManager PM;
Dan Gohman98bc4372010-04-08 18:47:09 +0000733 Lint *V = new Lint();
734 PM.add(V);
735 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000736}