1 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
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 defines the default implementation of the Alias Analysis interface
11 // that simply implements a few identities (two different globals cannot alias,
12 // etc), but otherwise does no analysis.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Operator.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include <algorithm>
36 using namespace llvm;
37 
38 //===----------------------------------------------------------------------===//
39 // Useful predicates
40 //===----------------------------------------------------------------------===//
41 
42 /// isKnownNonNull - Return true if we know that the specified value is never
43 /// null.
isKnownNonNull(const Value * V)44 static bool isKnownNonNull(const Value *V) {
45   // Alloca never returns null, malloc might.
46   if (isa<AllocaInst>(V)) return true;
47 
48   // A byval argument is never null.
49   if (const Argument *A = dyn_cast<Argument>(V))
50     return A->hasByValAttr();
51 
52   // Global values are not null unless extern weak.
53   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
54     return !GV->hasExternalWeakLinkage();
55   return false;
56 }
57 
58 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
59 /// object that never escapes from the function.
isNonEscapingLocalObject(const Value * V)60 static bool isNonEscapingLocalObject(const Value *V) {
61   // If this is a local allocation, check to see if it escapes.
62   if (isa<AllocaInst>(V) || isNoAliasCall(V))
63     // Set StoreCaptures to True so that we can assume in our callers that the
64     // pointer is not the result of a load instruction. Currently
65     // PointerMayBeCaptured doesn't have any special analysis for the
66     // StoreCaptures=false case; if it did, our callers could be refined to be
67     // more precise.
68     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
69 
70   // If this is an argument that corresponds to a byval or noalias argument,
71   // then it has not escaped before entering the function.  Check if it escapes
72   // inside the function.
73   if (const Argument *A = dyn_cast<Argument>(V))
74     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
75       // Don't bother analyzing arguments already known not to escape.
76       if (A->hasNoCaptureAttr())
77         return true;
78       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
79     }
80   return false;
81 }
82 
83 /// isEscapeSource - Return true if the pointer is one which would have
84 /// been considered an escape by isNonEscapingLocalObject.
isEscapeSource(const Value * V)85 static bool isEscapeSource(const Value *V) {
86   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
87     return true;
88 
89   // The load case works because isNonEscapingLocalObject considers all
90   // stores to be escapes (it passes true for the StoreCaptures argument
91   // to PointerMayBeCaptured).
92   if (isa<LoadInst>(V))
93     return true;
94 
95   return false;
96 }
97 
98 /// isObjectSmallerThan - Return true if we can prove that the object specified
99 /// by V is smaller than Size.
isObjectSmallerThan(const Value * V,unsigned Size,const TargetData & TD)100 static bool isObjectSmallerThan(const Value *V, unsigned Size,
101                                 const TargetData &TD) {
102   const Type *AccessTy;
103   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
104     AccessTy = GV->getType()->getElementType();
105   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
106     if (!AI->isArrayAllocation())
107       AccessTy = AI->getType()->getElementType();
108     else
109       return false;
110   } else if (const CallInst* CI = extractMallocCall(V)) {
111     if (!isArrayMalloc(V, &TD))
112       // The size is the argument to the malloc call.
113       if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getArgOperand(0)))
114         return (C->getZExtValue() < Size);
115     return false;
116   } else if (const Argument *A = dyn_cast<Argument>(V)) {
117     if (A->hasByValAttr())
118       AccessTy = cast<PointerType>(A->getType())->getElementType();
119     else
120       return false;
121   } else {
122     return false;
123   }
124 
125   if (AccessTy->isSized())
126     return TD.getTypeAllocSize(AccessTy) < Size;
127   return false;
128 }
129 
130 //===----------------------------------------------------------------------===//
131 // NoAA Pass
132 //===----------------------------------------------------------------------===//
133 
134 namespace {
135   /// NoAA - This class implements the -no-aa pass, which always returns "I
136   /// don't know" for alias queries.  NoAA is unlike other alias analysis
137   /// implementations, in that it does not chain to a previous analysis.  As
138   /// such it doesn't follow many of the rules that other alias analyses must.
139   ///
140   struct NoAA : public ImmutablePass, public AliasAnalysis {
141     static char ID; // Class identification, replacement for typeinfo
NoAA__anonbfd7c63f0111::NoAA142     NoAA() : ImmutablePass(ID) {}
NoAA__anonbfd7c63f0111::NoAA143     explicit NoAA(char &PID) : ImmutablePass(PID) { }
144 
getAnalysisUsage__anonbfd7c63f0111::NoAA145     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146     }
147 
initializePass__anonbfd7c63f0111::NoAA148     virtual void initializePass() {
149       TD = getAnalysisIfAvailable<TargetData>();
150     }
151 
alias__anonbfd7c63f0111::NoAA152     virtual AliasResult alias(const Value *V1, unsigned V1Size,
153                               const Value *V2, unsigned V2Size) {
154       return MayAlias;
155     }
156 
getModRefBehavior__anonbfd7c63f0111::NoAA157     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
158       return UnknownModRefBehavior;
159     }
getModRefBehavior__anonbfd7c63f0111::NoAA160     virtual ModRefBehavior getModRefBehavior(const Function *F) {
161       return UnknownModRefBehavior;
162     }
163 
pointsToConstantMemory__anonbfd7c63f0111::NoAA164     virtual bool pointsToConstantMemory(const Value *P) { return false; }
getModRefInfo__anonbfd7c63f0111::NoAA165     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
166                                        const Value *P, unsigned Size) {
167       return ModRef;
168     }
getModRefInfo__anonbfd7c63f0111::NoAA169     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
170                                        ImmutableCallSite CS2) {
171       return ModRef;
172     }
173 
deleteValue__anonbfd7c63f0111::NoAA174     virtual void deleteValue(Value *V) {}
copyValue__anonbfd7c63f0111::NoAA175     virtual void copyValue(Value *From, Value *To) {}
176 
177     /// getAdjustedAnalysisPointer - This method is used when a pass implements
178     /// an analysis interface through multiple inheritance.  If needed, it
179     /// should override this to adjust the this pointer as needed for the
180     /// specified pass info.
getAdjustedAnalysisPointer__anonbfd7c63f0111::NoAA181     virtual void *getAdjustedAnalysisPointer(const void *ID) {
182       if (ID == &AliasAnalysis::ID)
183         return (AliasAnalysis*)this;
184       return this;
185     }
186   };
187 }  // End of anonymous namespace
188 
189 // Register this pass...
190 char NoAA::ID = 0;
191 INITIALIZE_AG_PASS(NoAA, AliasAnalysis, "no-aa",
192                    "No Alias Analysis (always returns 'may' alias)",
193                    true, true, false);
194 
createNoAAPass()195 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
196 
197 //===----------------------------------------------------------------------===//
198 // GetElementPtr Instruction Decomposition and Analysis
199 //===----------------------------------------------------------------------===//
200 
201 namespace {
202   enum ExtensionKind {
203     EK_NotExtended,
204     EK_SignExt,
205     EK_ZeroExt
206   };
207 
208   struct VariableGEPIndex {
209     const Value *V;
210     ExtensionKind Extension;
211     int64_t Scale;
212   };
213 }
214 
215 
216 /// GetLinearExpression - Analyze the specified value as a linear expression:
217 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
218 /// values as APInts and return V as a Value*, and return whether we looked
219 /// through any sign or zero extends.  The incoming Value is known to have
220 /// IntegerType and it may already be sign or zero extended.
221 ///
222 /// Note that this looks through extends, so the high bits may not be
223 /// represented in the result.
GetLinearExpression(Value * V,APInt & Scale,APInt & Offset,ExtensionKind & Extension,const TargetData & TD,unsigned Depth)224 static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
225                                   ExtensionKind &Extension,
226                                   const TargetData &TD, unsigned Depth) {
227   assert(V->getType()->isIntegerTy() && "Not an integer value");
228 
229   // Limit our recursion depth.
230   if (Depth == 6) {
231     Scale = 1;
232     Offset = 0;
233     return V;
234   }
235 
236   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
237     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
238       switch (BOp->getOpcode()) {
239       default: break;
240       case Instruction::Or:
241         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
242         // analyze it.
243         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &TD))
244           break;
245         // FALL THROUGH.
246       case Instruction::Add:
247         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
248                                 TD, Depth+1);
249         Offset += RHSC->getValue();
250         return V;
251       case Instruction::Mul:
252         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
253                                 TD, Depth+1);
254         Offset *= RHSC->getValue();
255         Scale *= RHSC->getValue();
256         return V;
257       case Instruction::Shl:
258         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
259                                 TD, Depth+1);
260         Offset <<= RHSC->getValue().getLimitedValue();
261         Scale <<= RHSC->getValue().getLimitedValue();
262         return V;
263       }
264     }
265   }
266 
267   // Since GEP indices are sign extended anyway, we don't care about the high
268   // bits of a sign or zero extended value - just scales and offsets.  The
269   // extensions have to be consistent though.
270   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
271       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
272     Value *CastOp = cast<CastInst>(V)->getOperand(0);
273     unsigned OldWidth = Scale.getBitWidth();
274     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
275     Scale.trunc(SmallWidth);
276     Offset.trunc(SmallWidth);
277     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
278 
279     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
280                                         TD, Depth+1);
281     Scale.zext(OldWidth);
282     Offset.zext(OldWidth);
283 
284     return Result;
285   }
286 
287   Scale = 1;
288   Offset = 0;
289   return V;
290 }
291 
292 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
293 /// into a base pointer with a constant offset and a number of scaled symbolic
294 /// offsets.
295 ///
296 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
297 /// the VarIndices vector) are Value*'s that are known to be scaled by the
298 /// specified amount, but which may have other unrepresented high bits. As such,
299 /// the gep cannot necessarily be reconstructed from its decomposed form.
300 ///
301 /// When TargetData is around, this function is capable of analyzing everything
302 /// that Value::getUnderlyingObject() can look through.  When not, it just looks
303 /// through pointer casts.
304 ///
305 static const Value *
DecomposeGEPExpression(const Value * V,int64_t & BaseOffs,SmallVectorImpl<VariableGEPIndex> & VarIndices,const TargetData * TD)306 DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
307                        SmallVectorImpl<VariableGEPIndex> &VarIndices,
308                        const TargetData *TD) {
309   // Limit recursion depth to limit compile time in crazy cases.
310   unsigned MaxLookup = 6;
311 
312   BaseOffs = 0;
313   do {
314     // See if this is a bitcast or GEP.
315     const Operator *Op = dyn_cast<Operator>(V);
316     if (Op == 0) {
317       // The only non-operator case we can handle are GlobalAliases.
318       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
319         if (!GA->mayBeOverridden()) {
320           V = GA->getAliasee();
321           continue;
322         }
323       }
324       return V;
325     }
326 
327     if (Op->getOpcode() == Instruction::BitCast) {
328       V = Op->getOperand(0);
329       continue;
330     }
331 
332     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
333     if (GEPOp == 0)
334       return V;
335 
336     // Don't attempt to analyze GEPs over unsized objects.
337     if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
338         ->getElementType()->isSized())
339       return V;
340 
341     // If we are lacking TargetData information, we can't compute the offets of
342     // elements computed by GEPs.  However, we can handle bitcast equivalent
343     // GEPs.
344     if (TD == 0) {
345       if (!GEPOp->hasAllZeroIndices())
346         return V;
347       V = GEPOp->getOperand(0);
348       continue;
349     }
350 
351     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
352     gep_type_iterator GTI = gep_type_begin(GEPOp);
353     for (User::const_op_iterator I = GEPOp->op_begin()+1,
354          E = GEPOp->op_end(); I != E; ++I) {
355       Value *Index = *I;
356       // Compute the (potentially symbolic) offset in bytes for this index.
357       if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
358         // For a struct, add the member offset.
359         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
360         if (FieldNo == 0) continue;
361 
362         BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
363         continue;
364       }
365 
366       // For an array/pointer, add the element offset, explicitly scaled.
367       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
368         if (CIdx->isZero()) continue;
369         BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
370         continue;
371       }
372 
373       uint64_t Scale = TD->getTypeAllocSize(*GTI);
374       ExtensionKind Extension = EK_NotExtended;
375 
376       // If the integer type is smaller than the pointer size, it is implicitly
377       // sign extended to pointer size.
378       unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
379       if (TD->getPointerSizeInBits() > Width)
380         Extension = EK_SignExt;
381 
382       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
383       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
384       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
385                                   *TD, 0);
386 
387       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
388       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
389       BaseOffs += IndexOffset.getZExtValue()*Scale;
390       Scale *= IndexScale.getZExtValue();
391 
392 
393       // If we already had an occurrance of this index variable, merge this
394       // scale into it.  For example, we want to handle:
395       //   A[x][x] -> x*16 + x*4 -> x*20
396       // This also ensures that 'x' only appears in the index list once.
397       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
398         if (VarIndices[i].V == Index &&
399             VarIndices[i].Extension == Extension) {
400           Scale += VarIndices[i].Scale;
401           VarIndices.erase(VarIndices.begin()+i);
402           break;
403         }
404       }
405 
406       // Make sure that we have a scale that makes sense for this target's
407       // pointer size.
408       if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
409         Scale <<= ShiftBits;
410         Scale >>= ShiftBits;
411       }
412 
413       if (Scale) {
414         VariableGEPIndex Entry = {Index, Extension,
415 		                  static_cast<int64_t>(Scale)};
416         VarIndices.push_back(Entry);
417       }
418     }
419 
420     // Analyze the base pointer next.
421     V = GEPOp->getOperand(0);
422   } while (--MaxLookup);
423 
424   // If the chain of expressions is too deep, just return early.
425   return V;
426 }
427 
428 /// GetIndexDifference - Dest and Src are the variable indices from two
429 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
430 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
431 /// difference between the two pointers.
GetIndexDifference(SmallVectorImpl<VariableGEPIndex> & Dest,const SmallVectorImpl<VariableGEPIndex> & Src)432 static void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
433                                const SmallVectorImpl<VariableGEPIndex> &Src) {
434   if (Src.empty()) return;
435 
436   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
437     const Value *V = Src[i].V;
438     ExtensionKind Extension = Src[i].Extension;
439     int64_t Scale = Src[i].Scale;
440 
441     // Find V in Dest.  This is N^2, but pointer indices almost never have more
442     // than a few variable indexes.
443     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
444       if (Dest[j].V != V || Dest[j].Extension != Extension) continue;
445 
446       // If we found it, subtract off Scale V's from the entry in Dest.  If it
447       // goes to zero, remove the entry.
448       if (Dest[j].Scale != Scale)
449         Dest[j].Scale -= Scale;
450       else
451         Dest.erase(Dest.begin()+j);
452       Scale = 0;
453       break;
454     }
455 
456     // If we didn't consume this entry, add it to the end of the Dest list.
457     if (Scale) {
458       VariableGEPIndex Entry = { V, Extension, -Scale };
459       Dest.push_back(Entry);
460     }
461   }
462 }
463 
464 //===----------------------------------------------------------------------===//
465 // BasicAliasAnalysis Pass
466 //===----------------------------------------------------------------------===//
467 
468 #ifndef NDEBUG
getParent(const Value * V)469 static const Function *getParent(const Value *V) {
470   if (const Instruction *inst = dyn_cast<Instruction>(V))
471     return inst->getParent()->getParent();
472 
473   if (const Argument *arg = dyn_cast<Argument>(V))
474     return arg->getParent();
475 
476   return NULL;
477 }
478 
notDifferentParent(const Value * O1,const Value * O2)479 static bool notDifferentParent(const Value *O1, const Value *O2) {
480 
481   const Function *F1 = getParent(O1);
482   const Function *F2 = getParent(O2);
483 
484   return !F1 || !F2 || F1 == F2;
485 }
486 #endif
487 
488 namespace {
489   /// BasicAliasAnalysis - This is the default alias analysis implementation.
490   /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
491   /// derives from the NoAA class.
492   struct BasicAliasAnalysis : public NoAA {
493     static char ID; // Class identification, replacement for typeinfo
BasicAliasAnalysis__anonbfd7c63f0311::BasicAliasAnalysis494     BasicAliasAnalysis() : NoAA(ID) {}
495 
alias__anonbfd7c63f0311::BasicAliasAnalysis496     virtual AliasResult alias(const Value *V1, unsigned V1Size,
497                               const Value *V2, unsigned V2Size) {
498       assert(Visited.empty() && "Visited must be cleared after use!");
499       assert(notDifferentParent(V1, V2) &&
500              "BasicAliasAnalysis doesn't support interprocedural queries.");
501       AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
502       Visited.clear();
503       return Alias;
504     }
505 
506     virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
507                                        const Value *P, unsigned Size);
508 
getModRefInfo__anonbfd7c63f0311::BasicAliasAnalysis509     virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
510                                        ImmutableCallSite CS2) {
511       // The AliasAnalysis base class has some smarts, lets use them.
512       return AliasAnalysis::getModRefInfo(CS1, CS2);
513     }
514 
515     /// pointsToConstantMemory - Chase pointers until we find a (constant
516     /// global) or not.
517     virtual bool pointsToConstantMemory(const Value *P);
518 
519     /// getModRefBehavior - Return the behavior when calling the given
520     /// call site.
521     virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
522 
523     /// getModRefBehavior - Return the behavior when calling the given function.
524     /// For use when the call site is not known.
525     virtual ModRefBehavior getModRefBehavior(const Function *F);
526 
527     /// getAdjustedAnalysisPointer - This method is used when a pass implements
528     /// an analysis interface through multiple inheritance.  If needed, it
529     /// should override this to adjust the this pointer as needed for the
530     /// specified pass info.
getAdjustedAnalysisPointer__anonbfd7c63f0311::BasicAliasAnalysis531     virtual void *getAdjustedAnalysisPointer(const void *ID) {
532       if (ID == &AliasAnalysis::ID)
533         return (AliasAnalysis*)this;
534       return this;
535     }
536 
537   private:
538     // Visited - Track instructions visited by a aliasPHI, aliasSelect(), and aliasGEP().
539     SmallPtrSet<const Value*, 16> Visited;
540 
541     // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
542     // instruction against another.
543     AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
544                          const Value *V2, unsigned V2Size,
545                          const Value *UnderlyingV1, const Value *UnderlyingV2);
546 
547     // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
548     // instruction against another.
549     AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
550                          const Value *V2, unsigned V2Size);
551 
552     /// aliasSelect - Disambiguate a Select instruction against another value.
553     AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
554                             const Value *V2, unsigned V2Size);
555 
556     AliasResult aliasCheck(const Value *V1, unsigned V1Size,
557                            const Value *V2, unsigned V2Size);
558   };
559 }  // End of anonymous namespace
560 
561 // Register this pass...
562 char BasicAliasAnalysis::ID = 0;
563 INITIALIZE_AG_PASS(BasicAliasAnalysis, AliasAnalysis, "basicaa",
564                    "Basic Alias Analysis (default AA impl)",
565                    false, true, true);
566 
createBasicAliasAnalysisPass()567 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
568   return new BasicAliasAnalysis();
569 }
570 
571 
572 /// pointsToConstantMemory - Chase pointers until we find a (constant
573 /// global) or not.
pointsToConstantMemory(const Value * P)574 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
575   if (const GlobalVariable *GV =
576         dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
577     // Note: this doesn't require GV to be "ODR" because it isn't legal for a
578     // global to be marked constant in some modules and non-constant in others.
579     // GV may even be a declaration, not a definition.
580     return GV->isConstant();
581 
582   return NoAA::pointsToConstantMemory(P);
583 }
584 
585 /// getModRefBehavior - Return the behavior when calling the given call site.
586 AliasAnalysis::ModRefBehavior
getModRefBehavior(ImmutableCallSite CS)587 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
588   if (CS.doesNotAccessMemory())
589     // Can't do better than this.
590     return DoesNotAccessMemory;
591 
592   ModRefBehavior Min = UnknownModRefBehavior;
593 
594   // If the callsite knows it only reads memory, don't return worse
595   // than that.
596   if (CS.onlyReadsMemory())
597     Min = OnlyReadsMemory;
598 
599   // The AliasAnalysis base class has some smarts, lets use them.
600   return std::min(AliasAnalysis::getModRefBehavior(CS), Min);
601 }
602 
603 /// getModRefBehavior - Return the behavior when calling the given function.
604 /// For use when the call site is not known.
605 AliasAnalysis::ModRefBehavior
getModRefBehavior(const Function * F)606 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
607   if (F->doesNotAccessMemory())
608     // Can't do better than this.
609     return DoesNotAccessMemory;
610   if (F->onlyReadsMemory())
611     return OnlyReadsMemory;
612   if (unsigned id = F->getIntrinsicID())
613     return getIntrinsicModRefBehavior(id);
614 
615   return NoAA::getModRefBehavior(F);
616 }
617 
618 /// getModRefInfo - Check to see if the specified callsite can clobber the
619 /// specified memory object.  Since we only look at local properties of this
620 /// function, we really can't say much about this query.  We do, however, use
621 /// simple "address taken" analysis on local objects.
622 AliasAnalysis::ModRefResult
getModRefInfo(ImmutableCallSite CS,const Value * P,unsigned Size)623 BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
624                                   const Value *P, unsigned Size) {
625   assert(notDifferentParent(CS.getInstruction(), P) &&
626          "AliasAnalysis query involving multiple functions!");
627 
628   const Value *Object = P->getUnderlyingObject();
629 
630   // If this is a tail call and P points to a stack location, we know that
631   // the tail call cannot access or modify the local stack.
632   // We cannot exclude byval arguments here; these belong to the caller of
633   // the current function not to the current function, and a tail callee
634   // may reference them.
635   if (isa<AllocaInst>(Object))
636     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
637       if (CI->isTailCall())
638         return NoModRef;
639 
640   // If the pointer is to a locally allocated object that does not escape,
641   // then the call can not mod/ref the pointer unless the call takes the pointer
642   // as an argument, and itself doesn't capture it.
643   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
644       isNonEscapingLocalObject(Object)) {
645     bool PassedAsArg = false;
646     unsigned ArgNo = 0;
647     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
648          CI != CE; ++CI, ++ArgNo) {
649       // Only look at the no-capture pointer arguments.
650       if (!(*CI)->getType()->isPointerTy() ||
651           !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
652         continue;
653 
654       // If  this is a no-capture pointer argument, see if we can tell that it
655       // is impossible to alias the pointer we're checking.  If not, we have to
656       // assume that the call could touch the pointer, even though it doesn't
657       // escape.
658       if (!isNoAlias(cast<Value>(CI), UnknownSize, P, UnknownSize)) {
659         PassedAsArg = true;
660         break;
661       }
662     }
663 
664     if (!PassedAsArg)
665       return NoModRef;
666   }
667 
668   // Finally, handle specific knowledge of intrinsics.
669   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
670   if (II != 0)
671     switch (II->getIntrinsicID()) {
672     default: break;
673     case Intrinsic::memcpy:
674     case Intrinsic::memmove: {
675       unsigned Len = UnknownSize;
676       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
677         Len = LenCI->getZExtValue();
678       Value *Dest = II->getArgOperand(0);
679       Value *Src = II->getArgOperand(1);
680       if (isNoAlias(Dest, Len, P, Size)) {
681         if (isNoAlias(Src, Len, P, Size))
682           return NoModRef;
683         return Ref;
684       }
685       break;
686     }
687     case Intrinsic::memset:
688       // Since memset is 'accesses arguments' only, the AliasAnalysis base class
689       // will handle it for the variable length case.
690       if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
691         unsigned Len = LenCI->getZExtValue();
692         Value *Dest = II->getArgOperand(0);
693         if (isNoAlias(Dest, Len, P, Size))
694           return NoModRef;
695       }
696       break;
697     case Intrinsic::atomic_cmp_swap:
698     case Intrinsic::atomic_swap:
699     case Intrinsic::atomic_load_add:
700     case Intrinsic::atomic_load_sub:
701     case Intrinsic::atomic_load_and:
702     case Intrinsic::atomic_load_nand:
703     case Intrinsic::atomic_load_or:
704     case Intrinsic::atomic_load_xor:
705     case Intrinsic::atomic_load_max:
706     case Intrinsic::atomic_load_min:
707     case Intrinsic::atomic_load_umax:
708     case Intrinsic::atomic_load_umin:
709       if (TD) {
710         Value *Op1 = II->getArgOperand(0);
711         unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
712         if (isNoAlias(Op1, Op1Size, P, Size))
713           return NoModRef;
714       }
715       break;
716     case Intrinsic::lifetime_start:
717     case Intrinsic::lifetime_end:
718     case Intrinsic::invariant_start: {
719       unsigned PtrSize =
720         cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
721       if (isNoAlias(II->getArgOperand(1), PtrSize, P, Size))
722         return NoModRef;
723       break;
724     }
725     case Intrinsic::invariant_end: {
726       unsigned PtrSize =
727         cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
728       if (isNoAlias(II->getArgOperand(2), PtrSize, P, Size))
729         return NoModRef;
730       break;
731     }
732     }
733 
734   // The AliasAnalysis base class has some smarts, lets use them.
735   return AliasAnalysis::getModRefInfo(CS, P, Size);
736 }
737 
738 
739 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
740 /// against another pointer.  We know that V1 is a GEP, but we don't know
741 /// anything about V2.  UnderlyingV1 is GEP1->getUnderlyingObject(),
742 /// UnderlyingV2 is the same for V2.
743 ///
744 AliasAnalysis::AliasResult
aliasGEP(const GEPOperator * GEP1,unsigned V1Size,const Value * V2,unsigned V2Size,const Value * UnderlyingV1,const Value * UnderlyingV2)745 BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
746                              const Value *V2, unsigned V2Size,
747                              const Value *UnderlyingV1,
748                              const Value *UnderlyingV2) {
749   // If this GEP has been visited before, we're on a use-def cycle.
750   // Such cycles are only valid when PHI nodes are involved or in unreachable
751   // code. The visitPHI function catches cycles containing PHIs, but there
752   // could still be a cycle without PHIs in unreachable code.
753   if (!Visited.insert(GEP1))
754     return MayAlias;
755 
756   int64_t GEP1BaseOffset;
757   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
758 
759   // If we have two gep instructions with must-alias'ing base pointers, figure
760   // out if the indexes to the GEP tell us anything about the derived pointer.
761   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
762     // Do the base pointers alias?
763     AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize,
764                                        UnderlyingV2, UnknownSize);
765 
766     // If we get a No or May, then return it immediately, no amount of analysis
767     // will improve this situation.
768     if (BaseAlias != MustAlias) return BaseAlias;
769 
770     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
771     // exactly, see if the computed offset from the common pointer tells us
772     // about the relation of the resulting pointer.
773     const Value *GEP1BasePtr =
774       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
775 
776     int64_t GEP2BaseOffset;
777     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
778     const Value *GEP2BasePtr =
779       DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
780 
781     // If DecomposeGEPExpression isn't able to look all the way through the
782     // addressing operation, we must not have TD and this is too complex for us
783     // to handle without it.
784     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
785       assert(TD == 0 &&
786              "DecomposeGEPExpression and getUnderlyingObject disagree!");
787       return MayAlias;
788     }
789 
790     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
791     // symbolic difference.
792     GEP1BaseOffset -= GEP2BaseOffset;
793     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
794 
795   } else {
796     // Check to see if these two pointers are related by the getelementptr
797     // instruction.  If one pointer is a GEP with a non-zero index of the other
798     // pointer, we know they cannot alias.
799 
800     // If both accesses are unknown size, we can't do anything useful here.
801     if (V1Size == UnknownSize && V2Size == UnknownSize)
802       return MayAlias;
803 
804     AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, V2, V2Size);
805     if (R != MustAlias)
806       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
807       // If V2 is known not to alias GEP base pointer, then the two values
808       // cannot alias per GEP semantics: "A pointer value formed from a
809       // getelementptr instruction is associated with the addresses associated
810       // with the first operand of the getelementptr".
811       return R;
812 
813     const Value *GEP1BasePtr =
814       DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
815 
816     // If DecomposeGEPExpression isn't able to look all the way through the
817     // addressing operation, we must not have TD and this is too complex for us
818     // to handle without it.
819     if (GEP1BasePtr != UnderlyingV1) {
820       assert(TD == 0 &&
821              "DecomposeGEPExpression and getUnderlyingObject disagree!");
822       return MayAlias;
823     }
824   }
825 
826   // In the two GEP Case, if there is no difference in the offsets of the
827   // computed pointers, the resultant pointers are a must alias.  This
828   // hapens when we have two lexically identical GEP's (for example).
829   //
830   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
831   // must aliases the GEP, the end result is a must alias also.
832   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
833     return MustAlias;
834 
835   // If we have a known constant offset, see if this offset is larger than the
836   // access size being queried.  If so, and if no variable indices can remove
837   // pieces of this constant, then we know we have a no-alias.  For example,
838   //   &A[100] != &A.
839 
840   // In order to handle cases like &A[100][i] where i is an out of range
841   // subscript, we have to ignore all constant offset pieces that are a multiple
842   // of a scaled index.  Do this by removing constant offsets that are a
843   // multiple of any of our variable indices.  This allows us to transform
844   // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
845   // provides an offset of 4 bytes (assuming a <= 4 byte access).
846   for (unsigned i = 0, e = GEP1VariableIndices.size();
847        i != e && GEP1BaseOffset;++i)
848     if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].Scale)
849       GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].Scale;
850 
851   // If our known offset is bigger than the access size, we know we don't have
852   // an alias.
853   if (GEP1BaseOffset) {
854     if (GEP1BaseOffset >= (int64_t)V2Size ||
855         GEP1BaseOffset <= -(int64_t)V1Size)
856       return NoAlias;
857   }
858 
859   return MayAlias;
860 }
861 
862 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
863 /// instruction against another.
864 AliasAnalysis::AliasResult
aliasSelect(const SelectInst * SI,unsigned SISize,const Value * V2,unsigned V2Size)865 BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
866                                 const Value *V2, unsigned V2Size) {
867   // If this select has been visited before, we're on a use-def cycle.
868   // Such cycles are only valid when PHI nodes are involved or in unreachable
869   // code. The visitPHI function catches cycles containing PHIs, but there
870   // could still be a cycle without PHIs in unreachable code.
871   if (!Visited.insert(SI))
872     return MayAlias;
873 
874   // If the values are Selects with the same condition, we can do a more precise
875   // check: just check for aliases between the values on corresponding arms.
876   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
877     if (SI->getCondition() == SI2->getCondition()) {
878       AliasResult Alias =
879         aliasCheck(SI->getTrueValue(), SISize,
880                    SI2->getTrueValue(), V2Size);
881       if (Alias == MayAlias)
882         return MayAlias;
883       AliasResult ThisAlias =
884         aliasCheck(SI->getFalseValue(), SISize,
885                    SI2->getFalseValue(), V2Size);
886       if (ThisAlias != Alias)
887         return MayAlias;
888       return Alias;
889     }
890 
891   // If both arms of the Select node NoAlias or MustAlias V2, then returns
892   // NoAlias / MustAlias. Otherwise, returns MayAlias.
893   AliasResult Alias =
894     aliasCheck(V2, V2Size, SI->getTrueValue(), SISize);
895   if (Alias == MayAlias)
896     return MayAlias;
897 
898   // If V2 is visited, the recursive case will have been caught in the
899   // above aliasCheck call, so these subsequent calls to aliasCheck
900   // don't need to assume that V2 is being visited recursively.
901   Visited.erase(V2);
902 
903   AliasResult ThisAlias =
904     aliasCheck(V2, V2Size, SI->getFalseValue(), SISize);
905   if (ThisAlias != Alias)
906     return MayAlias;
907   return Alias;
908 }
909 
910 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
911 // against another.
912 AliasAnalysis::AliasResult
aliasPHI(const PHINode * PN,unsigned PNSize,const Value * V2,unsigned V2Size)913 BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
914                              const Value *V2, unsigned V2Size) {
915   // The PHI node has already been visited, avoid recursion any further.
916   if (!Visited.insert(PN))
917     return MayAlias;
918 
919   // If the values are PHIs in the same block, we can do a more precise
920   // as well as efficient check: just check for aliases between the values
921   // on corresponding edges.
922   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
923     if (PN2->getParent() == PN->getParent()) {
924       AliasResult Alias =
925         aliasCheck(PN->getIncomingValue(0), PNSize,
926                    PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
927                    V2Size);
928       if (Alias == MayAlias)
929         return MayAlias;
930       for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
931         AliasResult ThisAlias =
932           aliasCheck(PN->getIncomingValue(i), PNSize,
933                      PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
934                      V2Size);
935         if (ThisAlias != Alias)
936           return MayAlias;
937       }
938       return Alias;
939     }
940 
941   SmallPtrSet<Value*, 4> UniqueSrc;
942   SmallVector<Value*, 4> V1Srcs;
943   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
944     Value *PV1 = PN->getIncomingValue(i);
945     if (isa<PHINode>(PV1))
946       // If any of the source itself is a PHI, return MayAlias conservatively
947       // to avoid compile time explosion. The worst possible case is if both
948       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
949       // and 'n' are the number of PHI sources.
950       return MayAlias;
951     if (UniqueSrc.insert(PV1))
952       V1Srcs.push_back(PV1);
953   }
954 
955   AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
956   // Early exit if the check of the first PHI source against V2 is MayAlias.
957   // Other results are not possible.
958   if (Alias == MayAlias)
959     return MayAlias;
960 
961   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
962   // NoAlias / MustAlias. Otherwise, returns MayAlias.
963   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
964     Value *V = V1Srcs[i];
965 
966     // If V2 is visited, the recursive case will have been caught in the
967     // above aliasCheck call, so these subsequent calls to aliasCheck
968     // don't need to assume that V2 is being visited recursively.
969     Visited.erase(V2);
970 
971     AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
972     if (ThisAlias != Alias || ThisAlias == MayAlias)
973       return MayAlias;
974   }
975 
976   return Alias;
977 }
978 
979 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
980 // such as array references.
981 //
982 AliasAnalysis::AliasResult
aliasCheck(const Value * V1,unsigned V1Size,const Value * V2,unsigned V2Size)983 BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
984                                const Value *V2, unsigned V2Size) {
985   // If either of the memory references is empty, it doesn't matter what the
986   // pointer values are.
987   if (V1Size == 0 || V2Size == 0)
988     return NoAlias;
989 
990   // Strip off any casts if they exist.
991   V1 = V1->stripPointerCasts();
992   V2 = V2->stripPointerCasts();
993 
994   // Are we checking for alias of the same value?
995   if (V1 == V2) return MustAlias;
996 
997   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
998     return NoAlias;  // Scalars cannot alias each other
999 
1000   // Figure out what objects these things are pointing to if we can.
1001   const Value *O1 = V1->getUnderlyingObject();
1002   const Value *O2 = V2->getUnderlyingObject();
1003 
1004   // Null values in the default address space don't point to any object, so they
1005   // don't alias any other pointer.
1006   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1007     if (CPN->getType()->getAddressSpace() == 0)
1008       return NoAlias;
1009   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1010     if (CPN->getType()->getAddressSpace() == 0)
1011       return NoAlias;
1012 
1013   if (O1 != O2) {
1014     // If V1/V2 point to two different objects we know that we have no alias.
1015     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1016       return NoAlias;
1017 
1018     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1019     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1020         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1021       return NoAlias;
1022 
1023     // Arguments can't alias with local allocations or noalias calls
1024     // in the same function.
1025     if (((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
1026          (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1)))))
1027       return NoAlias;
1028 
1029     // Most objects can't alias null.
1030     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1031         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1032       return NoAlias;
1033 
1034     // If one pointer is the result of a call/invoke or load and the other is a
1035     // non-escaping local object within the same function, then we know the
1036     // object couldn't escape to a point where the call could return it.
1037     //
1038     // Note that if the pointers are in different functions, there are a
1039     // variety of complications. A call with a nocapture argument may still
1040     // temporary store the nocapture argument's value in a temporary memory
1041     // location if that memory location doesn't escape. Or it may pass a
1042     // nocapture value to other functions as long as they don't capture it.
1043     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1044       return NoAlias;
1045     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1046       return NoAlias;
1047   }
1048 
1049   // If the size of one access is larger than the entire object on the other
1050   // side, then we know such behavior is undefined and can assume no alias.
1051   if (TD)
1052     if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *TD)) ||
1053         (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *TD)))
1054       return NoAlias;
1055 
1056   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1057   // GEP can't simplify, we don't even look at the PHI cases.
1058   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1059     std::swap(V1, V2);
1060     std::swap(V1Size, V2Size);
1061     std::swap(O1, O2);
1062   }
1063   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
1064     return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
1065 
1066   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1067     std::swap(V1, V2);
1068     std::swap(V1Size, V2Size);
1069   }
1070   if (const PHINode *PN = dyn_cast<PHINode>(V1))
1071     return aliasPHI(PN, V1Size, V2, V2Size);
1072 
1073   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1074     std::swap(V1, V2);
1075     std::swap(V1Size, V2Size);
1076   }
1077   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
1078     return aliasSelect(S1, V1Size, V2, V2Size);
1079 
1080   return NoAA::alias(V1, V1Size, V2, V2Size);
1081 }
1082 
1083 // Make sure that anything that uses AliasAnalysis pulls in this file.
1084 DEFINING_FILE_FOR(BasicAliasAnalysis)
1085