1 //===- PointerTracking.cpp - Pointer Bounds Tracking ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements tracking of pointer bounds.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/ConstantFolding.h"
14 #include "llvm/Analysis/Dominators.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/MallocHelper.h"
17 #include "llvm/Analysis/PointerTracking.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Module.h"
22 #include "llvm/Value.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetData.h"
29 char PointerTracking::ID = 0;
30 PointerTracking::PointerTracking() : FunctionPass(&ID) {}
32 bool PointerTracking::runOnFunction(Function &F) {
34 assert(analyzing.empty());
36 TD = getAnalysisIfAvailable<TargetData>();
37 SE = &getAnalysis<ScalarEvolution>();
38 LI = &getAnalysis<LoopInfo>();
39 DT = &getAnalysis<DominatorTree>();
43 void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequiredTransitive<DominatorTree>();
45 AU.addRequiredTransitive<LoopInfo>();
46 AU.addRequiredTransitive<ScalarEvolution>();
50 bool PointerTracking::doInitialization(Module &M) {
51 const Type *PTy = Type::getInt8PtrTy(M.getContext());
53 // Find calloc(i64, i64) or calloc(i32, i32).
54 callocFunc = M.getFunction("calloc");
56 const FunctionType *Ty = callocFunc->getFunctionType();
58 std::vector<const Type*> args, args2;
59 args.push_back(Type::getInt64Ty(M.getContext()));
60 args.push_back(Type::getInt64Ty(M.getContext()));
61 args2.push_back(Type::getInt32Ty(M.getContext()));
62 args2.push_back(Type::getInt32Ty(M.getContext()));
63 const FunctionType *Calloc1Type =
64 FunctionType::get(PTy, args, false);
65 const FunctionType *Calloc2Type =
66 FunctionType::get(PTy, args2, false);
67 if (Ty != Calloc1Type && Ty != Calloc2Type)
68 callocFunc = 0; // Give up
71 // Find realloc(i8*, i64) or realloc(i8*, i32).
72 reallocFunc = M.getFunction("realloc");
74 const FunctionType *Ty = reallocFunc->getFunctionType();
75 std::vector<const Type*> args, args2;
77 args.push_back(Type::getInt64Ty(M.getContext()));
79 args2.push_back(Type::getInt32Ty(M.getContext()));
81 const FunctionType *Realloc1Type =
82 FunctionType::get(PTy, args, false);
83 const FunctionType *Realloc2Type =
84 FunctionType::get(PTy, args2, false);
85 if (Ty != Realloc1Type && Ty != Realloc2Type)
86 reallocFunc = 0; // Give up
91 // Calculates the number of elements allocated for pointer P,
92 // the type of the element is stored in Ty.
93 const SCEV *PointerTracking::computeAllocationCount(Value *P,
94 const Type *&Ty) const {
95 Value *V = P->stripPointerCasts();
96 if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
97 Value *arraySize = AI->getArraySize();
98 Ty = AI->getAllocatedType();
99 // arraySize elements of type Ty.
100 return SE->getSCEV(arraySize);
103 if (CallInst *CI = extractMallocCall(V)) {
104 Value *arraySize = getMallocArraySize(CI, P->getContext(), TD);
105 Ty = getMallocAllocatedType(CI);
106 if (!Ty || !arraySize) return SE->getCouldNotCompute();
107 // arraySize elements of type Ty.
108 return SE->getSCEV(arraySize);
111 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
112 if (GV->hasDefinitiveInitializer()) {
113 Constant *C = GV->getInitializer();
114 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
115 Ty = ATy->getElementType();
116 return SE->getConstant(Type::getInt32Ty(P->getContext()),
117 ATy->getNumElements());
121 return SE->getConstant(Type::getInt32Ty(P->getContext()), 1);
122 //TODO: implement more tracking for globals
125 if (CallInst *CI = dyn_cast<CallInst>(V)) {
127 Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
128 const Loop *L = LI->getLoopFor(CI->getParent());
129 if (F == callocFunc) {
130 Ty = Type::getInt8Ty(P->getContext());
131 // calloc allocates arg0*arg1 bytes.
132 return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
133 SE->getSCEV(CS.getArgument(1))),
135 } else if (F == reallocFunc) {
136 Ty = Type::getInt8Ty(P->getContext());
137 // realloc allocates arg1 bytes.
138 return SE->getSCEVAtScope(CS.getArgument(1), L);
142 return SE->getCouldNotCompute();
145 // Calculates the number of elements of type Ty allocated for P.
146 const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
149 const Type *elementTy;
150 const SCEV *Count = computeAllocationCount(P, elementTy);
151 if (isa<SCEVCouldNotCompute>(Count))
156 if (!TD) // need TargetData from this point forward
157 return SE->getCouldNotCompute();
159 uint64_t elementSize = TD->getTypeAllocSize(elementTy);
160 uint64_t wantSize = TD->getTypeAllocSize(Ty);
161 if (elementSize == wantSize)
163 if (elementSize % wantSize) //fractional counts not possible
164 return SE->getCouldNotCompute();
165 return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
166 elementSize/wantSize));
169 const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
170 // We only deal with pointers.
171 const PointerType *PTy = cast<PointerType>(V->getType());
172 return computeAllocationCountForType(V, PTy->getElementType());
175 const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
176 return computeAllocationCountForType(V, Type::getInt8Ty(V->getContext()));
179 // Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
180 enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
183 const SCEV *B) const {
184 if (SE->isLoopGuardedByCond(L, Pred, A, B))
186 Pred = ICmpInst::getSwappedPredicate(Pred);
187 if (SE->isLoopGuardedByCond(L, Pred, B, A))
190 Pred = ICmpInst::getInversePredicate(Pred);
191 if (SE->isLoopGuardedByCond(L, Pred, B, A))
193 Pred = ICmpInst::getSwappedPredicate(Pred);
194 if (SE->isLoopGuardedByCond(L, Pred, A, B))
199 enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
203 //FIXME: merge implementation
207 void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
209 const SCEV *&Offset) const
211 Pointer = Pointer->stripPointerCasts();
212 Base = Pointer->getUnderlyingObject();
213 Limit = getAllocationSizeInBytes(Base);
214 if (isa<SCEVCouldNotCompute>(Limit)) {
220 Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
221 if (isa<SCEVCouldNotCompute>(Offset)) {
227 void PointerTracking::print(raw_ostream &OS, const Module* M) const {
228 // Calling some PT methods may cause caches to be updated, however
229 // this should be safe for the same reason its safe for SCEV.
230 PointerTracking &PT = *const_cast<PointerTracking*>(this);
231 for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
232 if (!isa<PointerType>(I->getType()))
235 const SCEV *Limit, *Offset;
236 getPointerOffset(&*I, Base, Limit, Offset);
241 const SCEV *S = getAllocationElementCount(Base);
242 OS << *Base << " ==> " << *S << " elements, ";
243 OS << *Limit << " bytes allocated\n";
246 OS << &*I << " -- base: " << *Base;
247 OS << " offset: " << *Offset;
249 enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
252 OS << " always safe\n";
255 OS << " always unsafe\n";
258 OS << " <<unknown>>\n";
264 static RegisterPass<PointerTracking> X("pointertracking",
265 "Track pointer bounds", false, true);