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/MemoryBuiltins.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 (AllocaInst *AI = dyn_cast<AllocaInst>(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 const Type* AllocTy = getMallocAllocatedType(CI);
106 if (!AllocTy || !arraySize) return SE->getCouldNotCompute();
108 // arraySize elements of type Ty.
109 return SE->getSCEV(arraySize);
112 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
113 if (GV->hasDefinitiveInitializer()) {
114 Constant *C = GV->getInitializer();
115 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
116 Ty = ATy->getElementType();
117 return SE->getConstant(Type::getInt32Ty(P->getContext()),
118 ATy->getNumElements());
122 return SE->getConstant(Type::getInt32Ty(P->getContext()), 1);
123 //TODO: implement more tracking for globals
126 if (CallInst *CI = dyn_cast<CallInst>(V)) {
128 Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
129 const Loop *L = LI->getLoopFor(CI->getParent());
130 if (F == callocFunc) {
131 Ty = Type::getInt8Ty(P->getContext());
132 // calloc allocates arg0*arg1 bytes.
133 return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
134 SE->getSCEV(CS.getArgument(1))),
136 } else if (F == reallocFunc) {
137 Ty = Type::getInt8Ty(P->getContext());
138 // realloc allocates arg1 bytes.
139 return SE->getSCEVAtScope(CS.getArgument(1), L);
143 return SE->getCouldNotCompute();
146 // Calculates the number of elements of type Ty allocated for P.
147 const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
150 const Type *elementTy;
151 const SCEV *Count = computeAllocationCount(P, elementTy);
152 if (isa<SCEVCouldNotCompute>(Count))
157 if (!TD) // need TargetData from this point forward
158 return SE->getCouldNotCompute();
160 uint64_t elementSize = TD->getTypeAllocSize(elementTy);
161 uint64_t wantSize = TD->getTypeAllocSize(Ty);
162 if (elementSize == wantSize)
164 if (elementSize % wantSize) //fractional counts not possible
165 return SE->getCouldNotCompute();
166 return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
167 elementSize/wantSize));
170 const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
171 // We only deal with pointers.
172 const PointerType *PTy = cast<PointerType>(V->getType());
173 return computeAllocationCountForType(V, PTy->getElementType());
176 const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
177 return computeAllocationCountForType(V, Type::getInt8Ty(V->getContext()));
180 // Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
181 enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
184 const SCEV *B) const {
185 if (SE->isLoopGuardedByCond(L, Pred, A, B))
187 Pred = ICmpInst::getSwappedPredicate(Pred);
188 if (SE->isLoopGuardedByCond(L, Pred, B, A))
191 Pred = ICmpInst::getInversePredicate(Pred);
192 if (SE->isLoopGuardedByCond(L, Pred, B, A))
194 Pred = ICmpInst::getSwappedPredicate(Pred);
195 if (SE->isLoopGuardedByCond(L, Pred, A, B))
200 enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
204 //FIXME: merge implementation
208 void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
210 const SCEV *&Offset) const
212 Pointer = Pointer->stripPointerCasts();
213 Base = Pointer->getUnderlyingObject();
214 Limit = getAllocationSizeInBytes(Base);
215 if (isa<SCEVCouldNotCompute>(Limit)) {
221 Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
222 if (isa<SCEVCouldNotCompute>(Offset)) {
228 void PointerTracking::print(raw_ostream &OS, const Module* M) const {
229 // Calling some PT methods may cause caches to be updated, however
230 // this should be safe for the same reason its safe for SCEV.
231 PointerTracking &PT = *const_cast<PointerTracking*>(this);
232 for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
233 if (!isa<PointerType>(I->getType()))
236 const SCEV *Limit, *Offset;
237 getPointerOffset(&*I, Base, Limit, Offset);
242 const SCEV *S = getAllocationElementCount(Base);
243 OS << *Base << " ==> " << *S << " elements, ";
244 OS << *Limit << " bytes allocated\n";
247 OS << &*I << " -- base: " << *Base;
248 OS << " offset: " << *Offset;
250 enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
253 OS << " always safe\n";
256 OS << " always unsafe\n";
259 OS << " <<unknown>>\n";
265 static RegisterPass<PointerTracking> X("pointertracking",
266 "Track pointer bounds", false, true);