1 //==- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation --==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the generic AliasAnalysis interface which is used as the
10 // common interface used by all clients and implementations of alias analysis.
11 //
12 // This file also implements the default version of the AliasAnalysis interface
13 // that is to be used when no other implementation is specified.  This does some
14 // simple tests that detect obvious cases: two different global pointers cannot
15 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
16 // etc.
17 //
18 // This alias analysis implementation really isn't very good for anything, but
19 // it is very fast, and makes a nice clean default implementation.  Because it
20 // handles lots of little corner cases, other, more complex, alias analysis
21 // implementations may choose to rely on this pass to resolve these simple and
22 // easy cases.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
30 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/MemoryLocation.h"
34 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
35 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
36 #include "llvm/Analysis/ScopedNoAliasAA.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/IR/Argument.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/InitializePasses.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/AtomicOrdering.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <functional>
56 #include <iterator>
57 
58 #define DEBUG_TYPE "aa"
59 
60 using namespace llvm;
61 
62 STATISTIC(NumNoAlias,   "Number of NoAlias results");
63 STATISTIC(NumMayAlias,  "Number of MayAlias results");
64 STATISTIC(NumMustAlias, "Number of MustAlias results");
65 
66 /// Allow disabling BasicAA from the AA results. This is particularly useful
67 /// when testing to isolate a single AA implementation.
68 cl::opt<bool> DisableBasicAA("disable-basic-aa", cl::Hidden, cl::init(false));
69 
70 AAResults::AAResults(AAResults &&Arg)
71     : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) {
72   for (auto &AA : AAs)
73     AA->setAAResults(this);
74 }
75 
76 AAResults::~AAResults() {
77 // FIXME; It would be nice to at least clear out the pointers back to this
78 // aggregation here, but we end up with non-nesting lifetimes in the legacy
79 // pass manager that prevent this from working. In the legacy pass manager
80 // we'll end up with dangling references here in some cases.
81 #if 0
82   for (auto &AA : AAs)
83     AA->setAAResults(nullptr);
84 #endif
85 }
86 
87 bool AAResults::invalidate(Function &F, const PreservedAnalyses &PA,
88                            FunctionAnalysisManager::Invalidator &Inv) {
89   // AAResults preserves the AAManager by default, due to the stateless nature
90   // of AliasAnalysis. There is no need to check whether it has been preserved
91   // explicitly. Check if any module dependency was invalidated and caused the
92   // AAManager to be invalidated. Invalidate ourselves in that case.
93   auto PAC = PA.getChecker<AAManager>();
94   if (!PAC.preservedWhenStateless())
95     return true;
96 
97   // Check if any of the function dependencies were invalidated, and invalidate
98   // ourselves in that case.
99   for (AnalysisKey *ID : AADeps)
100     if (Inv.invalidate(ID, F, PA))
101       return true;
102 
103   // Everything we depend on is still fine, so are we. Nothing to invalidate.
104   return false;
105 }
106 
107 //===----------------------------------------------------------------------===//
108 // Default chaining methods
109 //===----------------------------------------------------------------------===//
110 
111 AliasResult AAResults::alias(const MemoryLocation &LocA,
112                              const MemoryLocation &LocB) {
113   AAQueryInfo AAQIP;
114   return alias(LocA, LocB, AAQIP);
115 }
116 
117 AliasResult AAResults::alias(const MemoryLocation &LocA,
118                              const MemoryLocation &LocB, AAQueryInfo &AAQI) {
119   AliasResult Result = MayAlias;
120 
121   Depth++;
122   for (const auto &AA : AAs) {
123     Result = AA->alias(LocA, LocB, AAQI);
124     if (Result != MayAlias)
125       break;
126   }
127   Depth--;
128 
129   if (Depth == 0) {
130     if (Result == NoAlias)
131       ++NumNoAlias;
132     else if (Result == MustAlias)
133       ++NumMustAlias;
134     else
135       ++NumMayAlias;
136   }
137   return Result;
138 }
139 
140 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc,
141                                        bool OrLocal) {
142   AAQueryInfo AAQIP;
143   return pointsToConstantMemory(Loc, AAQIP, OrLocal);
144 }
145 
146 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc,
147                                        AAQueryInfo &AAQI, bool OrLocal) {
148   for (const auto &AA : AAs)
149     if (AA->pointsToConstantMemory(Loc, AAQI, OrLocal))
150       return true;
151 
152   return false;
153 }
154 
155 ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
156   ModRefInfo Result = ModRefInfo::ModRef;
157 
158   for (const auto &AA : AAs) {
159     Result = intersectModRef(Result, AA->getArgModRefInfo(Call, ArgIdx));
160 
161     // Early-exit the moment we reach the bottom of the lattice.
162     if (isNoModRef(Result))
163       return ModRefInfo::NoModRef;
164   }
165 
166   return Result;
167 }
168 
169 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2) {
170   AAQueryInfo AAQIP;
171   return getModRefInfo(I, Call2, AAQIP);
172 }
173 
174 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2,
175                                     AAQueryInfo &AAQI) {
176   // We may have two calls.
177   if (const auto *Call1 = dyn_cast<CallBase>(I)) {
178     // Check if the two calls modify the same memory.
179     return getModRefInfo(Call1, Call2, AAQI);
180   } else if (I->isFenceLike()) {
181     // If this is a fence, just return ModRef.
182     return ModRefInfo::ModRef;
183   } else {
184     // Otherwise, check if the call modifies or references the
185     // location this memory access defines.  The best we can say
186     // is that if the call references what this instruction
187     // defines, it must be clobbered by this location.
188     const MemoryLocation DefLoc = MemoryLocation::get(I);
189     ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI);
190     if (isModOrRefSet(MR))
191       return setModAndRef(MR);
192   }
193   return ModRefInfo::NoModRef;
194 }
195 
196 ModRefInfo AAResults::getModRefInfo(const CallBase *Call,
197                                     const MemoryLocation &Loc) {
198   AAQueryInfo AAQIP;
199   return getModRefInfo(Call, Loc, AAQIP);
200 }
201 
202 ModRefInfo AAResults::getModRefInfo(const CallBase *Call,
203                                     const MemoryLocation &Loc,
204                                     AAQueryInfo &AAQI) {
205   ModRefInfo Result = ModRefInfo::ModRef;
206 
207   for (const auto &AA : AAs) {
208     Result = intersectModRef(Result, AA->getModRefInfo(Call, Loc, AAQI));
209 
210     // Early-exit the moment we reach the bottom of the lattice.
211     if (isNoModRef(Result))
212       return ModRefInfo::NoModRef;
213   }
214 
215   // Try to refine the mod-ref info further using other API entry points to the
216   // aggregate set of AA results.
217   auto MRB = getModRefBehavior(Call);
218   if (onlyAccessesInaccessibleMem(MRB))
219     return ModRefInfo::NoModRef;
220 
221   if (onlyReadsMemory(MRB))
222     Result = clearMod(Result);
223   else if (doesNotReadMemory(MRB))
224     Result = clearRef(Result);
225 
226   if (onlyAccessesArgPointees(MRB) || onlyAccessesInaccessibleOrArgMem(MRB)) {
227     bool IsMustAlias = true;
228     ModRefInfo AllArgsMask = ModRefInfo::NoModRef;
229     if (doesAccessArgPointees(MRB)) {
230       for (auto AI = Call->arg_begin(), AE = Call->arg_end(); AI != AE; ++AI) {
231         const Value *Arg = *AI;
232         if (!Arg->getType()->isPointerTy())
233           continue;
234         unsigned ArgIdx = std::distance(Call->arg_begin(), AI);
235         MemoryLocation ArgLoc =
236             MemoryLocation::getForArgument(Call, ArgIdx, TLI);
237         AliasResult ArgAlias = alias(ArgLoc, Loc, AAQI);
238         if (ArgAlias != NoAlias) {
239           ModRefInfo ArgMask = getArgModRefInfo(Call, ArgIdx);
240           AllArgsMask = unionModRef(AllArgsMask, ArgMask);
241         }
242         // Conservatively clear IsMustAlias unless only MustAlias is found.
243         IsMustAlias &= (ArgAlias == MustAlias);
244       }
245     }
246     // Return NoModRef if no alias found with any argument.
247     if (isNoModRef(AllArgsMask))
248       return ModRefInfo::NoModRef;
249     // Logical & between other AA analyses and argument analysis.
250     Result = intersectModRef(Result, AllArgsMask);
251     // If only MustAlias found above, set Must bit.
252     Result = IsMustAlias ? setMust(Result) : clearMust(Result);
253   }
254 
255   // If Loc is a constant memory location, the call definitely could not
256   // modify the memory location.
257   if (isModSet(Result) && pointsToConstantMemory(Loc, AAQI, /*OrLocal*/ false))
258     Result = clearMod(Result);
259 
260   return Result;
261 }
262 
263 ModRefInfo AAResults::getModRefInfo(const CallBase *Call1,
264                                     const CallBase *Call2) {
265   AAQueryInfo AAQIP;
266   return getModRefInfo(Call1, Call2, AAQIP);
267 }
268 
269 ModRefInfo AAResults::getModRefInfo(const CallBase *Call1,
270                                     const CallBase *Call2, AAQueryInfo &AAQI) {
271   ModRefInfo Result = ModRefInfo::ModRef;
272 
273   for (const auto &AA : AAs) {
274     Result = intersectModRef(Result, AA->getModRefInfo(Call1, Call2, AAQI));
275 
276     // Early-exit the moment we reach the bottom of the lattice.
277     if (isNoModRef(Result))
278       return ModRefInfo::NoModRef;
279   }
280 
281   // Try to refine the mod-ref info further using other API entry points to the
282   // aggregate set of AA results.
283 
284   // If Call1 or Call2 are readnone, they don't interact.
285   auto Call1B = getModRefBehavior(Call1);
286   if (Call1B == FMRB_DoesNotAccessMemory)
287     return ModRefInfo::NoModRef;
288 
289   auto Call2B = getModRefBehavior(Call2);
290   if (Call2B == FMRB_DoesNotAccessMemory)
291     return ModRefInfo::NoModRef;
292 
293   // If they both only read from memory, there is no dependence.
294   if (onlyReadsMemory(Call1B) && onlyReadsMemory(Call2B))
295     return ModRefInfo::NoModRef;
296 
297   // If Call1 only reads memory, the only dependence on Call2 can be
298   // from Call1 reading memory written by Call2.
299   if (onlyReadsMemory(Call1B))
300     Result = clearMod(Result);
301   else if (doesNotReadMemory(Call1B))
302     Result = clearRef(Result);
303 
304   // If Call2 only access memory through arguments, accumulate the mod/ref
305   // information from Call1's references to the memory referenced by
306   // Call2's arguments.
307   if (onlyAccessesArgPointees(Call2B)) {
308     if (!doesAccessArgPointees(Call2B))
309       return ModRefInfo::NoModRef;
310     ModRefInfo R = ModRefInfo::NoModRef;
311     bool IsMustAlias = true;
312     for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {
313       const Value *Arg = *I;
314       if (!Arg->getType()->isPointerTy())
315         continue;
316       unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);
317       auto Call2ArgLoc =
318           MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);
319 
320       // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
321       // dependence of Call1 on that location is the inverse:
322       // - If Call2 modifies location, dependence exists if Call1 reads or
323       //   writes.
324       // - If Call2 only reads location, dependence exists if Call1 writes.
325       ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);
326       ModRefInfo ArgMask = ModRefInfo::NoModRef;
327       if (isModSet(ArgModRefC2))
328         ArgMask = ModRefInfo::ModRef;
329       else if (isRefSet(ArgModRefC2))
330         ArgMask = ModRefInfo::Mod;
331 
332       // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
333       // above ArgMask to update dependence info.
334       ModRefInfo ModRefC1 = getModRefInfo(Call1, Call2ArgLoc, AAQI);
335       ArgMask = intersectModRef(ArgMask, ModRefC1);
336 
337       // Conservatively clear IsMustAlias unless only MustAlias is found.
338       IsMustAlias &= isMustSet(ModRefC1);
339 
340       R = intersectModRef(unionModRef(R, ArgMask), Result);
341       if (R == Result) {
342         // On early exit, not all args were checked, cannot set Must.
343         if (I + 1 != E)
344           IsMustAlias = false;
345         break;
346       }
347     }
348 
349     if (isNoModRef(R))
350       return ModRefInfo::NoModRef;
351 
352     // If MustAlias found above, set Must bit.
353     return IsMustAlias ? setMust(R) : clearMust(R);
354   }
355 
356   // If Call1 only accesses memory through arguments, check if Call2 references
357   // any of the memory referenced by Call1's arguments. If not, return NoModRef.
358   if (onlyAccessesArgPointees(Call1B)) {
359     if (!doesAccessArgPointees(Call1B))
360       return ModRefInfo::NoModRef;
361     ModRefInfo R = ModRefInfo::NoModRef;
362     bool IsMustAlias = true;
363     for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {
364       const Value *Arg = *I;
365       if (!Arg->getType()->isPointerTy())
366         continue;
367       unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);
368       auto Call1ArgLoc =
369           MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);
370 
371       // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
372       // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
373       // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
374       ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);
375       ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI);
376       if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||
377           (isRefSet(ArgModRefC1) && isModSet(ModRefC2)))
378         R = intersectModRef(unionModRef(R, ArgModRefC1), Result);
379 
380       // Conservatively clear IsMustAlias unless only MustAlias is found.
381       IsMustAlias &= isMustSet(ModRefC2);
382 
383       if (R == Result) {
384         // On early exit, not all args were checked, cannot set Must.
385         if (I + 1 != E)
386           IsMustAlias = false;
387         break;
388       }
389     }
390 
391     if (isNoModRef(R))
392       return ModRefInfo::NoModRef;
393 
394     // If MustAlias found above, set Must bit.
395     return IsMustAlias ? setMust(R) : clearMust(R);
396   }
397 
398   return Result;
399 }
400 
401 FunctionModRefBehavior AAResults::getModRefBehavior(const CallBase *Call) {
402   FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
403 
404   for (const auto &AA : AAs) {
405     Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(Call));
406 
407     // Early-exit the moment we reach the bottom of the lattice.
408     if (Result == FMRB_DoesNotAccessMemory)
409       return Result;
410   }
411 
412   return Result;
413 }
414 
415 FunctionModRefBehavior AAResults::getModRefBehavior(const Function *F) {
416   FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
417 
418   for (const auto &AA : AAs) {
419     Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(F));
420 
421     // Early-exit the moment we reach the bottom of the lattice.
422     if (Result == FMRB_DoesNotAccessMemory)
423       return Result;
424   }
425 
426   return Result;
427 }
428 
429 raw_ostream &llvm::operator<<(raw_ostream &OS, AliasResult AR) {
430   switch (AR) {
431   case NoAlias:
432     OS << "NoAlias";
433     break;
434   case MustAlias:
435     OS << "MustAlias";
436     break;
437   case MayAlias:
438     OS << "MayAlias";
439     break;
440   case PartialAlias:
441     OS << "PartialAlias";
442     break;
443   }
444   return OS;
445 }
446 
447 //===----------------------------------------------------------------------===//
448 // Helper method implementation
449 //===----------------------------------------------------------------------===//
450 
451 ModRefInfo AAResults::getModRefInfo(const LoadInst *L,
452                                     const MemoryLocation &Loc) {
453   AAQueryInfo AAQIP;
454   return getModRefInfo(L, Loc, AAQIP);
455 }
456 ModRefInfo AAResults::getModRefInfo(const LoadInst *L,
457                                     const MemoryLocation &Loc,
458                                     AAQueryInfo &AAQI) {
459   // Be conservative in the face of atomic.
460   if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered))
461     return ModRefInfo::ModRef;
462 
463   // If the load address doesn't alias the given address, it doesn't read
464   // or write the specified memory.
465   if (Loc.Ptr) {
466     AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI);
467     if (AR == NoAlias)
468       return ModRefInfo::NoModRef;
469     if (AR == MustAlias)
470       return ModRefInfo::MustRef;
471   }
472   // Otherwise, a load just reads.
473   return ModRefInfo::Ref;
474 }
475 
476 ModRefInfo AAResults::getModRefInfo(const StoreInst *S,
477                                     const MemoryLocation &Loc) {
478   AAQueryInfo AAQIP;
479   return getModRefInfo(S, Loc, AAQIP);
480 }
481 ModRefInfo AAResults::getModRefInfo(const StoreInst *S,
482                                     const MemoryLocation &Loc,
483                                     AAQueryInfo &AAQI) {
484   // Be conservative in the face of atomic.
485   if (isStrongerThan(S->getOrdering(), AtomicOrdering::Unordered))
486     return ModRefInfo::ModRef;
487 
488   if (Loc.Ptr) {
489     AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI);
490     // If the store address cannot alias the pointer in question, then the
491     // specified memory cannot be modified by the store.
492     if (AR == NoAlias)
493       return ModRefInfo::NoModRef;
494 
495     // If the pointer is a pointer to constant memory, then it could not have
496     // been modified by this store.
497     if (pointsToConstantMemory(Loc, AAQI))
498       return ModRefInfo::NoModRef;
499 
500     // If the store address aliases the pointer as must alias, set Must.
501     if (AR == MustAlias)
502       return ModRefInfo::MustMod;
503   }
504 
505   // Otherwise, a store just writes.
506   return ModRefInfo::Mod;
507 }
508 
509 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, const MemoryLocation &Loc) {
510   AAQueryInfo AAQIP;
511   return getModRefInfo(S, Loc, AAQIP);
512 }
513 
514 ModRefInfo AAResults::getModRefInfo(const FenceInst *S,
515                                     const MemoryLocation &Loc,
516                                     AAQueryInfo &AAQI) {
517   // If we know that the location is a constant memory location, the fence
518   // cannot modify this location.
519   if (Loc.Ptr && pointsToConstantMemory(Loc, AAQI))
520     return ModRefInfo::Ref;
521   return ModRefInfo::ModRef;
522 }
523 
524 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V,
525                                     const MemoryLocation &Loc) {
526   AAQueryInfo AAQIP;
527   return getModRefInfo(V, Loc, AAQIP);
528 }
529 
530 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V,
531                                     const MemoryLocation &Loc,
532                                     AAQueryInfo &AAQI) {
533   if (Loc.Ptr) {
534     AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI);
535     // If the va_arg address cannot alias the pointer in question, then the
536     // specified memory cannot be accessed by the va_arg.
537     if (AR == NoAlias)
538       return ModRefInfo::NoModRef;
539 
540     // If the pointer is a pointer to constant memory, then it could not have
541     // been modified by this va_arg.
542     if (pointsToConstantMemory(Loc, AAQI))
543       return ModRefInfo::NoModRef;
544 
545     // If the va_arg aliases the pointer as must alias, set Must.
546     if (AR == MustAlias)
547       return ModRefInfo::MustModRef;
548   }
549 
550   // Otherwise, a va_arg reads and writes.
551   return ModRefInfo::ModRef;
552 }
553 
554 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad,
555                                     const MemoryLocation &Loc) {
556   AAQueryInfo AAQIP;
557   return getModRefInfo(CatchPad, Loc, AAQIP);
558 }
559 
560 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad,
561                                     const MemoryLocation &Loc,
562                                     AAQueryInfo &AAQI) {
563   if (Loc.Ptr) {
564     // If the pointer is a pointer to constant memory,
565     // then it could not have been modified by this catchpad.
566     if (pointsToConstantMemory(Loc, AAQI))
567       return ModRefInfo::NoModRef;
568   }
569 
570   // Otherwise, a catchpad reads and writes.
571   return ModRefInfo::ModRef;
572 }
573 
574 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet,
575                                     const MemoryLocation &Loc) {
576   AAQueryInfo AAQIP;
577   return getModRefInfo(CatchRet, Loc, AAQIP);
578 }
579 
580 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet,
581                                     const MemoryLocation &Loc,
582                                     AAQueryInfo &AAQI) {
583   if (Loc.Ptr) {
584     // If the pointer is a pointer to constant memory,
585     // then it could not have been modified by this catchpad.
586     if (pointsToConstantMemory(Loc, AAQI))
587       return ModRefInfo::NoModRef;
588   }
589 
590   // Otherwise, a catchret reads and writes.
591   return ModRefInfo::ModRef;
592 }
593 
594 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX,
595                                     const MemoryLocation &Loc) {
596   AAQueryInfo AAQIP;
597   return getModRefInfo(CX, Loc, AAQIP);
598 }
599 
600 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX,
601                                     const MemoryLocation &Loc,
602                                     AAQueryInfo &AAQI) {
603   // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
604   if (isStrongerThanMonotonic(CX->getSuccessOrdering()))
605     return ModRefInfo::ModRef;
606 
607   if (Loc.Ptr) {
608     AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI);
609     // If the cmpxchg address does not alias the location, it does not access
610     // it.
611     if (AR == NoAlias)
612       return ModRefInfo::NoModRef;
613 
614     // If the cmpxchg address aliases the pointer as must alias, set Must.
615     if (AR == MustAlias)
616       return ModRefInfo::MustModRef;
617   }
618 
619   return ModRefInfo::ModRef;
620 }
621 
622 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW,
623                                     const MemoryLocation &Loc) {
624   AAQueryInfo AAQIP;
625   return getModRefInfo(RMW, Loc, AAQIP);
626 }
627 
628 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW,
629                                     const MemoryLocation &Loc,
630                                     AAQueryInfo &AAQI) {
631   // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
632   if (isStrongerThanMonotonic(RMW->getOrdering()))
633     return ModRefInfo::ModRef;
634 
635   if (Loc.Ptr) {
636     AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI);
637     // If the atomicrmw address does not alias the location, it does not access
638     // it.
639     if (AR == NoAlias)
640       return ModRefInfo::NoModRef;
641 
642     // If the atomicrmw address aliases the pointer as must alias, set Must.
643     if (AR == MustAlias)
644       return ModRefInfo::MustModRef;
645   }
646 
647   return ModRefInfo::ModRef;
648 }
649 
650 /// Return information about whether a particular call site modifies
651 /// or reads the specified memory location \p MemLoc before instruction \p I
652 /// in a BasicBlock.
653 /// FIXME: this is really just shoring-up a deficiency in alias analysis.
654 /// BasicAA isn't willing to spend linear time determining whether an alloca
655 /// was captured before or after this particular call, while we are. However,
656 /// with a smarter AA in place, this test is just wasting compile time.
657 ModRefInfo AAResults::callCapturesBefore(const Instruction *I,
658                                          const MemoryLocation &MemLoc,
659                                          DominatorTree *DT) {
660   if (!DT)
661     return ModRefInfo::ModRef;
662 
663   const Value *Object = getUnderlyingObject(MemLoc.Ptr);
664   if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
665       isa<Constant>(Object))
666     return ModRefInfo::ModRef;
667 
668   const auto *Call = dyn_cast<CallBase>(I);
669   if (!Call || Call == Object)
670     return ModRefInfo::ModRef;
671 
672   if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,
673                                  /* StoreCaptures */ true, I, DT,
674                                  /* include Object */ true))
675     return ModRefInfo::ModRef;
676 
677   unsigned ArgNo = 0;
678   ModRefInfo R = ModRefInfo::NoModRef;
679   bool IsMustAlias = true;
680   // Set flag only if no May found and all operands processed.
681   for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
682        CI != CE; ++CI, ++ArgNo) {
683     // Only look at the no-capture or byval pointer arguments.  If this
684     // pointer were passed to arguments that were neither of these, then it
685     // couldn't be no-capture.
686     if (!(*CI)->getType()->isPointerTy() ||
687         (!Call->doesNotCapture(ArgNo) && ArgNo < Call->getNumArgOperands() &&
688          !Call->isByValArgument(ArgNo)))
689       continue;
690 
691     AliasResult AR = alias(*CI, Object);
692     // If this is a no-capture pointer argument, see if we can tell that it
693     // is impossible to alias the pointer we're checking.  If not, we have to
694     // assume that the call could touch the pointer, even though it doesn't
695     // escape.
696     if (AR != MustAlias)
697       IsMustAlias = false;
698     if (AR == NoAlias)
699       continue;
700     if (Call->doesNotAccessMemory(ArgNo))
701       continue;
702     if (Call->onlyReadsMemory(ArgNo)) {
703       R = ModRefInfo::Ref;
704       continue;
705     }
706     // Not returning MustModRef since we have not seen all the arguments.
707     return ModRefInfo::ModRef;
708   }
709   return IsMustAlias ? setMust(R) : clearMust(R);
710 }
711 
712 /// canBasicBlockModify - Return true if it is possible for execution of the
713 /// specified basic block to modify the location Loc.
714 ///
715 bool AAResults::canBasicBlockModify(const BasicBlock &BB,
716                                     const MemoryLocation &Loc) {
717   return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod);
718 }
719 
720 /// canInstructionRangeModRef - Return true if it is possible for the
721 /// execution of the specified instructions to mod\ref (according to the
722 /// mode) the location Loc. The instructions to consider are all
723 /// of the instructions in the range of [I1,I2] INCLUSIVE.
724 /// I1 and I2 must be in the same basic block.
725 bool AAResults::canInstructionRangeModRef(const Instruction &I1,
726                                           const Instruction &I2,
727                                           const MemoryLocation &Loc,
728                                           const ModRefInfo Mode) {
729   assert(I1.getParent() == I2.getParent() &&
730          "Instructions not in same basic block!");
731   BasicBlock::const_iterator I = I1.getIterator();
732   BasicBlock::const_iterator E = I2.getIterator();
733   ++E;  // Convert from inclusive to exclusive range.
734 
735   for (; I != E; ++I) // Check every instruction in range
736     if (isModOrRefSet(intersectModRef(getModRefInfo(&*I, Loc), Mode)))
737       return true;
738   return false;
739 }
740 
741 // Provide a definition for the root virtual destructor.
742 AAResults::Concept::~Concept() = default;
743 
744 // Provide a definition for the static object used to identify passes.
745 AnalysisKey AAManager::Key;
746 
747 namespace {
748 
749 
750 } // end anonymous namespace
751 
752 ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID) {
753   initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
754 }
755 
756 ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB)
757     : ImmutablePass(ID), CB(std::move(CB)) {
758   initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
759 }
760 
761 char ExternalAAWrapperPass::ID = 0;
762 
763 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",
764                 false, true)
765 
766 ImmutablePass *
767 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) {
768   return new ExternalAAWrapperPass(std::move(Callback));
769 }
770 
771 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) {
772   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
773 }
774 
775 char AAResultsWrapperPass::ID = 0;
776 
777 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa",
778                       "Function Alias Analysis Results", false, true)
779 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
780 INITIALIZE_PASS_DEPENDENCY(CFLAndersAAWrapperPass)
781 INITIALIZE_PASS_DEPENDENCY(CFLSteensAAWrapperPass)
782 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass)
783 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
784 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
785 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
786 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass)
787 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass)
788 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa",
789                     "Function Alias Analysis Results", false, true)
790 
791 FunctionPass *llvm::createAAResultsWrapperPass() {
792   return new AAResultsWrapperPass();
793 }
794 
795 /// Run the wrapper pass to rebuild an aggregation over known AA passes.
796 ///
797 /// This is the legacy pass manager's interface to the new-style AA results
798 /// aggregation object. Because this is somewhat shoe-horned into the legacy
799 /// pass manager, we hard code all the specific alias analyses available into
800 /// it. While the particular set enabled is configured via commandline flags,
801 /// adding a new alias analysis to LLVM will require adding support for it to
802 /// this list.
803 bool AAResultsWrapperPass::runOnFunction(Function &F) {
804   // NB! This *must* be reset before adding new AA results to the new
805   // AAResults object because in the legacy pass manager, each instance
806   // of these will refer to the *same* immutable analyses, registering and
807   // unregistering themselves with them. We need to carefully tear down the
808   // previous object first, in this case replacing it with an empty one, before
809   // registering new results.
810   AAR.reset(
811       new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)));
812 
813   // BasicAA is always available for function analyses. Also, we add it first
814   // so that it can trump TBAA results when it proves MustAlias.
815   // FIXME: TBAA should have an explicit mode to support this and then we
816   // should reconsider the ordering here.
817   if (!DisableBasicAA)
818     AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());
819 
820   // Populate the results with the currently available AAs.
821   if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())
822     AAR->addAAResult(WrapperPass->getResult());
823   if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
824     AAR->addAAResult(WrapperPass->getResult());
825   if (auto *WrapperPass =
826           getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>())
827     AAR->addAAResult(WrapperPass->getResult());
828   if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>())
829     AAR->addAAResult(WrapperPass->getResult());
830   if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>())
831     AAR->addAAResult(WrapperPass->getResult());
832   if (auto *WrapperPass = getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
833     AAR->addAAResult(WrapperPass->getResult());
834   if (auto *WrapperPass = getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
835     AAR->addAAResult(WrapperPass->getResult());
836 
837   // If available, run an external AA providing callback over the results as
838   // well.
839   if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>())
840     if (WrapperPass->CB)
841       WrapperPass->CB(*this, F, *AAR);
842 
843   // Analyses don't mutate the IR, so return false.
844   return false;
845 }
846 
847 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
848   AU.setPreservesAll();
849   AU.addRequired<BasicAAWrapperPass>();
850   AU.addRequired<TargetLibraryInfoWrapperPass>();
851 
852   // We also need to mark all the alias analysis passes we will potentially
853   // probe in runOnFunction as used here to ensure the legacy pass manager
854   // preserves them. This hard coding of lists of alias analyses is specific to
855   // the legacy pass manager.
856   AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>();
857   AU.addUsedIfAvailable<TypeBasedAAWrapperPass>();
858   AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>();
859   AU.addUsedIfAvailable<GlobalsAAWrapperPass>();
860   AU.addUsedIfAvailable<SCEVAAWrapperPass>();
861   AU.addUsedIfAvailable<CFLAndersAAWrapperPass>();
862   AU.addUsedIfAvailable<CFLSteensAAWrapperPass>();
863   AU.addUsedIfAvailable<ExternalAAWrapperPass>();
864 }
865 
866 AAManager::Result AAManager::run(Function &F, FunctionAnalysisManager &AM) {
867   Result R(AM.getResult<TargetLibraryAnalysis>(F));
868   for (auto &Getter : ResultGetters)
869     (*Getter)(F, AM, R);
870   return R;
871 }
872 
873 AAResults llvm::createLegacyPMAAResults(Pass &P, Function &F,
874                                         BasicAAResult &BAR) {
875   AAResults AAR(P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F));
876 
877   // Add in our explicitly constructed BasicAA results.
878   if (!DisableBasicAA)
879     AAR.addAAResult(BAR);
880 
881   // Populate the results with the other currently available AAs.
882   if (auto *WrapperPass =
883           P.getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())
884     AAR.addAAResult(WrapperPass->getResult());
885   if (auto *WrapperPass = P.getAnalysisIfAvailable<TypeBasedAAWrapperPass>())
886     AAR.addAAResult(WrapperPass->getResult());
887   if (auto *WrapperPass =
888           P.getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>())
889     AAR.addAAResult(WrapperPass->getResult());
890   if (auto *WrapperPass = P.getAnalysisIfAvailable<GlobalsAAWrapperPass>())
891     AAR.addAAResult(WrapperPass->getResult());
892   if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLAndersAAWrapperPass>())
893     AAR.addAAResult(WrapperPass->getResult());
894   if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLSteensAAWrapperPass>())
895     AAR.addAAResult(WrapperPass->getResult());
896   if (auto *WrapperPass = P.getAnalysisIfAvailable<ExternalAAWrapperPass>())
897     if (WrapperPass->CB)
898       WrapperPass->CB(P, F, AAR);
899 
900   return AAR;
901 }
902 
903 bool llvm::isNoAliasCall(const Value *V) {
904   if (const auto *Call = dyn_cast<CallBase>(V))
905     return Call->hasRetAttr(Attribute::NoAlias);
906   return false;
907 }
908 
909 bool llvm::isNoAliasArgument(const Value *V) {
910   if (const Argument *A = dyn_cast<Argument>(V))
911     return A->hasNoAliasAttr();
912   return false;
913 }
914 
915 bool llvm::isIdentifiedObject(const Value *V) {
916   if (isa<AllocaInst>(V))
917     return true;
918   if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
919     return true;
920   if (isNoAliasCall(V))
921     return true;
922   if (const Argument *A = dyn_cast<Argument>(V))
923     return A->hasNoAliasAttr() || A->hasByValAttr();
924   return false;
925 }
926 
927 bool llvm::isIdentifiedFunctionLocal(const Value *V) {
928   return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
929 }
930 
931 void llvm::getAAResultsAnalysisUsage(AnalysisUsage &AU) {
932   // This function needs to be in sync with llvm::createLegacyPMAAResults -- if
933   // more alias analyses are added to llvm::createLegacyPMAAResults, they need
934   // to be added here also.
935   AU.addRequired<TargetLibraryInfoWrapperPass>();
936   AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>();
937   AU.addUsedIfAvailable<TypeBasedAAWrapperPass>();
938   AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>();
939   AU.addUsedIfAvailable<GlobalsAAWrapperPass>();
940   AU.addUsedIfAvailable<CFLAndersAAWrapperPass>();
941   AU.addUsedIfAvailable<CFLSteensAAWrapperPass>();
942   AU.addUsedIfAvailable<ExternalAAWrapperPass>();
943 }
944