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