1ae2fe6910f2588941d4ccf89baba82009d4b62b
[oota-llvm.git] / lib / Analysis / PointerTracking.cpp
1 //===- PointerTracking.cpp - Pointer Bounds Tracking ------------*- C++ -*-===//
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 file implements tracking of pointer bounds.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/ConstantFolding.h"
14 #include "llvm/Analysis/Dominators.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/PointerTracking.h"
17 #include "llvm/Analysis/ScalarEvolution.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Value.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/InstIterator.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetData.h"
26
27 namespace llvm {
28 char PointerTracking::ID=0;
29 PointerTracking::PointerTracking() : FunctionPass(&ID) {}
30
31 bool PointerTracking::runOnFunction(Function &F) {
32   predCache.clear();
33   assert(analyzing.empty());
34   FF = &F;
35   TD = getAnalysisIfAvailable<TargetData>();
36   SE = &getAnalysis<ScalarEvolution>();
37   LI = &getAnalysis<LoopInfo>();
38   DT = &getAnalysis<DominatorTree>();
39   return false;
40 }
41
42 void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
43   AU.addRequiredTransitive<DominatorTree>();
44   AU.addRequiredTransitive<LoopInfo>();
45   AU.addRequiredTransitive<ScalarEvolution>();
46   AU.setPreservesAll();
47 }
48
49 bool PointerTracking::doInitialization(Module &M) {
50   const Type *PTy = PointerType::getUnqual(Type::Int8Ty);
51
52   // Find calloc(i64, i64) or calloc(i32, i32).
53   callocFunc = M.getFunction("calloc");
54   if (callocFunc) {
55     const FunctionType *Ty = callocFunc->getFunctionType();
56
57     std::vector<const Type*> args, args2;
58     args.push_back(Type::Int64Ty);
59     args.push_back(Type::Int64Ty);
60     args2.push_back(Type::Int32Ty);
61     args2.push_back(Type::Int32Ty);
62     const FunctionType *Calloc1Type =
63       FunctionType::get(PTy, args, false);
64     const FunctionType *Calloc2Type =
65       FunctionType::get(PTy, args2, false);
66     if (Ty != Calloc1Type && Ty != Calloc2Type)
67       callocFunc = 0; // Give up
68   }
69
70   // Find realloc(i8*, i64) or realloc(i8*, i32).
71   reallocFunc = M.getFunction("realloc");
72   if (reallocFunc) {
73     const FunctionType *Ty = reallocFunc->getFunctionType();
74     std::vector<const Type*> args, args2;
75     args.push_back(PTy);
76     args.push_back(Type::Int64Ty);
77     args2.push_back(PTy);
78     args2.push_back(Type::Int32Ty);
79
80     const FunctionType *Realloc1Type =
81       FunctionType::get(PTy, args, false);
82     const FunctionType *Realloc2Type =
83       FunctionType::get(PTy, args2, false);
84     if (Ty != Realloc1Type && Ty != Realloc2Type)
85       reallocFunc = 0; // Give up
86   }
87   return false;
88 }
89
90 // Calculates the number of elements allocated for pointer P,
91 // the type of the element is stored in Ty.
92 const SCEV *PointerTracking::computeAllocationCount(Value *P,
93                                                     const Type *&Ty) const {
94   Value *V = P->stripPointerCasts();
95   if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
96     Value *arraySize = AI->getArraySize();
97     Ty = AI->getAllocatedType();
98     // arraySize elements of type Ty.
99     return SE->getSCEV(arraySize);
100   }
101
102   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
103     if (GV->hasDefinitiveInitializer()) {
104       Constant *C = GV->getInitializer();
105       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
106         Ty = ATy->getElementType();
107         return SE->getConstant(Type::Int32Ty, ATy->getNumElements());
108       }
109     }
110     Ty = GV->getType();
111     return SE->getConstant(Type::Int32Ty, 1);
112     //TODO: implement more tracking for globals
113   }
114
115   if (CallInst *CI = dyn_cast<CallInst>(V)) {
116     CallSite CS(CI);
117     Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
118     const Loop *L = LI->getLoopFor(CI->getParent());
119     if (F == callocFunc) {
120       Ty = Type::Int8Ty;
121       // calloc allocates arg0*arg1 bytes.
122       return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
123                                                SE->getSCEV(CS.getArgument(1))),
124                                 L);
125     } else if (F == reallocFunc) {
126       Ty = Type::Int8Ty;
127       // realloc allocates arg1 bytes.
128       return SE->getSCEVAtScope(CS.getArgument(1), L);
129     }
130   }
131
132   return SE->getCouldNotCompute();
133 }
134
135 // Calculates the number of elements of type Ty allocated for P.
136 const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
137                                                            const Type *Ty)
138   const {
139     const Type *elementTy;
140     const SCEV *Count = computeAllocationCount(P, elementTy);
141     if (isa<SCEVCouldNotCompute>(Count))
142       return Count;
143     if (elementTy == Ty)
144       return Count;
145
146     if (!TD) // need TargetData from this point forward
147       return SE->getCouldNotCompute();
148
149     uint64_t elementSize = TD->getTypeAllocSize(elementTy);
150     uint64_t wantSize = TD->getTypeAllocSize(Ty);
151     if (elementSize == wantSize)
152       return Count;
153     if (elementSize % wantSize) //fractional counts not possible
154       return SE->getCouldNotCompute();
155     return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
156                                                  elementSize/wantSize));
157 }
158
159 const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
160   // We only deal with pointers.
161   const PointerType *PTy = cast<PointerType>(V->getType());
162   return computeAllocationCountForType(V, PTy->getElementType());
163 }
164
165 const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
166   return computeAllocationCountForType(V, Type::Int8Ty);
167 }
168
169 // Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
170 enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
171                                                    Predicate Pred,
172                                                    const SCEV *A,
173                                                    const SCEV *B) const {
174   if (SE->isLoopGuardedByCond(L, Pred, A, B))
175     return AlwaysTrue;
176   Pred = ICmpInst::getSwappedPredicate(Pred);
177   if (SE->isLoopGuardedByCond(L, Pred, B, A))
178     return AlwaysTrue;
179
180   Pred = ICmpInst::getInversePredicate(Pred);
181   if (SE->isLoopGuardedByCond(L, Pred, B, A))
182     return AlwaysFalse;
183   Pred = ICmpInst::getSwappedPredicate(Pred);
184   if (SE->isLoopGuardedByCond(L, Pred, A, B))
185     return AlwaysTrue;
186   return Unknown;
187 }
188
189 enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
190                                                const SCEV *Limit,
191                                                BasicBlock *BB)
192 {
193   //FIXME: merge implementation
194   return Unknown;
195 }
196
197 void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
198                                        const SCEV *&Limit,
199                                        const SCEV *&Offset) const
200 {
201     Pointer = Pointer->stripPointerCasts();
202     Base = Pointer->getUnderlyingObject();
203     Limit = getAllocationSizeInBytes(Base);
204     if (isa<SCEVCouldNotCompute>(Limit)) {
205       Base = 0;
206       Offset = Limit;
207       return;
208     }
209
210     Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
211     if (isa<SCEVCouldNotCompute>(Offset)) {
212       Base = 0;
213       Limit = Offset;
214     }
215 }
216
217 void PointerTracking::print(raw_ostream &OS, const Module* M) const {
218   // Calling some PT methods may cause caches to be updated, however
219   // this should be safe for the same reason its safe for SCEV.
220   PointerTracking &PT = *const_cast<PointerTracking*>(this);
221   for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
222     if (!isa<PointerType>(I->getType()))
223       continue;
224     Value *Base;
225     const SCEV *Limit, *Offset;
226     getPointerOffset(&*I, Base, Limit, Offset);
227     if (!Base)
228       continue;
229
230     if (Base == &*I) {
231       const SCEV *S = getAllocationElementCount(Base);
232       OS << *Base << " ==> " << *S << " elements, ";
233       OS << *Limit << " bytes allocated\n";
234       continue;
235     }
236     OS << &*I << " -- base: " << *Base;
237     OS << " offset: " << *Offset;
238
239     enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
240     switch (res) {
241     case AlwaysTrue:
242       OS << " always safe\n";
243       break;
244     case AlwaysFalse:
245       OS << " always unsafe\n";
246       break;
247     case Unknown:
248       OS << " <<unknown>>\n";
249       break;
250     }
251   }
252 }
253
254 void PointerTracking::print(std::ostream &o, const Module* M) const {
255   raw_os_ostream OS(o);
256   print(OS, M);
257 }
258
259 static RegisterPass<PointerTracking> X("pointertracking",
260                                        "Track pointer bounds", false, true);
261 }