llvm.org GIT mirror llvm / 9146833
[PM/AA] Rebuild LLVM's alias analysis infrastructure in a way compatible with the new pass manager, and no longer relying on analysis groups. This builds essentially a ground-up new AA infrastructure stack for LLVM. The core ideas are the same that are used throughout the new pass manager: type erased polymorphism and direct composition. The design is as follows: - FunctionAAResults is a type-erasing alias analysis results aggregation interface to walk a single query across a range of results from different alias analyses. Currently this is function-specific as we always assume that aliasing queries are *within* a function. - AAResultBase is a CRTP utility providing stub implementations of various parts of the alias analysis result concept, notably in several cases in terms of other more general parts of the interface. This can be used to implement only a narrow part of the interface rather than the entire interface. This isn't really ideal, this logic should be hoisted into FunctionAAResults as currently it will cause a significant amount of redundant work, but it faithfully models the behavior of the prior infrastructure. - All the alias analysis passes are ported to be wrapper passes for the legacy PM and new-style analysis passes for the new PM with a shared result object. In some cases (most notably CFL), this is an extremely naive approach that we should revisit when we can specialize for the new pass manager. - BasicAA has been restructured to reflect that it is much more fundamentally a function analysis because it uses dominator trees and loop info that need to be constructed for each function. All of the references to getting alias analysis results have been updated to use the new aggregation interface. All the preservation and other pass management code has been updated accordingly. The way the FunctionAAResultsWrapperPass works is to detect the available alias analyses when run, and add them to the results object. This means that we should be able to continue to respect when various passes are added to the pipeline, for example adding CFL or adding TBAA passes should just cause their results to be available and to get folded into this. The exception to this rule is BasicAA which really needs to be a function pass due to using dominator trees and loop info. As a consequence, the FunctionAAResultsWrapperPass directly depends on BasicAA and always includes it in the aggregation. This has significant implications for preserving analyses. Generally, most passes shouldn't bother preserving FunctionAAResultsWrapperPass because rebuilding the results just updates the set of known AA passes. The exception to this rule are LoopPass instances which need to preserve all the function analyses that the loop pass manager will end up needing. This means preserving both BasicAAWrapperPass and the aggregating FunctionAAResultsWrapperPass. Now, when preserving an alias analysis, you do so by directly preserving that analysis. This is only necessary for non-immutable-pass-provided alias analyses though, and there are only three of interest: BasicAA, GlobalsAA (formerly GlobalsModRef), and SCEVAA. Usually BasicAA is preserved when needed because it (like DominatorTree and LoopInfo) is marked as a CFG-only pass. I've expanded GlobalsAA into the preserved set everywhere we previously were preserving all of AliasAnalysis, and I've added SCEVAA in the intersection of that with where we preserve SCEV itself. One significant challenge to all of this is that the CGSCC passes were actually using the alias analysis implementations by taking advantage of a pretty amazing set of loop holes in the old pass manager's analysis management code which allowed analysis groups to slide through in many cases. Moving away from analysis groups makes this problem much more obvious. To fix it, I've leveraged the flexibility the design of the new PM components provides to just directly construct the relevant alias analyses for the relevant functions in the IPO passes that need them. This is a bit hacky, but should go away with the new pass manager, and is already in many ways cleaner than the prior state. Another significant challenge is that various facilities of the old alias analysis infrastructure just don't fit any more. The most significant of these is the alias analysis 'counter' pass. That pass relied on the ability to snoop on AA queries at different points in the analysis group chain. Instead, I'm planning to build printing functionality directly into the aggregation layer. I've not included that in this patch merely to keep it smaller. Note that all of this needs a nearly complete rewrite of the AA documentation. I'm planning to do that, but I'd like to make sure the new design settles, and to flesh out a bit more of what it looks like in the new pass manager first. Differential Revision: http://reviews.llvm.org/D12080 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@247167 91177308-0d34-0410-b5e6-96231b3b80d8 Chandler Carruth 5 years ago
136 changed file(s) with 2331 addition(s) and 1815 deletion(s). Raw diff Collapse all Expand all
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/Analysis/BasicAliasAnalysis.h"
21 #include "llvm/Analysis/Passes.h"
32 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/LLVMContext.h"
533532 // Create a new pass manager attached to it.
534533 TheFPM = llvm::make_unique(TheModule.get());
535534
536 // Provide basic AliasAnalysis support for GVN.
537 TheFPM->add(createBasicAliasAnalysisPass());
538535 // Do simple "peephole" optimizations and bit-twiddling optzns.
539536 TheFPM->add(createInstructionCombiningPass());
540537 // Reassociate expressions.
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/Analysis/BasicAliasAnalysis.h"
21 #include "llvm/Analysis/Passes.h"
32 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/LLVMContext.h"
807806 // Create a new pass manager attached to it.
808807 TheFPM = llvm::make_unique(TheModule.get());
809808
810 // Provide basic AliasAnalysis support for GVN.
811 TheFPM->add(createBasicAliasAnalysisPass());
812809 // Do simple "peephole" optimizations and bit-twiddling optzns.
813810 TheFPM->add(createInstructionCombiningPass());
814811 // Reassociate expressions.
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/Analysis/BasicAliasAnalysis.h"
21 #include "llvm/Analysis/Passes.h"
32 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/LLVMContext.h"
925924 // Create a new pass manager attached to it.
926925 TheFPM = llvm::make_unique(TheModule.get());
927926
928 // Provide basic AliasAnalysis support for GVN.
929 TheFPM->add(createBasicAliasAnalysisPass());
930927 // Do simple "peephole" optimizations and bit-twiddling optzns.
931928 TheFPM->add(createInstructionCombiningPass());
932929 // Reassociate expressions.
0 #include "llvm/ADT/STLExtras.h"
1 #include "llvm/Analysis/BasicAliasAnalysis.h"
21 #include "llvm/Analysis/Passes.h"
32 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/LLVMContext.h"
10911090 // Create a new pass manager attached to it.
10921091 TheFPM = llvm::make_unique(TheModule.get());
10931092
1094 // Provide basic AliasAnalysis support for GVN.
1095 TheFPM->add(createBasicAliasAnalysisPass());
10961093 // Do simple "peephole" optimizations and bit-twiddling optzns.
10971094 TheFPM->add(createInstructionCombiningPass());
10981095 // Reassociate expressions.
4040 #include "llvm/ADT/DenseMap.h"
4141 #include "llvm/IR/CallSite.h"
4242 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/PassManager.h"
4344 #include "llvm/Analysis/MemoryLocation.h"
4445
4546 namespace llvm {
46
47 class BasicAAResult;
4748 class LoadInst;
4849 class StoreInst;
4950 class VAArgInst;
155156 FMRB_UnknownModRefBehavior = FMRL_Anywhere | MRI_ModRef
156157 };
157158
158 class AliasAnalysis {
159 protected:
160 const DataLayout *DL;
161 const TargetLibraryInfo *TLI;
162
163 private:
164 AliasAnalysis *AA; // Previous Alias Analysis to chain to.
165
166 protected:
167 /// InitializeAliasAnalysis - Subclasses must call this method to initialize
168 /// the AliasAnalysis interface before any other methods are called. This is
169 /// typically called by the run* methods of these subclasses. This may be
170 /// called multiple times.
171 ///
172 void InitializeAliasAnalysis(Pass *P, const DataLayout *DL);
173
174 /// getAnalysisUsage - All alias analysis implementations should invoke this
175 /// directly (using AliasAnalysis::getAnalysisUsage(AU)).
176 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
177
159 class AAResults {
178160 public:
179 static char ID; // Class identification, replacement for typeinfo
180 AliasAnalysis() : DL(nullptr), TLI(nullptr), AA(nullptr) {}
181 virtual ~AliasAnalysis(); // We want to be subclassed
182
183 /// getTargetLibraryInfo - Return a pointer to the current TargetLibraryInfo
184 /// object, or null if no TargetLibraryInfo object is available.
185 ///
186 const TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
161 // Make these results default constructable and movable. We have to spell
162 // these out because MSVC won't synthesize them.
163 AAResults() {}
164 AAResults(AAResults &&Arg);
165 AAResults &operator=(AAResults &&Arg);
166 ~AAResults();
167
168 /// Register a specific AA result.
169 template void addAAResult(AAResultT &AAResult) {
170 // FIXME: We should use a much lighter weight system than the usual
171 // polymorphic pattern because we don't own AAResult. It should
172 // ideally involve two pointers and no separate allocation.
173 AAs.emplace_back(new Model(AAResult, *this));
174 }
187175
188176 //===--------------------------------------------------------------------===//
189177 /// \name Alias Queries
193181 /// Returns an AliasResult indicating whether the two pointers are aliased to
194182 /// each other. This is the interface that must be implemented by specific
195183 /// alias analysis implementations.
196 virtual AliasResult alias(const MemoryLocation &LocA,
197 const MemoryLocation &LocB);
184 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
198185
199186 /// A convenience wrapper around the primary \c alias interface.
200187 AliasResult alias(const Value *V1, uint64_t V1Size, const Value *V2,
238225
239226 /// Checks whether the given location points to constant memory, or if
240227 /// \p OrLocal is true whether it points to a local alloca.
241 virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
242 bool OrLocal = false);
228 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
243229
244230 /// A convenience wrapper around the primary \c pointsToConstantMemory
245231 /// interface.
257243 /// that these bits do not necessarily account for the overall behavior of
258244 /// the function, but rather only provide additional per-argument
259245 /// information.
260 virtual ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
246 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
261247
262248 /// Return the behavior of the given call site.
263 virtual FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
249 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
264250
265251 /// Return the behavior when calling the given function.
266 virtual FunctionModRefBehavior getModRefBehavior(const Function *F);
252 FunctionModRefBehavior getModRefBehavior(const Function *F);
267253
268254 /// Checks if the specified call is known to never read or write memory.
269255 ///
343329
344330 /// getModRefInfo (for call sites) - Return information about whether
345331 /// a particular call site modifies or reads the specified memory location.
346 virtual ModRefInfo getModRefInfo(ImmutableCallSite CS,
347 const MemoryLocation &Loc);
332 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
348333
349334 /// getModRefInfo (for call sites) - A convenience wrapper.
350335 ModRefInfo getModRefInfo(ImmutableCallSite CS, const Value *P,
493478 /// Return information about whether two call sites may refer to the same set
494479 /// of memory locations. See the AA documentation for details:
495480 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
496 virtual ModRefInfo getModRefInfo(ImmutableCallSite CS1,
497 ImmutableCallSite CS2);
481 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
498482
499483 /// \brief Return information about whether a particular call site modifies
500484 /// or reads the specified memory location \p MemLoc before instruction \p I
541525 const ModRefInfo Mode) {
542526 return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
543527 }
528
529 private:
530 class Concept;
531 template class Model;
532
533 template friend class AAResultBase;
534
535 std::vector> AAs;
544536 };
537
538 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
539 /// pointer or reference.
540 typedef AAResults AliasAnalysis;
541
542 /// A private abstract base class describing the concept of an individual alias
543 /// analysis implementation.
544 ///
545 /// This interface is implemented by any \c Model instantiation. It is also the
546 /// interface which a type used to instantiate the model must provide.
547 ///
548 /// All of these methods model methods by the same name in the \c
549 /// AAResults class. Only differences and specifics to how the
550 /// implementations are called are documented here.
551 class AAResults::Concept {
552 public:
553 virtual ~Concept() = 0;
554
555 /// An update API used internally by the AAResults to provide
556 /// a handle back to the top level aggregation.
557 virtual void setAAResults(AAResults *NewAAR) = 0;
558
559 //===--------------------------------------------------------------------===//
560 /// \name Alias Queries
561 /// @{
562
563 /// The main low level interface to the alias analysis implementation.
564 /// Returns an AliasResult indicating whether the two pointers are aliased to
565 /// each other. This is the interface that must be implemented by specific
566 /// alias analysis implementations.
567 virtual AliasResult alias(const MemoryLocation &LocA,
568 const MemoryLocation &LocB) = 0;
569
570 /// Checks whether the given location points to constant memory, or if
571 /// \p OrLocal is true whether it points to a local alloca.
572 virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
573 bool OrLocal) = 0;
574
575 /// @}
576 //===--------------------------------------------------------------------===//
577 /// \name Simple mod/ref information
578 /// @{
579
580 /// Get the ModRef info associated with a pointer argument of a callsite. The
581 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
582 /// that these bits do not necessarily account for the overall behavior of
583 /// the function, but rather only provide additional per-argument
584 /// information.
585 virtual ModRefInfo getArgModRefInfo(ImmutableCallSite CS,
586 unsigned ArgIdx) = 0;
587
588 /// Return the behavior of the given call site.
589 virtual FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) = 0;
590
591 /// Return the behavior when calling the given function.
592 virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
593
594 /// getModRefInfo (for call sites) - Return information about whether
595 /// a particular call site modifies or reads the specified memory location.
596 virtual ModRefInfo getModRefInfo(ImmutableCallSite CS,
597 const MemoryLocation &Loc) = 0;
598
599 /// Return information about whether two call sites may refer to the same set
600 /// of memory locations. See the AA documentation for details:
601 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
602 virtual ModRefInfo getModRefInfo(ImmutableCallSite CS1,
603 ImmutableCallSite CS2) = 0;
604
605 /// @}
606 };
607
608 /// A private class template which derives from \c Concept and wraps some other
609 /// type.
610 ///
611 /// This models the concept by directly forwarding each interface point to the
612 /// wrapped type which must implement a compatible interface. This provides
613 /// a type erased binding.
614 template class AAResults::Model final : public Concept {
615 AAResultT &Result;
616
617 public:
618 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
619 Result.setAAResults(&AAR);
620 }
621 ~Model() override {}
622
623 void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
624
625 AliasResult alias(const MemoryLocation &LocA,
626 const MemoryLocation &LocB) override {
627 return Result.alias(LocA, LocB);
628 }
629
630 bool pointsToConstantMemory(const MemoryLocation &Loc,
631 bool OrLocal) override {
632 return Result.pointsToConstantMemory(Loc, OrLocal);
633 }
634
635 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) override {
636 return Result.getArgModRefInfo(CS, ArgIdx);
637 }
638
639 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override {
640 return Result.getModRefBehavior(CS);
641 }
642
643 FunctionModRefBehavior getModRefBehavior(const Function *F) override {
644 return Result.getModRefBehavior(F);
645 }
646
647 ModRefInfo getModRefInfo(ImmutableCallSite CS,
648 const MemoryLocation &Loc) override {
649 return Result.getModRefInfo(CS, Loc);
650 }
651
652 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
653 ImmutableCallSite CS2) override {
654 return Result.getModRefInfo(CS1, CS2);
655 }
656 };
657
658 /// A CRTP-driven "mixin" base class to help implement the function alias
659 /// analysis results concept.
660 ///
661 /// Because of the nature of many alias analysis implementations, they often
662 /// only implement a subset of the interface. This base class will attempt to
663 /// implement the remaining portions of the interface in terms of simpler forms
664 /// of the interface where possible, and otherwise provide conservatively
665 /// correct fallback implementations.
666 ///
667 /// Implementors of an alias analysis should derive from this CRTP, and then
668 /// override specific methods that they wish to customize. There is no need to
669 /// use virtual anywhere, the CRTP base class does static dispatch to the
670 /// derived type passed into it.
671 template class AAResultBase {
672 // Expose some parts of the interface only to the AAResults::Model
673 // for wrapping. Specifically, this allows the model to call our
674 // setAAResults method without exposing it as a fully public API.
675 friend class AAResults::Model;
676
677 /// A pointer to the AAResults object that this AAResult is
678 /// aggregated within. May be null if not aggregated.
679 AAResults *AAR;
680
681 /// Helper to dispatch calls back through the derived type.
682 DerivedT &derived() { return static_cast(*this); }
683
684 /// A setter for the AAResults pointer, which is used to satisfy the
685 /// AAResults::Model contract.
686 void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
687
688 protected:
689 /// This proxy class models a common pattern where we delegate to either the
690 /// top-level \c AAResults aggregation if one is registered, or to the
691 /// current result if none are registered.
692 class AAResultsProxy {
693 AAResults *AAR;
694 DerivedT &CurrentResult;
695
696 public:
697 AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
698 : AAR(AAR), CurrentResult(CurrentResult) {}
699
700 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
701 return AAR ? AAR->alias(LocA, LocB) : CurrentResult.alias(LocA, LocB);
702 }
703
704 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
705 return AAR ? AAR->pointsToConstantMemory(Loc, OrLocal)
706 : CurrentResult.pointsToConstantMemory(Loc, OrLocal);
707 }
708
709 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
710 return AAR ? AAR->getArgModRefInfo(CS, ArgIdx) : CurrentResult.getArgModRefInfo(CS, ArgIdx);
711 }
712
713 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
714 return AAR ? AAR->getModRefBehavior(CS) : CurrentResult.getModRefBehavior(CS);
715 }
716
717 FunctionModRefBehavior getModRefBehavior(const Function *F) {
718 return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
719 }
720
721 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc) {
722 return AAR ? AAR->getModRefInfo(CS, Loc)
723 : CurrentResult.getModRefInfo(CS, Loc);
724 }
725
726 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
727 return AAR ? AAR->getModRefInfo(CS1, CS2) : CurrentResult.getModRefInfo(CS1, CS2);
728 }
729 };
730
731 const TargetLibraryInfo &TLI;
732
733 explicit AAResultBase(const TargetLibraryInfo &TLI) : TLI(TLI) {}
734
735 // Provide all the copy and move constructors so that derived types aren't
736 // constrained.
737 AAResultBase(const AAResultBase &Arg) : TLI(Arg.TLI) {}
738 AAResultBase(AAResultBase &&Arg) : TLI(Arg.TLI) {}
739
740 /// Get a proxy for the best AA result set to query at this time.
741 ///
742 /// When this result is part of a larger aggregation, this will proxy to that
743 /// aggregation. When this result is used in isolation, it will just delegate
744 /// back to the derived class's implementation.
745 AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
746
747 public:
748 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
749 return MayAlias;
750 }
751
752 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
753 return false;
754 }
755
756 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
757 return MRI_ModRef;
758 }
759
760 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
761 if (const Function *F = CS.getCalledFunction())
762 return getBestAAResults().getModRefBehavior(F);
763
764 return FMRB_UnknownModRefBehavior;
765 }
766
767 FunctionModRefBehavior getModRefBehavior(const Function *F) {
768 return FMRB_UnknownModRefBehavior;
769 }
770
771 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
772
773 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
774 };
775
776 /// Synthesize \c ModRefInfo for a call site and memory location by examining
777 /// the general behavior of the call site and any specific information for its
778 /// arguments.
779 ///
780 /// This essentially, delegates across the alias analysis interface to collect
781 /// information which may be enough to (conservatively) fulfill the query.
782 template
783 ModRefInfo AAResultBase::getModRefInfo(ImmutableCallSite CS,
784 const MemoryLocation &Loc) {
785 auto MRB = getBestAAResults().getModRefBehavior(CS);
786 if (MRB == FMRB_DoesNotAccessMemory)
787 return MRI_NoModRef;
788
789 ModRefInfo Mask = MRI_ModRef;
790 if (AAResults::onlyReadsMemory(MRB))
791 Mask = MRI_Ref;
792
793 if (AAResults::onlyAccessesArgPointees(MRB)) {
794 bool DoesAlias = false;
795 ModRefInfo AllArgsMask = MRI_NoModRef;
796 if (AAResults::doesAccessArgPointees(MRB)) {
797 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(),
798 AE = CS.arg_end();
799 AI != AE; ++AI) {
800 const Value *Arg = *AI;
801 if (!Arg->getType()->isPointerTy())
802 continue;
803 unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
804 MemoryLocation ArgLoc = MemoryLocation::getForArgument(CS, ArgIdx, TLI);
805 AliasResult ArgAlias = getBestAAResults().alias(ArgLoc, Loc);
806 if (ArgAlias != NoAlias) {
807 ModRefInfo ArgMask = getBestAAResults().getArgModRefInfo(CS, ArgIdx);
808 DoesAlias = true;
809 AllArgsMask = ModRefInfo(AllArgsMask | ArgMask);
810 }
811 }
812 }
813 if (!DoesAlias)
814 return MRI_NoModRef;
815 Mask = ModRefInfo(Mask & AllArgsMask);
816 }
817
818 // If Loc is a constant memory location, the call definitely could not
819 // modify the memory location.
820 if ((Mask & MRI_Mod) &&
821 getBestAAResults().pointsToConstantMemory(Loc, /*OrLocal*/ false))
822 Mask = ModRefInfo(Mask & ~MRI_Mod);
823
824 return Mask;
825 }
826
827 /// Synthesize \c ModRefInfo for two call sites by examining the general
828 /// behavior of the call site and any specific information for its arguments.
829 ///
830 /// This essentially, delegates across the alias analysis interface to collect
831 /// information which may be enough to (conservatively) fulfill the query.
832 template
833 ModRefInfo AAResultBase::getModRefInfo(ImmutableCallSite CS1,
834 ImmutableCallSite CS2) {
835 // If CS1 or CS2 are readnone, they don't interact.
836 auto CS1B = getBestAAResults().getModRefBehavior(CS1);
837 if (CS1B == FMRB_DoesNotAccessMemory)
838 return MRI_NoModRef;
839
840 auto CS2B = getBestAAResults().getModRefBehavior(CS2);
841 if (CS2B == FMRB_DoesNotAccessMemory)
842 return MRI_NoModRef;
843
844 // If they both only read from memory, there is no dependence.
845 if (AAResults::onlyReadsMemory(CS1B) && AAResults::onlyReadsMemory(CS2B))
846 return MRI_NoModRef;
847
848 ModRefInfo Mask = MRI_ModRef;
849
850 // If CS1 only reads memory, the only dependence on CS2 can be
851 // from CS1 reading memory written by CS2.
852 if (AAResults::onlyReadsMemory(CS1B))
853 Mask = ModRefInfo(Mask & MRI_Ref);
854
855 // If CS2 only access memory through arguments, accumulate the mod/ref
856 // information from CS1's references to the memory referenced by
857 // CS2's arguments.
858 if (AAResults::onlyAccessesArgPointees(CS2B)) {
859 ModRefInfo R = MRI_NoModRef;
860 if (AAResults::doesAccessArgPointees(CS2B)) {
861 for (ImmutableCallSite::arg_iterator I = CS2.arg_begin(),
862 E = CS2.arg_end();
863 I != E; ++I) {
864 const Value *Arg = *I;
865 if (!Arg->getType()->isPointerTy())
866 continue;
867 unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
868 auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, TLI);
869
870 // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence
871 // of CS1 on that location is the inverse.
872 ModRefInfo ArgMask =
873 getBestAAResults().getArgModRefInfo(CS2, CS2ArgIdx);
874 if (ArgMask == MRI_Mod)
875 ArgMask = MRI_ModRef;
876 else if (ArgMask == MRI_Ref)
877 ArgMask = MRI_Mod;
878
879 ArgMask = ModRefInfo(ArgMask &
880 getBestAAResults().getModRefInfo(CS1, CS2ArgLoc));
881
882 R = ModRefInfo((R | ArgMask) & Mask);
883 if (R == Mask)
884 break;
885 }
886 }
887 return R;
888 }
889
890 // If CS1 only accesses memory through arguments, check if CS2 references
891 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
892 if (AAResults::onlyAccessesArgPointees(CS1B)) {
893 ModRefInfo R = MRI_NoModRef;
894 if (AAResults::doesAccessArgPointees(CS1B)) {
895 for (ImmutableCallSite::arg_iterator I = CS1.arg_begin(),
896 E = CS1.arg_end();
897 I != E; ++I) {
898 const Value *Arg = *I;
899 if (!Arg->getType()->isPointerTy())
900 continue;
901 unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
902 auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, TLI);
903
904 // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
905 // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
906 // might Ref, then we care only about a Mod by CS2.
907 ModRefInfo ArgMask = getBestAAResults().getArgModRefInfo(CS1, CS1ArgIdx);
908 ModRefInfo ArgR = getBestAAResults().getModRefInfo(CS2, CS1ArgLoc);
909 if (((ArgMask & MRI_Mod) != MRI_NoModRef &&
910 (ArgR & MRI_ModRef) != MRI_NoModRef) ||
911 ((ArgMask & MRI_Ref) != MRI_NoModRef &&
912 (ArgR & MRI_Mod) != MRI_NoModRef))
913 R = ModRefInfo((R | ArgMask) & Mask);
914
915 if (R == Mask)
916 break;
917 }
918 }
919 return R;
920 }
921
922 return Mask;
923 }
545924
546925 /// isNoAliasCall - Return true if this pointer is returned by a noalias
547926 /// function.
567946 /// IdentifiedObjects.
568947 bool isIdentifiedFunctionLocal(const Value *V);
569948
949 /// A manager for alias analyses.
950 ///
951 /// This class can have analyses registered with it and when run, it will run
952 /// all of them and aggregate their results into single AA results interface
953 /// that dispatches across all of the alias analysis results available.
954 ///
955 /// Note that the order in which analyses are registered is very significant.
956 /// That is the order in which the results will be aggregated and queried.
957 ///
958 /// This manager effectively wraps the AnalysisManager for registering alias
959 /// analyses. When you register your alias analysis with this manager, it will
960 /// ensure the analysis itself is registered with its AnalysisManager.
961 class AAManager {
962 public:
963 typedef AAResults Result;
964
965 // This type hase value semantics. We have to spell these out because MSVC
966 // won't synthesize them.
967 AAManager() {}
968 AAManager(AAManager &&Arg)
969 : FunctionResultGetters(std::move(Arg.FunctionResultGetters)) {}
970 AAManager(const AAManager &Arg)
971 : FunctionResultGetters(Arg.FunctionResultGetters) {}
972 AAManager &operator=(AAManager &&RHS) {
973 FunctionResultGetters = std::move(RHS.FunctionResultGetters);
974 return *this;
975 }
976 AAManager &operator=(const AAManager &RHS) {
977 FunctionResultGetters = RHS.FunctionResultGetters;
978 return *this;
979 }
980
981 /// Register a specific AA result.
982 template void registerFunctionAnalysis() {
983 FunctionResultGetters.push_back(&getFunctionAAResultImpl);
984 }
985
986 Result run(Function &F, AnalysisManager &AM) {
987 Result R;
988 for (auto &Getter : FunctionResultGetters)
989 (*Getter)(F, AM, R);
990 return R;
991 }
992
993 private:
994 SmallVector &AM,
995 AAResults &AAResults),
996 4> FunctionResultGetters;
997
998 template
999 static void getFunctionAAResultImpl(Function &F,
1000 AnalysisManager &AM,
1001 AAResults &AAResults) {
1002 AAResults.addAAResult(AM.template getResult(F));
1003 }
1004 };
1005
1006 /// A wrapper pass to provide the legacy pass manager access to a suitably
1007 /// prepared AAResults object.
1008 class AAResultsWrapperPass : public FunctionPass {
1009 std::unique_ptr AAR;
1010
1011 public:
1012 static char ID;
1013
1014 AAResultsWrapperPass();
1015
1016 AAResults &getAAResults() { return *AAR; }
1017 const AAResults &getAAResults() const { return *AAR; }
1018
1019 bool runOnFunction(Function &F) override;
1020
1021 void getAnalysisUsage(AnalysisUsage &AU) const override;
1022 };
1023
1024 FunctionPass *createAAResultsWrapperPass();
1025
1026 /// A helper for the legacy pass manager to create a \c AAResults
1027 /// object populated to the best of our ability for a particular function when
1028 /// inside of a \c ModulePass or a \c CallGraphSCCPass.
1029 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
1030
5701031 } // End llvm namespace
5711032
5721033 #endif
+0
-65
include/llvm/Analysis/AliasAnalysisCounter.h less more
None //===- AliasAnalysisCounter.h - Alias Analysis Query Counter ----*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This declares an alias analysis which counts and prints queries made
10 /// through it. By inserting this between other AAs you can track when specific
11 /// layers of LLVM's AA get queried.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_ALIASANALYSISCOUNTER_H
16 #define LLVM_ANALYSIS_ALIASANALYSISCOUNTER_H
17
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Pass.h"
21
22 namespace llvm {
23
24 class AliasAnalysisCounter : public ModulePass, public AliasAnalysis {
25 unsigned No, May, Partial, Must;
26 unsigned NoMR, JustRef, JustMod, MR;
27 Module *M;
28
29 public:
30 static char ID; // Class identification, replacement for typeinfo
31
32 AliasAnalysisCounter();
33 ~AliasAnalysisCounter() override;
34
35 bool runOnModule(Module &M) override;
36
37 void getAnalysisUsage(AnalysisUsage &AU) const override;
38
39 /// getAdjustedAnalysisPointer - This method is used when a pass implements
40 /// an analysis interface through multiple inheritance. If needed, it
41 /// should override this to adjust the this pointer as needed for the
42 /// specified pass info.
43 void *getAdjustedAnalysisPointer(AnalysisID PI) override;
44
45 // Forwarding functions: just delegate to a real AA implementation, counting
46 // the number of responses...
47 AliasResult alias(const MemoryLocation &LocA,
48 const MemoryLocation &LocB) override;
49
50 using AliasAnalysis::getModRefInfo;
51 ModRefInfo getModRefInfo(ImmutableCallSite CS,
52 const MemoryLocation &Loc) override;
53 };
54
55 //===--------------------------------------------------------------------===//
56 //
57 // createAliasAnalysisCounterPass - This pass counts alias queries and how the
58 // alias analysis implementation responds.
59 //
60 ModulePass *createAliasAnalysisCounterPass();
61
62 }
63
64 #endif
1919 #include "llvm/ADT/DenseMap.h"
2020 #include "llvm/ADT/ilist.h"
2121 #include "llvm/ADT/ilist_node.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
2223 #include "llvm/IR/Metadata.h"
2324 #include "llvm/IR/ValueHandle.h"
2425 #include
2526
2627 namespace llvm {
2728
28 class AliasAnalysis;
2929 class LoadInst;
3030 class StoreInst;
3131 class VAArgInst;
2222 #include "llvm/IR/Instruction.h"
2323 #include "llvm/IR/LLVMContext.h"
2424 #include "llvm/IR/Module.h"
25 #include "llvm/Pass.h"
25 #include "llvm/IR/PassManager.h"
2626 #include "llvm/Support/ErrorHandling.h"
2727
2828 namespace llvm {
29
30 /// This is the primary alias analysis implementation.
31 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
32 static char ID; // Class identification, replacement for typeinfo
29 class AssumptionCache;
30 class DominatorTree;
31 class LoopInfo;
32
33 /// This is the AA result object for the basic, local, and stateless alias
34 /// analysis. It implements the AA query interface in an entirely stateless
35 /// manner. As one consequence, it is never invalidated. While it does retain
36 /// some storage, that is used as an optimization and not to preserve
37 /// information from query to query.
38 class BasicAAResult : public AAResultBase {
39 friend AAResultBase;
40
41 const DataLayout &DL;
42 AssumptionCache ∾
43 DominatorTree *DT;
44 LoopInfo *LI;
3345
3446 #ifndef NDEBUG
3547 static const Function *getParent(const Value *V) {
5163 }
5264 #endif
5365
54 BasicAliasAnalysis() : ImmutablePass(ID) {
55 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
56 }
57
58 bool doInitialization(Module &M) override;
59
60 void getAnalysisUsage(AnalysisUsage &AU) const override {
61 AU.addRequired();
62 AU.addRequired();
63 AU.addRequired();
64 }
65
66 AliasResult alias(const MemoryLocation &LocA,
67 const MemoryLocation &LocB) override {
68 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
66 public:
67 BasicAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI,
68 AssumptionCache &AC, DominatorTree *DT = nullptr,
69 LoopInfo *LI = nullptr)
70 : AAResultBase(TLI), DL(DL), AC(AC), DT(DT), LI(LI) {}
71
72 BasicAAResult(const BasicAAResult &Arg)
73 : AAResultBase(Arg), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI) {}
74 BasicAAResult(BasicAAResult &&Arg)
75 : AAResultBase(std::move(Arg)), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT),
76 LI(Arg.LI) {}
77
78 /// Handle invalidation events from the new pass manager.
79 ///
80 /// By definition, this result is stateless and so remains valid.
81 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
82
83 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
6984 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
7085 "BasicAliasAnalysis doesn't support interprocedural queries.");
86
87 // If we have a directly cached entry for these locations, we have recursed
88 // through this once, so just return the cached results. Notably, when this
89 // happens, we don't clear the cache.
90 auto CacheIt = AliasCache.find(LocPair(LocA, LocB));
91 if (CacheIt != AliasCache.end())
92 return CacheIt->second;
93
7194 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
7295 LocB.Size, LocB.AATags);
7396 // AliasCache rarely has more than 1 or 2 elements, always use
79102 return Alias;
80103 }
81104
82 ModRefInfo getModRefInfo(ImmutableCallSite CS,
83 const MemoryLocation &Loc) override;
84
85 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
86 ImmutableCallSite CS2) override;
105 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
106
107 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
87108
88109 /// Chases pointers until we find a (constant global) or not.
89 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) override;
110 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
90111
91112 /// Get the location associated with a pointer argument of a callsite.
92 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) override;
113 ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
93114
94115 /// Returns the behavior when calling the given call site.
95 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
116 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
96117
97118 /// Returns the behavior when calling the given function. For use when the
98119 /// call site is not known.
99 FunctionModRefBehavior getModRefBehavior(const Function *F) override;
100
101 /// This method is used when a pass implements an analysis interface through
102 /// multiple inheritance. If needed, it should override this to adjust the
103 /// this pointer as needed for the specified pass info.
104 void *getAdjustedAnalysisPointer(const void *ID) override {
105 if (ID == &AliasAnalysis::ID)
106 return (AliasAnalysis *)this;
107 return this;
108 }
120 FunctionModRefBehavior getModRefBehavior(const Function *F);
109121
110122 private:
111123 // A linear transformation of a Value; this class represents ZExt(SExt(V,
180192 bool
181193 constantOffsetHeuristic(const SmallVectorImpl &VarIndices,
182194 uint64_t V1Size, uint64_t V2Size, int64_t BaseOffset,
183 const DataLayout *DL, AssumptionCache *AC,
184 DominatorTree *DT);
195 AssumptionCache *AC, DominatorTree *DT);
185196
186197 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
187198
205216 const Value *V2, uint64_t V2Size, AAMDNodes V2AATag);
206217 };
207218
208 //===--------------------------------------------------------------------===//
209 //
210 // createBasicAliasAnalysisPass - This pass implements the stateless alias
211 // analysis.
212 //
213 ImmutablePass *createBasicAliasAnalysisPass();
214
219 /// Analysis pass providing a never-invalidated alias analysis result.
220 class BasicAA {
221 public:
222 typedef BasicAAResult Result;
223
224 /// \brief Opaque, unique identifier for this analysis pass.
225 static void *ID() { return (void *)&PassID; }
226
227 BasicAAResult run(Function &F, AnalysisManager *AM);
228
229 /// \brief Provide access to a name for this pass for debugging purposes.
230 static StringRef name() { return "BasicAliasAnalysis"; }
231
232 private:
233 static char PassID;
234 };
235
236 /// Legacy wrapper pass to provide the BasicAAResult object.
237 class BasicAAWrapperPass : public FunctionPass {
238 std::unique_ptr Result;
239
240 virtual void anchor();
241
242 public:
243 static char ID;
244
245 BasicAAWrapperPass() : FunctionPass(ID) {}
246
247 BasicAAResult &getResult() { return *Result; }
248 const BasicAAResult &getResult() const { return *Result; }
249
250 bool runOnFunction(Function &F) override;
251 void getAnalysisUsage(AnalysisUsage &AU) const override;
252 };
253
254 FunctionPass *createBasicAAWrapperPass();
255
256 /// A helper for the legacy pass manager to create a \c BasicAAResult object
257 /// populated to the best of our ability for a particular function when inside
258 /// of a \c ModulePass or a \c CallGraphSCCPass.
259 BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
215260 }
216261
217262 #endif
2525
2626 namespace llvm {
2727
28 class CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
28 class CFLAAResult : public AAResultBase {
29 friend AAResultBase;
30
2931 struct FunctionInfo;
3032
31 struct FunctionHandle final : public CallbackVH {
32 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
33 : CallbackVH(Fn), CFLAA(CFLAA) {
34 assert(Fn != nullptr);
35 assert(CFLAA != nullptr);
36 }
33 public:
34 explicit CFLAAResult(const TargetLibraryInfo &TLI);
35 CFLAAResult(CFLAAResult &&Arg);
3736
38 void deleted() override { removeSelfFromCache(); }
39 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
40
41 private:
42 CFLAliasAnalysis *CFLAA;
43
44 void removeSelfFromCache() {
45 assert(CFLAA != nullptr);
46 auto *Val = getValPtr();
47 CFLAA->evict(cast(Val));
48 setValPtr(nullptr);
49 }
50 };
51
52 /// \brief Cached mapping of Functions to their StratifiedSets.
53 /// If a function's sets are currently being built, it is marked
54 /// in the cache as an Optional without a value. This way, if we
55 /// have any kind of recursion, it is discernable from a function
56 /// that simply has empty sets.
57 DenseMap> Cache;
58 std::forward_list Handles;
59
60 public:
61 static char ID;
62
63 CFLAliasAnalysis();
64 ~CFLAliasAnalysis() override;
65
66 void getAnalysisUsage(AnalysisUsage &AU) const override;
67
68 void *getAdjustedAnalysisPointer(const void *ID) override;
37 /// Handle invalidation events from the new pass manager.
38 ///
39 /// By definition, this result is stateless and so remains valid.
40 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
6941
7042 /// \brief Inserts the given Function into the cache.
7143 void scan(Function *Fn);
7850
7951 AliasResult query(const MemoryLocation &LocA, const MemoryLocation &LocB);
8052
81 AliasResult alias(const MemoryLocation &LocA,
82 const MemoryLocation &LocB) override {
53 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
8354 if (LocA.Ptr == LocB.Ptr) {
8455 if (LocA.Size == LocB.Size) {
8556 return MustAlias;
9566 // one Value tied to a Function, and neither GlobalValues nor ConstantExprs
9667 // are.
9768 if (isa(LocA.Ptr) && isa(LocB.Ptr)) {
98 return AliasAnalysis::alias(LocA, LocB);
69 return AAResultBase::alias(LocA, LocB);
9970 }
10071
10172 AliasResult QueryResult = query(LocA, LocB);
10273 if (QueryResult == MayAlias)
103 return AliasAnalysis::alias(LocA, LocB);
74 return AAResultBase::alias(LocA, LocB);
10475
10576 return QueryResult;
10677 }
10778
108 bool doInitialization(Module &M) override;
79 private:
80 struct FunctionHandle final : public CallbackVH {
81 FunctionHandle(Function *Fn, CFLAAResult *Result)
82 : CallbackVH(Fn), Result(Result) {
83 assert(Fn != nullptr);
84 assert(Result != nullptr);
85 }
86
87 void deleted() override { removeSelfFromCache(); }
88 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
89
90 private:
91 CFLAAResult *Result;
92
93 void removeSelfFromCache() {
94 assert(Result != nullptr);
95 auto *Val = getValPtr();
96 Result->evict(cast(Val));
97 setValPtr(nullptr);
98 }
99 };
100
101 /// \brief Cached mapping of Functions to their StratifiedSets.
102 /// If a function's sets are currently being built, it is marked
103 /// in the cache as an Optional without a value. This way, if we
104 /// have any kind of recursion, it is discernable from a function
105 /// that simply has empty sets.
106 DenseMap> Cache;
107 std::forward_list Handles;
108
109 FunctionInfo buildSetsFrom(Function *F);
110 };
111
112 /// Analysis pass providing a never-invalidated alias analysis result.
113 ///
114 /// FIXME: We really should refactor CFL to use the analysis more heavily, and
115 /// in particular to leverage invalidation to trigger re-computation of sets.
116 class CFLAA {
117 public:
118 typedef CFLAAResult Result;
119
120 /// \brief Opaque, unique identifier for this analysis pass.
121 static void *ID() { return (void *)&PassID; }
122
123 CFLAAResult run(Function &F, AnalysisManager *AM);
124
125 /// \brief Provide access to a name for this pass for debugging purposes.
126 static StringRef name() { return "CFLAA"; }
109127
110128 private:
111 FunctionInfo buildSetsFrom(Function *F);
129 static char PassID;
130 };
131
132 /// Legacy wrapper pass to provide the CFLAAResult object.
133 class CFLAAWrapperPass : public ImmutablePass {
134 std::unique_ptr Result;
135
136 public:
137 static char ID;
138
139 CFLAAWrapperPass();
140
141 CFLAAResult &getResult() { return *Result; }
142 const CFLAAResult &getResult() const { return *Result; }
143
144 bool doInitialization(Module &M) override;
145 bool doFinalization(Module &M) override;
146 void getAnalysisUsage(AnalysisUsage &AU) const override;
112147 };
113148
114149 //===--------------------------------------------------------------------===//
115150 //
116 // createCFLAliasAnalysisPass - This pass implements a set-based approach to
151 // createCFLAAWrapperPass - This pass implements a set-based approach to
117152 // alias analysis.
118153 //
119 ImmutablePass *createCFLAliasAnalysisPass();
120
154 ImmutablePass *createCFLAAWrapperPass();
121155 }
122156
123157 #endif
4141
4242 #include "llvm/ADT/SmallBitVector.h"
4343 #include "llvm/ADT/ArrayRef.h"
44 #include "llvm/Analysis/AliasAnalysis.h"
4445 #include "llvm/IR/Instructions.h"
4546 #include "llvm/Pass.h"
4647
4748 namespace llvm {
48 class AliasAnalysis;
4949 class Loop;
5050 class LoopInfo;
5151 class ScalarEvolution;
2424
2525 namespace llvm {
2626
27 /// GlobalsModRef - The actual analysis pass.
28 class GlobalsModRef : public ModulePass, public AliasAnalysis {
27 /// An alias analysis result set for globals.
28 ///
29 /// This focuses on handling aliasing properties of globals and interprocedural
30 /// function call mod/ref information.
31 class GlobalsAAResult : public AAResultBase {
32 friend AAResultBase;
33
2934 class FunctionInfo;
35
36 const DataLayout &DL;
3037
3138 /// The globals that do not have their addresses taken.
3239 SmallPtrSet NonAddressTakenGlobals;
4451
4552 /// Handle to clear this analysis on deletion of values.
4653 struct DeletionCallbackHandle final : CallbackVH {
47 GlobalsModRef &GMR;
54 GlobalsAAResult &GAR;
4855 std::list::iterator I;
4956
50 DeletionCallbackHandle(GlobalsModRef &GMR, Value *V)
51 : CallbackVH(V), GMR(GMR) {}
57 DeletionCallbackHandle(GlobalsAAResult &GAR, Value *V)
58 : CallbackVH(V), GAR(GAR) {}
5259
5360 void deleted() override;
5461 };
5966 /// could perform to the memory utilization here if this becomes a problem.
6067 std::list Handles;
6168
69 explicit GlobalsAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI);
70
6271 public:
63 static char ID;
64 GlobalsModRef();
72 GlobalsAAResult(GlobalsAAResult &&Arg);
6573
66 bool runOnModule(Module &M) override {
67 InitializeAliasAnalysis(this, &M.getDataLayout());
68
69 // Find non-addr taken globals.
70 AnalyzeGlobals(M);
71
72 // Propagate on CG.
73 AnalyzeCallGraph(getAnalysis().getCallGraph(), M);
74 return false;
75 }
76
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 AliasAnalysis::getAnalysisUsage(AU);
79 AU.addRequired();
80 AU.setPreservesAll(); // Does not transform code
81 }
82
83 /// getAdjustedAnalysisPointer - This method is used when a pass implements
84 /// an analysis interface through multiple inheritance. If needed, it
85 /// should override this to adjust the this pointer as needed for the
86 /// specified pass info.
87 void *getAdjustedAnalysisPointer(AnalysisID PI) override {
88 if (PI == &AliasAnalysis::ID)
89 return (AliasAnalysis *)this;
90 return this;
91 }
74 static GlobalsAAResult analyzeModule(Module &M, const TargetLibraryInfo &TLI,
75 CallGraph &CG);
9276
9377 //------------------------------------------------
9478 // Implement the AliasAnalysis API
9579 //
96 AliasResult alias(const MemoryLocation &LocA,
97 const MemoryLocation &LocB) override;
80 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
9881
99 using AliasAnalysis::getModRefInfo;
100 ModRefInfo getModRefInfo(ImmutableCallSite CS,
101 const MemoryLocation &Loc) override;
82 using AAResultBase::getModRefInfo;
83 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
10284
10385 /// getModRefBehavior - Return the behavior of the specified function if
10486 /// called from the specified call site. The call site may be null in which
10587 /// case the most generic behavior of this function should be returned.
106 FunctionModRefBehavior getModRefBehavior(const Function *F) override;
88 FunctionModRefBehavior getModRefBehavior(const Function *F);
10789
10890 /// getModRefBehavior - Return the behavior of the specified function if
10991 /// called from the specified call site. The call site may be null in which
11092 /// case the most generic behavior of this function should be returned.
111 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
93 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
11294
11395 private:
11496 FunctionInfo *getFunctionInfo(const Function *F);
124106 bool isNonEscapingGlobalNoAlias(const GlobalValue *GV, const Value *V);
125107 };
126108
109 /// Analysis pass providing a never-invalidated alias analysis result.
110 class GlobalsAA {
111 public:
112 typedef GlobalsAAResult Result;
113
114 /// \brief Opaque, unique identifier for this analysis pass.
115 static void *ID() { return (void *)&PassID; }
116
117 GlobalsAAResult run(Module &M, AnalysisManager *AM);
118
119 /// \brief Provide access to a name for this pass for debugging purposes.
120 static StringRef name() { return "GlobalsAA"; }
121
122 private:
123 static char PassID;
124 };
125
126 /// Legacy wrapper pass to provide the GlobalsAAResult object.
127 class GlobalsAAWrapperPass : public ModulePass {
128 std::unique_ptr Result;
129
130 public:
131 static char ID;
132
133 GlobalsAAWrapperPass();
134
135 GlobalsAAResult &getResult() { return *Result; }
136 const GlobalsAAResult &getResult() const { return *Result; }
137
138 bool runOnModule(Module &M) override;
139 bool doFinalization(Module &M) override;
140 void getAnalysisUsage(AnalysisUsage &AU) const override;
141 };
142
127143 //===--------------------------------------------------------------------===//
128144 //
129 // createGlobalsModRefPass - This pass provides alias and mod/ref info for
145 // createGlobalsAAWrapperPass - This pass provides alias and mod/ref info for
130146 // global values that do not have their addresses taken.
131147 //
132 Pass *createGlobalsModRefPass();
133
148 ModulePass *createGlobalsAAWrapperPass();
134149 }
135150
136151 #endif
1313 #ifndef LLVM_ANALYSIS_LOADS_H
1414 #define LLVM_ANALYSIS_LOADS_H
1515
16 #include "llvm/Analysis/AliasAnalysis.h"
1617 #include "llvm/IR/BasicBlock.h"
1718
1819 namespace llvm {
1920
20 class AliasAnalysis;
2121 class DataLayout;
2222 class MDNode;
2323
2828
2929 class Value;
3030 class DataLayout;
31 class AliasAnalysis;
3231 class ScalarEvolution;
3332 class Loop;
3433 class SCEV;
2727 class FunctionPass;
2828 class Instruction;
2929 class CallSite;
30 class AliasAnalysis;
3130 class AssumptionCache;
3231 class MemoryDependenceAnalysis;
3332 class PredIteratorCache;
2323 #define LLVM_ANALYSIS_OBJCARCALIASANALYSIS_H
2424
2525 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
2627 #include "llvm/Pass.h"
2728
2829 namespace llvm {
3435 /// TODO: This class could be generalized to know about other ObjC-specific
3536 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
3637 /// even though their offsets are dynamic.
37 class ObjCARCAliasAnalysis : public ImmutablePass, public AliasAnalysis {
38 class ObjCARCAAResult : public AAResultBase {
39 friend AAResultBase;
40
41 const DataLayout &DL;
42
3843 public:
39 static char ID; // Class identification, replacement for typeinfo
40 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
41 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
42 }
44 explicit ObjCARCAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI)
45 : AAResultBase(TLI), DL(DL) {}
46 ObjCARCAAResult(ObjCARCAAResult &&Arg)
47 : AAResultBase(std::move(Arg)), DL(Arg.DL) {}
48
49 /// Handle invalidation events from the new pass manager.
50 ///
51 /// By definition, this result is stateless and so remains valid.
52 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
53
54 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
55 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
56
57 using AAResultBase::getModRefBehavior;
58 FunctionModRefBehavior getModRefBehavior(const Function *F);
59
60 using AAResultBase::getModRefInfo;
61 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
62 };
63
64 /// Analysis pass providing a never-invalidated alias analysis result.
65 class ObjCARCAA {
66 public:
67 typedef ObjCARCAAResult Result;
68
69 /// \brief Opaque, unique identifier for this analysis pass.
70 static void *ID() { return (void *)&PassID; }
71
72 ObjCARCAAResult run(Function &F, AnalysisManager *AM);
73
74 /// \brief Provide access to a name for this pass for debugging purposes.
75 static StringRef name() { return "ObjCARCAA"; }
4376
4477 private:
78 static char PassID;
79 };
80
81 /// Legacy wrapper pass to provide the ObjCARCAAResult object.
82 class ObjCARCAAWrapperPass : public ImmutablePass {
83 std::unique_ptr Result;
84
85 public:
86 static char ID;
87
88 ObjCARCAAWrapperPass();
89
90 ObjCARCAAResult &getResult() { return *Result; }
91 const ObjCARCAAResult &getResult() const { return *Result; }
92
4593 bool doInitialization(Module &M) override;
46
47 /// This method is used when a pass implements an analysis interface through
48 /// multiple inheritance. If needed, it should override this to adjust the
49 /// this pointer as needed for the specified pass info.
50 void *getAdjustedAnalysisPointer(const void *PI) override {
51 if (PI == &AliasAnalysis::ID)
52 return static_cast(this);
53 return this;
54 }
55
94 bool doFinalization(Module &M) override;
5695 void getAnalysisUsage(AnalysisUsage &AU) const override;
57 AliasResult alias(const MemoryLocation &LocA,
58 const MemoryLocation &LocB) override;
59 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) override;
60 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
61 FunctionModRefBehavior getModRefBehavior(const Function *F) override;
62 ModRefInfo getModRefInfo(ImmutableCallSite CS,
63 const MemoryLocation &Loc) override;
64 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
65 ImmutableCallSite CS2) override;
6696 };
6797
6898 } // namespace objcarc
3131
3232 //===--------------------------------------------------------------------===//
3333 //
34 // createNoAAPass - This pass implements a "I don't know" alias analysis.
35 //
36 ImmutablePass *createNoAAPass();
37
38 //===--------------------------------------------------------------------===//
39 //
40 // createObjCARCAliasAnalysisPass - This pass implements ObjC-ARC-based
34 // createObjCARCAAWrapperPass - This pass implements ObjC-ARC-based
4135 // alias analysis.
4236 //
43 ImmutablePass *createObjCARCAliasAnalysisPass();
37 ImmutablePass *createObjCARCAAWrapperPass();
4438
4539 FunctionPass *createPAEvalPass();
4640
2323
2424 /// A simple alias analysis implementation that uses ScalarEvolution to answer
2525 /// queries.
26 class ScalarEvolutionAliasAnalysis : public FunctionPass, public AliasAnalysis {
27 ScalarEvolution *SE;
26 class SCEVAAResult : public AAResultBase {
27 ScalarEvolution &SE;
2828
2929 public:
30 static char ID; // Class identification, replacement for typeinfo
31 ScalarEvolutionAliasAnalysis() : FunctionPass(ID), SE(nullptr) {
32 initializeScalarEvolutionAliasAnalysisPass(
33 *PassRegistry::getPassRegistry());
34 }
30 explicit SCEVAAResult(const TargetLibraryInfo &TLI, ScalarEvolution &SE)
31 : AAResultBase(TLI), SE(SE) {}
32 SCEVAAResult(SCEVAAResult &&Arg) : AAResultBase(std::move(Arg)), SE(Arg.SE) {}
3533
36 /// This method is used when a pass implements an analysis interface through
37 /// multiple inheritance.
38 ///
39 /// If needed, it should override this to adjust the this pointer as needed
40 /// for the specified pass info.
41 void *getAdjustedAnalysisPointer(AnalysisID PI) override {
42 if (PI == &AliasAnalysis::ID)
43 return (AliasAnalysis *)this;
44 return this;
45 }
34 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
4635
4736 private:
48 void getAnalysisUsage(AnalysisUsage &AU) const override;
49 bool runOnFunction(Function &F) override;
50 AliasResult alias(const MemoryLocation &LocA,
51 const MemoryLocation &LocB) override;
52
5337 Value *GetBaseValue(const SCEV *S);
5438 };
5539
56 /// Creates an instance of \c ScalarEvolutionAliasAnalysis.
57 FunctionPass *createScalarEvolutionAliasAnalysisPass();
40 /// Analysis pass providing a never-invalidated alias analysis result.
41 class SCEVAA {
42 public:
43 typedef SCEVAAResult Result;
44
45 /// \brief Opaque, unique identifier for this analysis pass.
46 static void *ID() { return (void *)&PassID; }
47
48 SCEVAAResult run(Function &F, AnalysisManager *AM);
49
50 /// \brief Provide access to a name for this pass for debugging purposes.
51 static StringRef name() { return "SCEVAA"; }
52
53 private:
54 static char PassID;
55 };
56
57 /// Legacy wrapper pass to provide the SCEVAAResult object.
58 class SCEVAAWrapperPass : public FunctionPass {
59 std::unique_ptr Result;
60
61 public:
62 static char ID;
63
64 SCEVAAWrapperPass();
65
66 SCEVAAResult &getResult() { return *Result; }
67 const SCEVAAResult &getResult() const { return *Result; }
68
69 bool runOnFunction(Function &F) override;
70 void getAnalysisUsage(AnalysisUsage &AU) const override;
71 };
72
73 /// Creates an instance of \c SCEVAAWrapperPass.
74 FunctionPass *createSCEVAAWrapperPass();
5875
5976 }
6077
2121
2222 namespace llvm {
2323
24 /// ScopedNoAliasAA - This is a simple alias analysis
25 /// implementation that uses scoped-noalias metadata to answer queries.
26 class ScopedNoAliasAA : public ImmutablePass, public AliasAnalysis {
24 /// A simple AA result which uses scoped-noalias metadata to answer queries.
25 class ScopedNoAliasAAResult : public AAResultBase {
26 friend AAResultBase;
27
2728 public:
28 static char ID; // Class identification, replacement for typeinfo
29 ScopedNoAliasAA() : ImmutablePass(ID) {
30 initializeScopedNoAliasAAPass(*PassRegistry::getPassRegistry());
31 }
29 explicit ScopedNoAliasAAResult(const TargetLibraryInfo &TLI)
30 : AAResultBase(TLI) {}
31 ScopedNoAliasAAResult(ScopedNoAliasAAResult &&Arg)
32 : AAResultBase(std::move(Arg)) {}
3233
33 bool doInitialization(Module &M) override;
34 /// Handle invalidation events from the new pass manager.
35 ///
36 /// By definition, this result is stateless and so remains valid.
37 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
3438
35 /// getAdjustedAnalysisPointer - This method is used when a pass implements
36 /// an analysis interface through multiple inheritance. If needed, it
37 /// should override this to adjust the this pointer as needed for the
38 /// specified pass info.
39 void *getAdjustedAnalysisPointer(const void *PI) override {
40 if (PI == &AliasAnalysis::ID)
41 return (AliasAnalysis *)this;
42 return this;
43 }
39 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
40 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
41 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
4442
45 protected:
43 private:
4644 bool mayAliasInScopes(const MDNode *Scopes, const MDNode *NoAlias) const;
4745 void collectMDInDomain(const MDNode *List, const MDNode *Domain,
4846 SmallPtrSetImpl &Nodes) const;
47 };
48
49 /// Analysis pass providing a never-invalidated alias analysis result.
50 class ScopedNoAliasAA {
51 public:
52 typedef ScopedNoAliasAAResult Result;
53
54 /// \brief Opaque, unique identifier for this analysis pass.
55 static void *ID() { return (void *)&PassID; }
56
57 ScopedNoAliasAAResult run(Function &F, AnalysisManager *AM);
58
59 /// \brief Provide access to a name for this pass for debugging purposes.
60 static StringRef name() { return "ScopedNoAliasAA"; }
4961
5062 private:
63 static char PassID;
64 };
65
66 /// Legacy wrapper pass to provide the ScopedNoAliasAAResult object.
67 class ScopedNoAliasAAWrapperPass : public ImmutablePass {
68 std::unique_ptr Result;
69
70 public:
71 static char ID;
72
73 ScopedNoAliasAAWrapperPass();
74
75 ScopedNoAliasAAResult &getResult() { return *Result; }
76 const ScopedNoAliasAAResult &getResult() const { return *Result; }
77
78 bool doInitialization(Module &M) override;
79 bool doFinalization(Module &M) override;
5180 void getAnalysisUsage(AnalysisUsage &AU) const override;
52 AliasResult alias(const MemoryLocation &LocA,
53 const MemoryLocation &LocB) override;
54 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) override;
55 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
56 FunctionModRefBehavior getModRefBehavior(const Function *F) override;
57 ModRefInfo getModRefInfo(ImmutableCallSite CS,
58 const MemoryLocation &Loc) override;
59 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
60 ImmutableCallSite CS2) override;
6181 };
6282
6383 //===--------------------------------------------------------------------===//
6484 //
65 // createScopedNoAliasAAPass - This pass implements metadata-based
85 // createScopedNoAliasAAWrapperPass - This pass implements metadata-based
6686 // scoped noalias analysis.
6787 //
68 ImmutablePass *createScopedNoAliasAAPass();
69
88 ImmutablePass *createScopedNoAliasAAWrapperPass();
7089 }
7190
7291 #endif
2121
2222 namespace llvm {
2323
24 /// TypeBasedAliasAnalysis - This is a simple alias analysis
25 /// implementation that uses TypeBased to answer queries.
26 class TypeBasedAliasAnalysis : public ImmutablePass, public AliasAnalysis {
24 /// A simple AA result that uses TBAA metadata to answer queries.
25 class TypeBasedAAResult : public AAResultBase {
26 friend AAResultBase;
27
2728 public:
28 static char ID; // Class identification, replacement for typeinfo
29 TypeBasedAliasAnalysis() : ImmutablePass(ID) {
30 initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
31 }
29 explicit TypeBasedAAResult(const TargetLibraryInfo &TLI)
30 : AAResultBase(TLI) {}
31 TypeBasedAAResult(TypeBasedAAResult &&Arg) : AAResultBase(std::move(Arg)) {}
32
33 /// Handle invalidation events from the new pass manager.
34 ///
35 /// By definition, this result is stateless and so remains valid.
36 bool invalidate(Function &, const PreservedAnalyses &) { return false; }
37
38 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
39 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
40 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
41 FunctionModRefBehavior getModRefBehavior(const Function *F);
42 ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
43 ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
44
45 private:
46 bool Aliases(const MDNode *A, const MDNode *B) const;
47 bool PathAliases(const MDNode *A, const MDNode *B) const;
48 };
49
50 /// Analysis pass providing a never-invalidated alias analysis result.
51 class TypeBasedAA {
52 public:
53 typedef TypeBasedAAResult Result;
54
55 /// \brief Opaque, unique identifier for this analysis pass.
56 static void *ID() { return (void *)&PassID; }
57
58 TypeBasedAAResult run(Function &F, AnalysisManager *AM);
59
60 /// \brief Provide access to a name for this pass for debugging purposes.
61 static StringRef name() { return "TypeBasedAA"; }
62
63 private:
64 static char PassID;
65 };
66
67 /// Legacy wrapper pass to provide the TypeBasedAAResult object.
68 class TypeBasedAAWrapperPass : public ImmutablePass {
69 std::unique_ptr Result;
70
71 public:
72 static char ID;
73
74 TypeBasedAAWrapperPass();
75
76 TypeBasedAAResult &getResult() { return *Result; }
77 const TypeBasedAAResult &getResult() const { return *Result; }
3278
3379 bool doInitialization(Module &M) override;
34
35 /// getAdjustedAnalysisPointer - This method is used when a pass implements
36 /// an analysis interface through multiple inheritance. If needed, it
37 /// should override this to adjust the this pointer as needed for the
38 /// specified pass info.
39 void *getAdjustedAnalysisPointer(const void *PI) override {
40 if (PI == &AliasAnalysis::ID)
41 return (AliasAnalysis *)this;
42 return this;
43 }
44
45 bool Aliases(const MDNode *A, const MDNode *B) const;
46 bool PathAliases(const MDNode *A, const MDNode *B) const;
47
48 private:
80 bool doFinalization(Module &M) override;
4981 void getAnalysisUsage(AnalysisUsage &AU) const override;
50 AliasResult alias(const MemoryLocation &LocA,
51 const MemoryLocation &LocB) override;
52 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) override;
53 FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
54 FunctionModRefBehavior getModRefBehavior(const Function *F) override;
55 ModRefInfo getModRefInfo(ImmutableCallSite CS,
56 const MemoryLocation &Loc) override;
57 ModRefInfo getModRefInfo(ImmutableCallSite CS1,
58 ImmutableCallSite CS2) override;
5982 };
6083
6184 //===--------------------------------------------------------------------===//
6285 //
63 // createTypeBasedAliasAnalysisPass - This pass implements metadata-based
86 // createTypeBasedAAWrapperPass - This pass implements metadata-based
6487 // type-based alias analysis.
6588 //
66 ImmutablePass *createTypeBasedAliasAnalysisPass();
67
89 ImmutablePass *createTypeBasedAAWrapperPass();
6890 }
6991
7092 #endif
2121
2222 #include "llvm/ADT/IndexedMap.h"
2323 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
2425 #include "llvm/CodeGen/LiveInterval.h"
2526 #include "llvm/CodeGen/MachineBasicBlock.h"
2627 #include "llvm/CodeGen/MachineFunctionPass.h"
3536
3637 extern cl::opt UseSegmentSetForPhysRegs;
3738
38 class AliasAnalysis;
3939 class BitVector;
4040 class BlockFrequency;
4141 class LiveRangeCalc;
2020 #include "llvm/ADT/ArrayRef.h"
2121 #include "llvm/ADT/SetVector.h"
2222 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
2324 #include "llvm/CodeGen/LiveInterval.h"
2425 #include "llvm/CodeGen/MachineRegisterInfo.h"
2526 #include "llvm/Target/TargetMachine.h"
2728
2829 namespace llvm {
2930
30 class AliasAnalysis;
3131 class LiveIntervals;
3232 class MachineBlockFrequencyInfo;
3333 class MachineLoopInfo;
2222 #include "llvm/ADT/ilist.h"
2323 #include "llvm/ADT/ilist_node.h"
2424 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
2526 #include "llvm/CodeGen/MachineOperand.h"
2627 #include "llvm/IR/DebugInfo.h"
2728 #include "llvm/IR/DebugLoc.h"
3334 namespace llvm {
3435
3536 template class SmallVectorImpl;
36 class AliasAnalysis;
3737 class TargetInstrInfo;
3838 class TargetRegisterClass;
3939 class TargetRegisterInfo;
7676 #ifndef LLVM_CODEGEN_MACHINESCHEDULER_H
7777 #define LLVM_CODEGEN_MACHINESCHEDULER_H
7878
79 #include "llvm/Analysis/AliasAnalysis.h"
7980 #include "llvm/CodeGen/MachinePassRegistry.h"
8081 #include "llvm/CodeGen/RegisterPressure.h"
8182 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
8687 extern cl::opt ForceTopDown;
8788 extern cl::opt ForceBottomUp;
8889
89 class AliasAnalysis;
9090 class LiveIntervals;
9191 class MachineDominatorTree;
9292 class MachineLoopInfo;
1919 #include "llvm/ADT/GraphTraits.h"
2020 #include "llvm/ADT/PointerIntPair.h"
2121 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
2223 #include "llvm/CodeGen/MachineInstr.h"
2324 #include "llvm/Target/TargetLowering.h"
2425
2526 namespace llvm {
26 class AliasAnalysis;
2727 class SUnit;
2828 class MachineConstantPool;
2929 class MachineFunction;
1818 #include "llvm/ADT/SetVector.h"
1919 #include "llvm/ADT/StringMap.h"
2020 #include "llvm/ADT/ilist.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
2122 #include "llvm/CodeGen/DAGCombine.h"
2223 #include "llvm/CodeGen/MachineFunction.h"
2324 #include "llvm/CodeGen/SelectionDAGNodes.h"
3031
3132 namespace llvm {
3233
33 class AliasAnalysis;
3434 class MachineConstantPoolValue;
3535 class MachineFunction;
3636 class MDNode;
6262 void initializeAddDiscriminatorsPass(PassRegistry&);
6363 void initializeADCEPass(PassRegistry&);
6464 void initializeBDCEPass(PassRegistry&);
65 void initializeAliasAnalysisAnalysisGroup(PassRegistry&);
66 void initializeAliasAnalysisCounterPass(PassRegistry&);
6765 void initializeAliasSetPrinterPass(PassRegistry&);
6866 void initializeAlwaysInlinerPass(PassRegistry&);
6967 void initializeArgPromotionPass(PassRegistry&);
7169 void initializeSampleProfileLoaderPass(PassRegistry&);
7270 void initializeAlignmentFromAssumptionsPass(PassRegistry&);
7371 void initializeBarrierNoopPass(PassRegistry&);
74 void initializeBasicAliasAnalysisPass(PassRegistry&);
72 void initializeBasicAAWrapperPassPass(PassRegistry&);
7573 void initializeCallGraphWrapperPassPass(PassRegistry &);
7674 void initializeBlockExtractorPassPass(PassRegistry&);
7775 void initializeBlockFrequencyInfoWrapperPassPass(PassRegistry&);
8583 void initializeCFGOnlyViewerPass(PassRegistry&);
8684 void initializeCFGPrinterPass(PassRegistry&);
8785 void initializeCFGSimplifyPassPass(PassRegistry&);
88 void initializeCFLAliasAnalysisPass(PassRegistry&);
86 void initializeCFLAAWrapperPassPass(PassRegistry&);
8987 void initializeForwardControlFlowIntegrityPass(PassRegistry&);
9088 void initializeFlattenCFGPassPass(PassRegistry&);
9189 void initializeStructurizeCFGPass(PassRegistry&);
115113 void initializeEarlyIfConverterPass(PassRegistry&);
116114 void initializeEdgeBundlesPass(PassRegistry&);
117115 void initializeExpandPostRAPass(PassRegistry&);
116 void initializeAAResultsWrapperPassPass(PassRegistry &);
118117 void initializeGCOVProfilerPass(PassRegistry&);
119118 void initializeInstrProfilingPass(PassRegistry&);
120119 void initializeAddressSanitizerPass(PassRegistry&);
133132 void initializeGVNPass(PassRegistry&);
134133 void initializeGlobalDCEPass(PassRegistry&);
135134 void initializeGlobalOptPass(PassRegistry&);
136 void initializeGlobalsModRefPass(PassRegistry&);
135 void initializeGlobalsAAWrapperPassPass(PassRegistry&);
137136 void initializeIPCPPass(PassRegistry&);
138137 void initializeIPSCCPPass(PassRegistry&);
139138 void initializeIVUsersPass(PassRegistry&);
204203 void initializeModuleDebugInfoPrinterPass(PassRegistry&);
205204 void initializeNaryReassociatePass(PassRegistry&);
206205 void initializeNoAAPass(PassRegistry&);
207 void initializeObjCARCAliasAnalysisPass(PassRegistry&);
206 void initializeObjCARCAAWrapperPassPass(PassRegistry&);
208207 void initializeObjCARCAPElimPass(PassRegistry&);
209208 void initializeObjCARCExpandPass(PassRegistry&);
210209 void initializeObjCARCContractPass(PassRegistry&);
242241 void initializeSROAPass(PassRegistry&);
243242 void initializeSROA_DTPass(PassRegistry&);
244243 void initializeSROA_SSAUpPass(PassRegistry&);
245 void initializeScalarEvolutionAliasAnalysisPass(PassRegistry&);
244 void initializeSCEVAAWrapperPassPass(PassRegistry&);
246245 void initializeScalarEvolutionWrapperPassPass(PassRegistry&);
247246 void initializeShrinkWrapPass(PassRegistry &);
248247 void initializeSimpleInlinerPass(PassRegistry&);
270269 void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &);
271270 void initializeAssumptionCacheTrackerPass(PassRegistry &);
272271 void initializeTwoAddressInstructionPassPass(PassRegistry&);
273 void initializeTypeBasedAliasAnalysisPass(PassRegistry&);
274 void initializeScopedNoAliasAAPass(PassRegistry&);
272 void initializeTypeBasedAAWrapperPassPass(PassRegistry&);
273 void initializeScopedNoAliasAAWrapperPassPass(PassRegistry&);
275274 void initializeUnifyFunctionExitNodesPass(PassRegistry&);
276275 void initializeUnreachableBlockElimPass(PassRegistry&);
277276 void initializeUnreachableMachineBlockElimPass(PassRegistry&);
1616
1717 #include "llvm/ADT/Statistic.h"
1818 #include "llvm/Analysis/AliasSetTracker.h"
19 #include "llvm/Analysis/AliasAnalysisCounter.h"
2019 #include "llvm/Analysis/BasicAliasAnalysis.h"
2120 #include "llvm/Analysis/CFLAliasAnalysis.h"
2221 #include "llvm/Analysis/CallPrinter.h"
5857 (void) llvm::createAAEvalPass();
5958 (void) llvm::createAggressiveDCEPass();
6059 (void) llvm::createBitTrackingDCEPass();
61 (void) llvm::createAliasAnalysisCounterPass();
6260 (void) llvm::createArgumentPromotionPass();
6361 (void) llvm::createAlignmentFromAssumptionsPass();
64 (void) llvm::createBasicAliasAnalysisPass();
65 (void) llvm::createScalarEvolutionAliasAnalysisPass();
66 (void) llvm::createTypeBasedAliasAnalysisPass();
67 (void) llvm::createScopedNoAliasAAPass();
62 (void) llvm::createBasicAAWrapperPass();
63 (void) llvm::createSCEVAAWrapperPass();
64 (void) llvm::createTypeBasedAAWrapperPass();
65 (void) llvm::createScopedNoAliasAAWrapperPass();
6866 (void) llvm::createBoundsCheckingPass();
6967 (void) llvm::createBreakCriticalEdgesPass();
7068 (void) llvm::createCallGraphPrinterPass();
7169 (void) llvm::createCallGraphViewerPass();
7270 (void) llvm::createCFGSimplificationPass();
73 (void) llvm::createCFLAliasAnalysisPass();
71 (void) llvm::createCFLAAWrapperPass();
7472 (void) llvm::createStructurizeCFGPass();
7573 (void) llvm::createConstantMergePass();
7674 (void) llvm::createConstantPropagationPass();
9189 (void) llvm::createAlwaysInlinerPass();
9290 (void) llvm::createGlobalDCEPass();
9391 (void) llvm::createGlobalOptimizerPass();
94 (void) llvm::createGlobalsModRefPass();
92 (void) llvm::createGlobalsAAWrapperPass();
9593 (void) llvm::createIPConstantPropagationPass();
9694 (void) llvm::createIPSCCPPass();
9795 (void) llvm::createInductiveRangeCheckEliminationPass();
114112 (void) llvm::createLowerInvokePass();
115113 (void) llvm::createLowerSwitchPass();
116114 (void) llvm::createNaryReassociatePass();
117 (void) llvm::createNoAAPass();
118 (void) llvm::createObjCARCAliasAnalysisPass();
115 (void) llvm::createObjCARCAAWrapperPass();
119116 (void) llvm::createObjCARCAPElimPass();
120117 (void) llvm::createObjCARCExpandPass();
121118 (void) llvm::createObjCARCContractPass();
1919
2020 #include "llvm/ADT/SmallVector.h"
2121 #include "llvm/ADT/Twine.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
2223 #include "llvm/IR/ValueHandle.h"
2324 #include "llvm/IR/ValueMap.h"
2425 #include "llvm/Transforms/Utils/ValueMapper.h"
4344 class Loop;
4445 class LoopInfo;
4546 class AllocaInst;
46 class AliasAnalysis;
4747 class AssumptionCacheTracker;
4848 class DominatorTree;
4949
201201 class InlineFunctionInfo {
202202 public:
203203 explicit InlineFunctionInfo(CallGraph *cg = nullptr,
204 AliasAnalysis *AA = nullptr,
205204 AssumptionCacheTracker *ACT = nullptr)
206 : CG(cg), AA(AA), ACT(ACT) {}
205 : CG(cg), ACT(ACT) {}
207206
208207 /// CG - If non-null, InlineFunction will update the callgraph to reflect the
209208 /// changes it makes.
210209 CallGraph *CG;
211 AliasAnalysis *AA;
212210 AssumptionCacheTracker *ACT;
213211
214212 /// StaticAllocas - InlineFunction fills this in with all static allocas that
236234 /// function by one level.
237235 ///
238236 bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI,
239 bool InsertLifetime = true);
237 AAResults *CalleeAAR = nullptr, bool InsertLifetime = true);
240238 bool InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
241 bool InsertLifetime = true);
239 AAResults *CalleeAAR = nullptr, bool InsertLifetime = true);
242240 bool InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
243 bool InsertLifetime = true);
241 AAResults *CalleeAAR = nullptr, bool InsertLifetime = true);
244242
245243 /// \brief Clones a loop \p OrigLoop. Returns the loop and the blocks in \p
246244 /// Blocks.
1414 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
1515 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
1616
17 #include "llvm/Analysis/AliasAnalysis.h"
1718 #include "llvm/IR/DataLayout.h"
1819 #include "llvm/IR/Dominators.h"
1920 #include "llvm/IR/GetElementPtrTypeIterator.h"
3940 class TargetLibraryInfo;
4041 class TargetTransformInfo;
4142 class DIBuilder;
42 class AliasAnalysis;
4343 class DominatorTree;
4444
4545 template class SmallVectorImpl;
1414 #define LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
1515
1616 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
1718 #include "llvm/IR/Dominators.h"
1819 #include "llvm/IR/IRBuilder.h"
1920
2021 namespace llvm {
21 class AliasAnalysis;
2222 class AliasSet;
2323 class AliasSetTracker;
2424 class AssumptionCache;
2424 //===----------------------------------------------------------------------===//
2525
2626 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BasicAliasAnalysis.h"
2728 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/CFLAliasAnalysis.h"
2830 #include "llvm/Analysis/CaptureTracking.h"
31 #include "llvm/Analysis/GlobalsModRef.h"
32 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
33 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
34 #include "llvm/Analysis/ScopedNoAliasAA.h"
2935 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
3037 #include "llvm/Analysis/ValueTracking.h"
3138 #include "llvm/IR/BasicBlock.h"
3239 #include "llvm/IR/DataLayout.h"
3946 #include "llvm/Pass.h"
4047 using namespace llvm;
4148
42 // Register the AliasAnalysis interface, providing a nice name to refer to.
43 INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
44 char AliasAnalysis::ID = 0;
49 /// Allow disabling BasicAA from the AA results. This is particularly useful
50 /// when testing to isolate a single AA implementation.
51 static cl::opt DisableBasicAA("disable-basicaa", cl::Hidden,
52 cl::init(false));
53
54 AAResults::AAResults(AAResults &&Arg) : AAs(std::move(Arg.AAs)) {
55 for (auto &AA : AAs)
56 AA->setAAResults(this);
57 }
58
59 AAResults &AAResults::operator=(AAResults &&Arg) {
60 AAs = std::move(Arg.AAs);
61 for (auto &AA : AAs)
62 AA->setAAResults(this);
63 return *this;
64 }
65
66 AAResults::~AAResults() {
67 // FIXME; It would be nice to at least clear out the pointers back to this
68 // aggregation here, but we end up with non-nesting lifetimes in the legacy
69 // pass manager that prevent this from working. In the legacy pass manager
70 // we'll end up with dangling references here in some cases.
71 #if 0
72 for (auto &AA : AAs)
73 AA->setAAResults(nullptr);
74 #endif
75 }
4576
4677 //===----------------------------------------------------------------------===//
4778 // Default chaining methods
4879 //===----------------------------------------------------------------------===//
4980
50 AliasResult AliasAnalysis::alias(const MemoryLocation &LocA,
51 const MemoryLocation &LocB) {
52 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
53 return AA->alias(LocA, LocB);
54 }
55
56 bool AliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
57 bool OrLocal) {
58 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
59 return AA->pointsToConstantMemory(Loc, OrLocal);
60 }
61
62 ModRefInfo AliasAnalysis::getArgModRefInfo(ImmutableCallSite CS,
63 unsigned ArgIdx) {
64 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
65 return AA->getArgModRefInfo(CS, ArgIdx);
66 }
67
68 ModRefInfo AliasAnalysis::getModRefInfo(Instruction *I,
69 ImmutableCallSite Call) {
81 AliasResult AAResults::alias(const MemoryLocation &LocA,
82 const MemoryLocation &LocB) {
83 for (const auto &AA : AAs) {
84 auto Result = AA->alias(LocA, LocB);
85 if (Result != MayAlias)
86 return Result;
87 }
88 return MayAlias;
89 }
90
91 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc,
92 bool OrLocal) {
93 for (const auto &AA : AAs)
94 if (AA->pointsToConstantMemory(Loc, OrLocal))
95 return true;
96
97 return false;
98 }
99
100 ModRefInfo AAResults::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
101 ModRefInfo Result = MRI_ModRef;
102
103 for (const auto &AA : AAs) {
104 Result = ModRefInfo(Result & AA->getArgModRefInfo(CS, ArgIdx));
105
106 // Early-exit the moment we reach the bottom of the lattice.
107 if (Result == MRI_NoModRef)
108 return Result;
109 }
110
111 return Result;
112 }
113
114 ModRefInfo AAResults::getModRefInfo(Instruction *I, ImmutableCallSite Call) {
70115 // We may have two calls
71116 if (auto CS = ImmutableCallSite(I)) {
72117 // Check if the two calls modify the same memory
83128 return MRI_NoModRef;
84129 }
85130
86 ModRefInfo AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
87 const MemoryLocation &Loc) {
88 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
89
90 auto MRB = getModRefBehavior(CS);
91 if (MRB == FMRB_DoesNotAccessMemory)
92 return MRI_NoModRef;
93
94 ModRefInfo Mask = MRI_ModRef;
95 if (onlyReadsMemory(MRB))
96 Mask = MRI_Ref;
97
98 if (onlyAccessesArgPointees(MRB)) {
99 bool doesAlias = false;
100 ModRefInfo AllArgsMask = MRI_NoModRef;
101 if (doesAccessArgPointees(MRB)) {
102 for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
103 AI != AE; ++AI) {
104 const Value *Arg = *AI;
105 if (!Arg->getType()->isPointerTy())
106 continue;
107 unsigned ArgIdx = std::distance(CS.arg_begin(), AI);
108 MemoryLocation ArgLoc =
109 MemoryLocation::getForArgument(CS, ArgIdx, *TLI);
110 if (!isNoAlias(ArgLoc, Loc)) {
111 ModRefInfo ArgMask = getArgModRefInfo(CS, ArgIdx);
112 doesAlias = true;
113 AllArgsMask = ModRefInfo(AllArgsMask | ArgMask);
114 }
115 }
116 }
117 if (!doesAlias)
118 return MRI_NoModRef;
119 Mask = ModRefInfo(Mask & AllArgsMask);
120 }
121
122 // If Loc is a constant memory location, the call definitely could not
123 // modify the memory location.
124 if ((Mask & MRI_Mod) && pointsToConstantMemory(Loc))
125 Mask = ModRefInfo(Mask & ~MRI_Mod);
126
127 // If this is the end of the chain, don't forward.
128 if (!AA) return Mask;
129
130 // Otherwise, fall back to the next AA in the chain. But we can merge
131 // in any mask we've managed to compute.
132 return ModRefInfo(AA->getModRefInfo(CS, Loc) & Mask);
133 }
134
135 ModRefInfo AliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
136 ImmutableCallSite CS2) {
137 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
138
139 // If CS1 or CS2 are readnone, they don't interact.
140 auto CS1B = getModRefBehavior(CS1);
141 if (CS1B == FMRB_DoesNotAccessMemory)
142 return MRI_NoModRef;
143
144 auto CS2B = getModRefBehavior(CS2);
145 if (CS2B == FMRB_DoesNotAccessMemory)
146 return MRI_NoModRef;
147
148 // If they both only read from memory, there is no dependence.
149 if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
150 return MRI_NoModRef;
151
152 ModRefInfo Mask = MRI_ModRef;
153
154 // If CS1 only reads memory, the only dependence on CS2 can be
155 // from CS1 reading memory written by CS2.
156 if (onlyReadsMemory(CS1B))
157 Mask = ModRefInfo(Mask & MRI_Ref);
158
159 // If CS2 only access memory through arguments, accumulate the mod/ref
160 // information from CS1's references to the memory referenced by
161 // CS2's arguments.
162 if (onlyAccessesArgPointees(CS2B)) {
163 ModRefInfo R = MRI_NoModRef;
164 if (doesAccessArgPointees(CS2B)) {
165 for (ImmutableCallSite::arg_iterator
166 I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
167 const Value *Arg = *I;
168 if (!Arg->getType()->isPointerTy())
169 continue;
170 unsigned CS2ArgIdx = std::distance(CS2.arg_begin(), I);
171 auto CS2ArgLoc = MemoryLocation::getForArgument(CS2, CS2ArgIdx, *TLI);
172
173 // ArgMask indicates what CS2 might do to CS2ArgLoc, and the dependence of
174 // CS1 on that location is the inverse.
175 ModRefInfo ArgMask = getArgModRefInfo(CS2, CS2ArgIdx);
176 if (ArgMask == MRI_Mod)
177 ArgMask = MRI_ModRef;
178 else if (ArgMask == MRI_Ref)
179 ArgMask = MRI_Mod;
180
181 R = ModRefInfo((R | (getModRefInfo(CS1, CS2ArgLoc) & ArgMask)) & Mask);
182 if (R == Mask)
183 break;
184 }
185 }
186 return R;
187 }
188
189 // If CS1 only accesses memory through arguments, check if CS2 references
190 // any of the memory referenced by CS1's arguments. If not, return NoModRef.
191 if (onlyAccessesArgPointees(CS1B)) {
192 ModRefInfo R = MRI_NoModRef;
193 if (doesAccessArgPointees(CS1B)) {
194 for (ImmutableCallSite::arg_iterator
195 I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
196 const Value *Arg = *I;
197 if (!Arg->getType()->isPointerTy())
198 continue;
199 unsigned CS1ArgIdx = std::distance(CS1.arg_begin(), I);
200 auto CS1ArgLoc = MemoryLocation::getForArgument(CS1, CS1ArgIdx, *TLI);
201
202 // ArgMask indicates what CS1 might do to CS1ArgLoc; if CS1 might Mod
203 // CS1ArgLoc, then we care about either a Mod or a Ref by CS2. If CS1
204 // might Ref, then we care only about a Mod by CS2.
205 ModRefInfo ArgMask = getArgModRefInfo(CS1, CS1ArgIdx);
206 ModRefInfo ArgR = getModRefInfo(CS2, CS1ArgLoc);
207 if (((ArgMask & MRI_Mod) != MRI_NoModRef &&
208 (ArgR & MRI_ModRef) != MRI_NoModRef) ||
209 ((ArgMask & MRI_Ref) != MRI_NoModRef &&
210 (ArgR & MRI_Mod) != MRI_NoModRef))
211 R = ModRefInfo((R | ArgMask) & Mask);
212
213 if (R == Mask)
214 break;
215 }
216 }
217 return R;
218 }
219
220 // If this is the end of the chain, don't forward.
221 if (!AA) return Mask;
222
223 // Otherwise, fall back to the next AA in the chain. But we can merge
224 // in any mask we've managed to compute.
225 return ModRefInfo(AA->getModRefInfo(CS1, CS2) & Mask);
226 }
227
228 FunctionModRefBehavior AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
229 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
230
231 auto Min = FMRB_UnknownModRefBehavior;
232
233 // Call back into the alias analysis with the other form of getModRefBehavior
234 // to see if it can give a better response.
235 if (const Function *F = CS.getCalledFunction())
236 Min = getModRefBehavior(F);
237
238 // If this is the end of the chain, don't forward.
239 if (!AA) return Min;
240
241 // Otherwise, fall back to the next AA in the chain. But we can merge
242 // in any result we've managed to compute.
243 return FunctionModRefBehavior(AA->getModRefBehavior(CS) & Min);
244 }
245
246 FunctionModRefBehavior AliasAnalysis::getModRefBehavior(const Function *F) {
247 assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
248 return AA->getModRefBehavior(F);
131 ModRefInfo AAResults::getModRefInfo(ImmutableCallSite CS,
132 const MemoryLocation &Loc) {
133 ModRefInfo Result = MRI_ModRef;
134
135 for (const auto &AA : AAs) {
136 Result = ModRefInfo(Result & AA->getModRefInfo(CS, Loc));
137
138 // Early-exit the moment we reach the bottom of the lattice.
139 if (Result == MRI_NoModRef)
140 return Result;
141 }
142
143 return Result;
144 }
145
146 ModRefInfo AAResults::getModRefInfo(ImmutableCallSite CS1,
147 ImmutableCallSite CS2) {
148 ModRefInfo Result = MRI_ModRef;
149
150 for (const auto &AA : AAs) {
151 Result = ModRefInfo(Result & AA->getModRefInfo(CS1, CS2));
152
153 // Early-exit the moment we reach the bottom of the lattice.
154 if (Result == MRI_NoModRef)
155 return Result;
156 }
157
158 return Result;
159 }
160
161 FunctionModRefBehavior AAResults::getModRefBehavior(ImmutableCallSite CS) {
162 FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
163
164 for (const auto &AA : AAs) {
165 Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(CS));
166
167 // Early-exit the moment we reach the bottom of the lattice.
168 if (Result == FMRB_DoesNotAccessMemory)
169 return Result;
170 }
171
172 return Result;
173 }
174
175 FunctionModRefBehavior AAResults::getModRefBehavior(const Function *F) {
176 FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior;
177
178 for (const auto &AA : AAs) {
179 Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(F));
180
181 // Early-exit the moment we reach the bottom of the lattice.
182 if (Result == FMRB_DoesNotAccessMemory)
183 return Result;
184 }
185
186 return Result;
249187 }
250188
251189 //===----------------------------------------------------------------------===//
252 // AliasAnalysis non-virtual helper method implementation
190 // Helper method implementation
253191 //===----------------------------------------------------------------------===//
254192
255 ModRefInfo AliasAnalysis::getModRefInfo(const LoadInst *L,
256 const MemoryLocation &Loc) {
193 ModRefInfo AAResults::getModRefInfo(const LoadInst *L,
194 const MemoryLocation &Loc) {
257195 // Be conservative in the face of volatile/atomic.
258196 if (!L->isUnordered())
259197 return MRI_ModRef;
267205 return MRI_Ref;
268206 }
269207
270 ModRefInfo AliasAnalysis::getModRefInfo(const StoreInst *S,
271 const MemoryLocation &Loc) {
208 ModRefInfo AAResults::getModRefInfo(const StoreInst *S,
209 const MemoryLocation &Loc) {
272210 // Be conservative in the face of volatile/atomic.
273211 if (!S->isUnordered())
274212 return MRI_ModRef;
289227 return MRI_Mod;
290228 }
291229
292 ModRefInfo AliasAnalysis::getModRefInfo(const VAArgInst *V,
293 const MemoryLocation &Loc) {
230 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V,
231 const MemoryLocation &Loc) {
294232
295233 if (Loc.Ptr) {
296234 // If the va_arg address cannot alias the pointer in question, then the
308246 return MRI_ModRef;
309247 }
310248
311 ModRefInfo AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX,
312 const MemoryLocation &Loc) {
249 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX,
250 const MemoryLocation &Loc) {
313251 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
314252 if (CX->getSuccessOrdering() > Monotonic)
315253 return MRI_ModRef;
321259 return MRI_ModRef;
322260 }
323261
324 ModRefInfo AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW,
325 const MemoryLocation &Loc) {
262 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW,
263 const MemoryLocation &Loc) {
326264 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
327265 if (RMW->getOrdering() > Monotonic)
328266 return MRI_ModRef;
342280 /// BasicAA isn't willing to spend linear time determining whether an alloca
343281 /// was captured before or after this particular call, while we are. However,
344282 /// with a smarter AA in place, this test is just wasting compile time.
345 ModRefInfo AliasAnalysis::callCapturesBefore(const Instruction *I,
346 const MemoryLocation &MemLoc,
347 DominatorTree *DT,
348 OrderedBasicBlock *OBB) {
283 ModRefInfo AAResults::callCapturesBefore(const Instruction *I,
284 const MemoryLocation &MemLoc,
285 DominatorTree *DT,
286 OrderedBasicBlock *OBB) {
349287 if (!DT)
350288 return MRI_ModRef;
351289
352 const Value *Object = GetUnderlyingObject(MemLoc.Ptr, *DL);
290 const Value *Object =
291 GetUnderlyingObject(MemLoc.Ptr, I->getModule()->getDataLayout());
353292 if (!isIdentifiedObject(Object) || isa(Object) ||
354293 isa(Object))
355294 return MRI_ModRef;
392331 return R;
393332 }
394333
395 // AliasAnalysis destructor: DO NOT move this to the header file for
396 // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
397 // the AliasAnalysis.o file in the current .a file, causing alias analysis
398 // support to not be included in the tool correctly!
399 //
400 AliasAnalysis::~AliasAnalysis() {}
401
402 /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
403 /// AliasAnalysis interface before any other methods are called.
404 ///
405 void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
406 DL = NewDL;
407 auto *TLIP = P->getAnalysisIfAvailable();
408 TLI = TLIP ? &TLIP->getTLI() : nullptr;
409 AA = &P->getAnalysis();
410 }
411
412 // getAnalysisUsage - All alias analysis implementations should invoke this
413 // directly (using AliasAnalysis::getAnalysisUsage(AU)).
414 void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
415 AU.addRequired(); // All AA's chain
416 }
417
418334 /// canBasicBlockModify - Return true if it is possible for execution of the
419335 /// specified basic block to modify the location Loc.
420336 ///
421 bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
422 const MemoryLocation &Loc) {
337 bool AAResults::canBasicBlockModify(const BasicBlock &BB,
338 const MemoryLocation &Loc) {
423339 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, MRI_Mod);
424340 }
425341
428344 /// mode) the location Loc. The instructions to consider are all
429345 /// of the instructions in the range of [I1,I2] INCLUSIVE.
430346 /// I1 and I2 must be in the same basic block.
431 bool AliasAnalysis::canInstructionRangeModRef(const Instruction &I1,
432 const Instruction &I2,
433 const MemoryLocation &Loc,
434 const ModRefInfo Mode) {
347 bool AAResults::canInstructionRangeModRef(const Instruction &I1,
348 const Instruction &I2,
349 const MemoryLocation &Loc,
350 const ModRefInfo Mode) {
435351 assert(I1.getParent() == I2.getParent() &&
436352 "Instructions not in same basic block!");
437353 BasicBlock::const_iterator I = &I1;
442358 if (getModRefInfo(I, Loc) & Mode)
443359 return true;
444360 return false;
361 }
362
363 // Provide a definition for the root virtual destructor.
364 AAResults::Concept::~Concept() {}
365
366 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) {
367 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
368 }
369
370 char AAResultsWrapperPass::ID = 0;
371
372 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa",
373 "Function Alias Analysis Results", false, true)
374 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
375 INITIALIZE_PASS_DEPENDENCY(CFLAAWrapperPass)
376 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
377 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
378 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
379 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass)
380 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass)
381 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa",
382 "Function Alias Analysis Results", false, true)
383
384 FunctionPass *llvm::createAAResultsWrapperPass() {
385 return new AAResultsWrapperPass();
386 }
387
388 /// Run the wrapper pass to rebuild an aggregation over known AA passes.
389 ///
390 /// This is the legacy pass manager's interface to the new-style AA results
391 /// aggregation object. Because this is somewhat shoe-horned into the legacy
392 /// pass manager, we hard code all the specific alias analyses available into
393 /// it. While the particular set enabled is configured via commandline flags,
394 /// adding a new alias analysis to LLVM will require adding support for it to
395 /// this list.
396 bool AAResultsWrapperPass::runOnFunction(Function &F) {
397 // NB! This *must* be reset before adding new AA results to the new
398 // AAResults object because in the legacy pass manager, each instance
399 // of these will refer to the *same* immutable analyses, registering and
400 // unregistering themselves with them. We need to carefully tear down the
401 // previous object first, in this case replacing it with an empty one, before
402 // registering new results.
403 AAR.reset(new AAResults());
404
405 // BasicAA is always available for function analyses. Also, we add it first
406 // so that it can trump TBAA results when it proves MustAlias.
407 // FIXME: TBAA should have an explicit mode to support this and then we
408 // should reconsider the ordering here.
409 if (!DisableBasicAA)
410 AAR->addAAResult(getAnalysis().getResult());
411
412 // Populate the results with the currently available AAs.
413 if (auto *WrapperPass = getAnalysisIfAvailable())
414 AAR->addAAResult(WrapperPass->getResult());
415 if (auto *WrapperPass = getAnalysisIfAvailable())
416 AAR->addAAResult(WrapperPass->getResult());
417 if (auto *WrapperPass =
418 getAnalysisIfAvailable())
419 AAR->addAAResult(WrapperPass->getResult());
420 if (auto *WrapperPass = getAnalysisIfAvailable())
421 AAR->addAAResult(WrapperPass->getResult());
422 if (auto *WrapperPass = getAnalysisIfAvailable())
423 AAR->addAAResult(WrapperPass->getResult());
424 if (auto *WrapperPass = getAnalysisIfAvailable())
425 AAR->addAAResult(WrapperPass->getResult());
426
427 // Analyses don't mutate the IR, so return false.
428 return false;
429 }
430
431 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
432 AU.setPreservesAll();
433 AU.addRequired();
434
435 // We also need to mark all the alias analysis passes we will potentially
436 // probe in runOnFunction as used here to ensure the legacy pass manager
437 // preserves them. This hard coding of lists of alias analyses is specific to
438 // the legacy pass manager.
439 AU.addUsedIfAvailable();
440 AU.addUsedIfAvailable();
441 AU.addUsedIfAvailable();
442 AU.addUsedIfAvailable();
443 AU.addUsedIfAvailable();
444 AU.addUsedIfAvailable();
445 }
446
447 AAResults llvm::createLegacyPMAAResults(Pass &P, Function &F,
448 BasicAAResult &BAR) {
449 AAResults AAR;
450
451 // Add in our explicitly constructed BasicAA results.
452 if (!DisableBasicAA)
453 AAR.addAAResult(BAR);
454
455 // Populate the results with the other currently available AAs.
456 if (auto *WrapperPass =
457 P.getAnalysisIfAvailable())
458 AAR.addAAResult(WrapperPass->getResult());
459 if (auto *WrapperPass = P.getAnalysisIfAvailable())
460 AAR.addAAResult(WrapperPass->getResult());
461 if (auto *WrapperPass =
462 P.getAnalysisIfAvailable())
463 AAR.addAAResult(WrapperPass->getResult());
464 if (auto *WrapperPass = P.getAnalysisIfAvailable())
465 AAR.addAAResult(WrapperPass->getResult());
466 if (auto *WrapperPass = P.getAnalysisIfAvailable())
467 AAR.addAAResult(WrapperPass->getResult());
468 if (auto *WrapperPass = P.getAnalysisIfAvailable())
469 AAR.addAAResult(WrapperPass->getResult());
470
471 return AAR;
445472 }
446473
447474 /// isNoAliasCall - Return true if this pointer is returned by a noalias
+0
-165
lib/Analysis/AliasAnalysisCounter.cpp less more
None //===- AliasAnalysisCounter.cpp - Alias Analysis Query Counter ------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a pass which can be used to count how many alias queries
10 // are being made and how the alias analysis implementation being used responds.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/AliasAnalysisCounter.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23
24 static cl::opt PrintAll("count-aa-print-all-queries", cl::ReallyHidden,
25 cl::init(true));
26 static cl::opt PrintAllFailures("count-aa-print-all-failed-queries",
27 cl::ReallyHidden);
28
29 char AliasAnalysisCounter::ID = 0;
30 INITIALIZE_AG_PASS(AliasAnalysisCounter, AliasAnalysis, "count-aa",
31 "Count Alias Analysis Query Responses", false, true, false)
32
33 ModulePass *llvm::createAliasAnalysisCounterPass() {
34 return new AliasAnalysisCounter();
35 }
36
37 AliasAnalysisCounter::AliasAnalysisCounter() : ModulePass(ID) {
38 initializeAliasAnalysisCounterPass(*PassRegistry::getPassRegistry());
39 No = May = Partial = Must = 0;
40 NoMR = JustRef = JustMod = MR = 0;
41 }
42
43 static void printLine(const char *Desc, unsigned Val, unsigned Sum) {
44 errs() << " " << Val << " " << Desc << " responses (" << Val * 100 / Sum
45 << "%)\n";
46 }
47
48 AliasAnalysisCounter::~AliasAnalysisCounter() {
49 unsigned AASum = No + May + Partial + Must;
50 unsigned MRSum = NoMR + JustRef + JustMod + MR;
51 if (AASum + MRSum) { // Print a report if any counted queries occurred...
52 errs() << "\n===== Alias Analysis Counter Report =====\n"
53 << " Analysis counted:\n"
54 << " " << AASum << " Total Alias Queries Performed\n";
55 if (AASum) {
56 printLine("no alias", No, AASum);
57 printLine("may alias", May, AASum);
58 printLine("partial alias", Partial, AASum);
59 printLine("must alias", Must, AASum);
60 errs() << " Alias Analysis Counter Summary: " << No * 100 / AASum << "%/"
61 << May * 100 / AASum << "%/" << Partial * 100 / AASum << "%/"
62 << Must * 100 / AASum << "%\n\n";
63 }
64
65 errs() << " " << MRSum << " Total MRI_Mod/MRI_Ref Queries Performed\n";
66 if (MRSum) {
67 printLine("no mod/ref", NoMR, MRSum);
68 printLine("ref", JustRef, MRSum);
69 printLine("mod", JustMod, MRSum);
70 printLine("mod/ref", MR, MRSum);
71 errs() << " MRI_Mod/MRI_Ref Analysis Counter Summary: "
72 << NoMR * 100 / MRSum << "%/" << JustRef * 100 / MRSum << "%/"
73 << JustMod * 100 / MRSum << "%/" << MR * 100 / MRSum << "%\n\n";
74 }
75 }
76 }
77
78 bool AliasAnalysisCounter::runOnModule(Module &M) {
79 this->M = &M;
80 InitializeAliasAnalysis(this, &M.getDataLayout());
81 return false;
82 }
83
84 void AliasAnalysisCounter::getAnalysisUsage(AnalysisUsage &AU) const {
85 AliasAnalysis::getAnalysisUsage(AU);
86 AU.addRequired();
87 AU.setPreservesAll();
88 }
89
90 void *AliasAnalysisCounter::getAdjustedAnalysisPointer(AnalysisID PI) {
91 if (PI == &AliasAnalysis::ID)
92 return (AliasAnalysis *)this;
93 return this;
94 }
95
96 AliasResult AliasAnalysisCounter::alias(const MemoryLocation &LocA,
97 const MemoryLocation &LocB) {
98 AliasResult R = getAnalysis().alias(LocA, LocB);
99
100 const char *AliasString = nullptr;
101 switch (R) {
102 case NoAlias:
103 No++;
104 AliasString = "No alias";
105 break;
106 case MayAlias:
107 May++;
108 AliasString = "May alias";
109 break;
110 case PartialAlias:
111 Partial++;
112 AliasString = "Partial alias";
113 break;
114 case MustAlias:
115 Must++;
116 AliasString = "Must alias";
117 break;
118 }
119
120 if (PrintAll || (PrintAllFailures && R == MayAlias)) {
121 errs() << AliasString << ":\t";
122 errs() << "[" << LocA.Size << "B] ";
123 LocA.Ptr->printAsOperand(errs(), true, M);
124 errs() << ", ";
125 errs() << "[" << LocB.Size << "B] ";
126 LocB.Ptr->printAsOperand(errs(), true, M);
127 errs() << "\n";
128 }
129
130 return R;
131 }
132
133 ModRefInfo AliasAnalysisCounter::getModRefInfo(ImmutableCallSite CS,
134 const MemoryLocation &Loc) {
135 ModRefInfo R = getAnalysis().getModRefInfo(CS, Loc);
136
137 const char *MRString = nullptr;
138 switch (R) {
139 case MRI_NoModRef:
140 NoMR++;
141 MRString = "MRI_NoModRef";
142 break;
143 case MRI_Ref:
144 JustRef++;
145 MRString = "JustRef";
146 break;
147 case MRI_Mod:
148 JustMod++;
149 MRString = "JustMod";
150 break;
151 case MRI_ModRef:
152 MR++;
153 MRString = "MRI_ModRef";
154 break;
155 }
156
157 if (PrintAll || (PrintAllFailures && R == MRI_ModRef)) {
158 errs() << MRString << ": Ptr: ";
159 errs() << "[" << Loc.Size << "B] ";
160 Loc.Ptr->printAsOperand(errs(), true, M);
161 errs() << "\t<->" << *CS.getInstruction() << '\n';
162 }
163 return R;
164 }
5858 }
5959
6060 void getAnalysisUsage(AnalysisUsage &AU) const override {
61 AU.addRequiredliasAnalysis>();
61 AU.addRequiredAResultsWrapperPass>();
6262 AU.setPreservesAll();
6363 }
6464
8282 char AAEval::ID = 0;
8383 INITIALIZE_PASS_BEGIN(AAEval, "aa-eval",
8484 "Exhaustive Alias Analysis Precision Evaluator", false, true)
85 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
85 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
8686 INITIALIZE_PASS_END(AAEval, "aa-eval",
8787 "Exhaustive Alias Analysis Precision Evaluator", false, true)
8888
141141
142142 bool AAEval::runOnFunction(Function &F) {
143143 const DataLayout &DL = F.getParent()->getDataLayout();
144 AliasAnalysis &AA = getAnalysisliasAnalysis>();
144 AliasAnalysis &AA = getAnalysisAResultsWrapperPass>().getAAResults();
145145
146146 SetVector Pointers;
147147 SetVector CallSites;
648648
649649 void getAnalysisUsage(AnalysisUsage &AU) const override {
650650 AU.setPreservesAll();
651 AU.addRequiredliasAnalysis>();
651 AU.addRequiredAResultsWrapperPass>();
652652 }
653653
654654 bool runOnFunction(Function &F) override {
655 Tracker = new AliasSetTracker(getAnalysis());
655 auto &AAWP = getAnalysis();
656 Tracker = new AliasSetTracker(AAWP.getAAResults());
656657
657658 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
658659 Tracker->add(&*I);
666667 char AliasSetPrinter::ID = 0;
667668 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
668669 "Alias Set Printer", false, true)
669 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
670 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
670671 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
671672 "Alias Set Printer", false, true)
1919
2020 /// initializeAnalysis - Initialize all passes linked into the Analysis library.
2121 void llvm::initializeAnalysis(PassRegistry &Registry) {
22 initializeAliasAnalysisAnalysisGroup(Registry);
23 initializeAliasAnalysisCounterPass(Registry);
2422 initializeAAEvalPass(Registry);
2523 initializeAliasSetPrinterPass(Registry);
26 initializeNoAAPass(Registry);
27 initializeBasicAliasAnalysisPass(Registry);
24 initializeBasicAAWrapperPassPass(Registry);
2825 initializeBlockFrequencyInfoWrapperPassPass(Registry);
2926 initializeBranchProbabilityInfoWrapperPassPass(Registry);
3027 initializeCallGraphWrapperPassPass(Registry);
3532 initializeCFGPrinterPass(Registry);
3633 initializeCFGOnlyViewerPass(Registry);
3734 initializeCFGOnlyPrinterPass(Registry);
38 initializeCFLAliasAnalysisPass(Registry);
35 initializeCFLAAWrapperPassPass(Registry);
3936 initializeDependenceAnalysisPass(Registry);
4037 initializeDelinearizationPass(Registry);
4138 initializeDemandedBitsPass(Registry);
4946 initializePostDomPrinterPass(Registry);
5047 initializePostDomOnlyViewerPass(Registry);
5148 initializePostDomOnlyPrinterPass(Registry);
52 initializeGlobalsModRefPass(Registry);
49 initializeAAResultsWrapperPassPass(Registry);
50 initializeGlobalsAAWrapperPassPass(Registry);
5351 initializeIVUsersPass(Registry);
5452 initializeInstCountPass(Registry);
5553 initializeIntervalPartitionPass(Registry);
6058 initializeMemDerefPrinterPass(Registry);
6159 initializeMemoryDependenceAnalysisPass(Registry);
6260 initializeModuleDebugInfoPrinterPass(Registry);
63 initializeObjCARCAliasAnalysisPass(Registry);
61 initializeObjCARCAAWrapperPassPass(Registry);
6462 initializePostDominatorTreePass(Registry);
6563 initializeRegionInfoPassPass(Registry);
6664 initializeRegionViewerPass(Registry);
6765 initializeRegionPrinterPass(Registry);
6866 initializeRegionOnlyViewerPass(Registry);
6967 initializeRegionOnlyPrinterPass(Registry);
68 initializeSCEVAAWrapperPassPass(Registry);
7069 initializeScalarEvolutionWrapperPassPass(Registry);
71 initializeScalarEvolutionAliasAnalysisPass(Registry);
7270 initializeTargetTransformInfoWrapperPassPass(Registry);
73 initializeTypeBasedAliasAnalysisPass(Registry);
74 initializeScopedNoAliasAAPass(Registry);
71 initializeTypeBasedAAWrapperPassPass(Registry);
72 initializeScopedNoAliasAAWrapperPassPass(Registry);
7573 }
7674
7775 void LLVMInitializeAnalysis(LLVMPassRegistryRef R) {
2222 #include "llvm/Analysis/LoopInfo.h"
2323 #include "llvm/Analysis/MemoryBuiltins.h"
2424 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Analysis/AssumptionCache.h"
2526 #include "llvm/IR/Constants.h"
2627 #include "llvm/IR/DataLayout.h"
2728 #include "llvm/IR/DerivedTypes.h"
176177 ///
177178 /// Note that this looks through extends, so the high bits may not be
178179 /// represented in the result.
179 /*static*/ const Value *BasicAliasAnalysis::GetLinearExpression(
180 /*static*/ const Value *BasicAAResult::GetLinearExpression(
180181 const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
181182 unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
182183 AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
330331 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
331332 /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
332333 /// through pointer casts.
333 /*static*/ const Value *BasicAliasAnalysis::DecomposeGEPExpression(
334 /*static*/ const Value *BasicAAResult::DecomposeGEPExpression(
334335 const Value *V, int64_t &BaseOffs,
335336 SmallVectorImpl &VarIndices, bool &MaxLookupReached,
336337 const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT) {
465466 return V;
466467 }
467468
468 //===----------------------------------------------------------------------===//
469 // BasicAliasAnalysis Pass
470 //===----------------------------------------------------------------------===//
471
472 // Register the pass...
473 char BasicAliasAnalysis::ID = 0;
474 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
475 "Basic Alias Analysis (stateless AA impl)", false,
476 true, false)
477 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
478 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
479 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
480 "Basic Alias Analysis (stateless AA impl)", false, true,
481 false)
482
483 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
484 return new BasicAliasAnalysis();
485 }
486
487469 /// Returns whether the given pointer value points to memory that is local to
488470 /// the function, with global constants being considered local to all
489471 /// functions.
490 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
491 bool OrLocal) {
472 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
473 bool OrLocal) {
492474 assert(Visited.empty() && "Visited must be cleared after use!");
493475
494476 unsigned MaxLookup = 8;
495477 SmallVector Worklist;
496478 Worklist.push_back(Loc.Ptr);
497479 do {
498 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
480 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
499481 if (!Visited.insert(V).second) {
500482 Visited.clear();
501 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
483 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
502484 }
503485
504486 // An alloca instruction defines local memory.
512494 // others. GV may even be a declaration, not a definition.
513495 if (!GV->isConstant()) {
514496 Visited.clear();
515 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
497 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
516498 }
517499 continue;
518500 }
530512 // Don't bother inspecting phi nodes with many operands.
531513 if (PN->getNumIncomingValues() > MaxLookup) {
532514 Visited.clear();
533 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
515 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
534516 }
535517 for (Value *IncValue : PN->incoming_values())
536518 Worklist.push_back(IncValue);
539521
540522 // Otherwise be conservative.
541523 Visited.clear();
542 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
524 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
543525
544526 } while (!Worklist.empty() && --MaxLookup);
545527
565547 }
566548
567549 /// Returns the behavior when calling the given call site.
568 FunctionModRefBehavior
569 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
550 FunctionModRefBehavior BasicAAResult::getModRefBehavior(ImmutableCallSite CS) {
570551 if (CS.doesNotAccessMemory())
571552 // Can't do better than this.
572553 return FMRB_DoesNotAccessMemory;
581562 if (CS.onlyAccessesArgMemory())
582563 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
583564
584 // The AliasAnalysis base class has some smarts, lets use them.
585 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
565 // The AAResultBase base class has some smarts, lets use them.
566 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(CS) & Min);
586567 }
587568
588569 /// Returns the behavior when calling the given function. For use when the call
589570 /// site is not known.
590 FunctionModRefBehavior
591 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
571 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
592572 // If the function declares it doesn't access memory, we can't do better.
593573 if (F->doesNotAccessMemory())
594574 return FMRB_DoesNotAccessMemory;
602582 if (F->onlyAccessesArgMemory())
603583 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
604584
605 const TargetLibraryInfo &TLI =
606 getAnalysis().getTLI();
607585 if (isMemsetPattern16(F, TLI))
608586 Min = FMRB_OnlyAccessesArgumentPointees;
609587
610588 // Otherwise be conservative.
611 return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
612 }
613
614 ModRefInfo BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS,
615 unsigned ArgIdx) {
589 return FunctionModRefBehavior(AAResultBase::getModRefBehavior(F) & Min);
590 }
591
592 ModRefInfo BasicAAResult::getArgModRefInfo(ImmutableCallSite CS,
593 unsigned ArgIdx) {
616594 if (const IntrinsicInst *II = dyn_cast(CS.getInstruction()))
617595 switch (II->getIntrinsicID()) {
618596 default:
630608 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
631609 // whenever possible.
632610 if (CS.getCalledFunction() &&
633 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
611 isMemsetPattern16(CS.getCalledFunction(), TLI)) {
634612 assert((ArgIdx == 0 || ArgIdx == 1) &&
635613 "Invalid argument index for memset_pattern16");
636614 return ArgIdx ? MRI_Ref : MRI_Mod;
637615 }
638616 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
639617
640 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
618 return AAResultBase::getArgModRefInfo(CS, ArgIdx);
641619 }
642620
643621 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
646624 return true;
647625
648626 return false;
649 }
650
651 bool BasicAliasAnalysis::doInitialization(Module &M) {
652 InitializeAliasAnalysis(this, &M.getDataLayout());
653 return true;
654627 }
655628
656629 /// Checks to see if the specified callsite can clobber the specified memory
659632 /// Since we only look at local properties of this function, we really can't
660633 /// say much about this query. We do, however, use simple "address taken"
661634 /// analysis on local objects.
662 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
663 const MemoryLocation &Loc) {
635 ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS,
636 const MemoryLocation &Loc) {
664637 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
665638 "AliasAnalysis query involving multiple functions!");
666639
667 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
640 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
668641
669642 // If this is a tail call and Loc.Ptr points to a stack location, we know that
670643 // the tail call cannot access or modify the local stack.
696669 // is impossible to alias the pointer we're checking. If not, we have to
697670 // assume that the call could touch the pointer, even though it doesn't
698671 // escape.
699 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
672 AliasResult AR =
673 getBestAAResults().alias(MemoryLocation(*CI), MemoryLocation(Object));
674 if (AR) {
700675 PassedAsArg = true;
701676 break;
702677 }
712687 if (isAssumeIntrinsic(CS))
713688 return MRI_NoModRef;
714689
715 // The AliasAnalysis base class has some smarts, lets use them.
716 return AliasAnalysis::getModRefInfo(CS, Loc);
717 }
718
719 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
720 ImmutableCallSite CS2) {
690 // The AAResultBase base class has some smarts, lets use them.
691 return AAResultBase::getModRefInfo(CS, Loc);
692 }
693
694 ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS1,
695 ImmutableCallSite CS2) {
721696 // While the assume intrinsic is marked as arbitrarily writing so that
722697 // proper control dependencies will be maintained, it never aliases any
723698 // particular memory location.
724699 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
725700 return MRI_NoModRef;
726701
727 // The AliasAnalysis base class has some smarts, lets use them.
728 return AliasAnalysis::getModRefInfo(CS1, CS2);
702 // The AAResultBase base class has some smarts, lets use them.
703 return AAResultBase::getModRefInfo(CS1, CS2);
729704 }
730705
731706 /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
828803 /// We know that V1 is a GEP, but we don't know anything about V2.
829804 /// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
830805 /// V2.
831 AliasResult BasicAliasAnalysis::aliasGEP(
832 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
833 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
834 const Value *UnderlyingV1, const Value *UnderlyingV2) {
806 AliasResult BasicAAResult::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
807 const AAMDNodes &V1AAInfo, const Value *V2,
808 uint64_t V2Size, const AAMDNodes &V2AAInfo,
809 const Value *UnderlyingV1,
810 const Value *UnderlyingV2) {
835811 int64_t GEP1BaseOffset;
836812 bool GEP1MaxLookupReached;
837813 SmallVector GEP1VariableIndices;
838
839 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
840 // different functions.
841 // FIXME: This really doesn't make any sense. We get a dominator tree below
842 // that can only refer to a single function. But this function (aliasGEP) is
843 // a method on an immutable pass that can be called when there *isn't*
844 // a single function. The old pass management layer makes this "work", but
845 // this isn't really a clean solution.
846 AssumptionCacheTracker &ACT = getAnalysis();
847 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
848 if (auto *GEP1I = dyn_cast(GEP1))
849 AC1 = &ACT.getAssumptionCache(
850 const_cast(*GEP1I->getParent()->getParent()));
851 if (auto *I2 = dyn_cast(V2))
852 AC2 = &ACT.getAssumptionCache(
853 const_cast(*I2->getParent()->getParent()));
854
855 DominatorTreeWrapperPass *DTWP =
856 getAnalysisIfAvailable();
857 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
858814
859815 // If we have two gep instructions with must-alias or not-alias'ing base
860816 // pointers, figure out if the indexes to the GEP tell us anything about the
879835 SmallVector GEP2VariableIndices;
880836 const Value *GEP2BasePtr =
881837 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
882 GEP2MaxLookupReached, *DL, AC2, DT);
838 GEP2MaxLookupReached, DL, &AC, DT);
883839 const Value *GEP1BasePtr =
884840 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
885 GEP1MaxLookupReached, *DL, AC1, DT);
841 GEP1MaxLookupReached, DL, &AC, DT);
886842 // DecomposeGEPExpression and GetUnderlyingObject should return the
887843 // same result except when DecomposeGEPExpression has no DataLayout.
844 // FIXME: They always have a DataLayout so this should become an
845 // assert.
888846 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
889 assert(!DL &&
890 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
891847 return MayAlias;
892848 }
893849 // If the max search depth is reached the result is undefined
912868 // about the relation of the resulting pointer.
913869 const Value *GEP1BasePtr =
914870 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
915 GEP1MaxLookupReached, *DL, AC1, DT);
871 GEP1MaxLookupReached, DL, &AC, DT);
916872
917873 int64_t GEP2BaseOffset;
918874 bool GEP2MaxLookupReached;
919875 SmallVector GEP2VariableIndices;
920876 const Value *GEP2BasePtr =
921877 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
922 GEP2MaxLookupReached, *DL, AC2, DT);
878 GEP2MaxLookupReached, DL, &AC, DT);
923879
924880 // DecomposeGEPExpression and GetUnderlyingObject should return the
925881 // same result except when DecomposeGEPExpression has no DataLayout.
882 // FIXME: They always have a DataLayout so this should become an assert.
926883 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
927 assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
928884 return MayAlias;
929885 }
930886
931887 // If we know the two GEPs are based off of the exact same pointer (and not
932888 // just the same underlying object), see if that tells us anything about
933889 // the resulting pointers.
934 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
935 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
890 if (GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
891 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
936892 // If we couldn't find anything interesting, don't abandon just yet.
937893 if (R != MayAlias)
938894 return R;
969925
970926 const Value *GEP1BasePtr =
971927 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
972 GEP1MaxLookupReached, *DL, AC1, DT);
928 GEP1MaxLookupReached, DL, &AC, DT);
973929
974930 // DecomposeGEPExpression and GetUnderlyingObject should return the
975931 // same result except when DecomposeGEPExpression has no DataLayout.
932 // FIXME: They always have a DataLayout so this should become an assert.
976933 if (GEP1BasePtr != UnderlyingV1) {
977 assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
978934 return MayAlias;
979935 }
980936 // If the max search depth is reached the result is undefined
1038994 const Value *V = GEP1VariableIndices[i].V;
1039995
1040996 bool SignKnownZero, SignKnownOne;
1041 ComputeSignBit(const_cast(V), SignKnownZero, SignKnownOne, *DL,
1042 0, AC1, nullptr, DT);
997 ComputeSignBit(const_cast(V), SignKnownZero, SignKnownOne, DL,
998 0, &AC, nullptr, DT);
1043999
10441000 // Zero-extension widens the variable, and so forces the sign
10451001 // bit to zero.
10741030 return NoAlias;
10751031
10761032 if (constantOffsetHeuristic(GEP1VariableIndices, V1Size, V2Size,
1077 GEP1BaseOffset, DL, AC1, DT))
1033 GEP1BaseOffset, &AC, DT))
10781034 return NoAlias;
10791035 }
10801036
11021058
11031059 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
11041060 /// against another.
1105 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1106 uint64_t SISize,
1107 const AAMDNodes &SIAAInfo,
1108 const Value *V2, uint64_t V2Size,
1109 const AAMDNodes &V2AAInfo) {
1061 AliasResult BasicAAResult::aliasSelect(const SelectInst *SI, uint64_t SISize,
1062 const AAMDNodes &SIAAInfo,
1063 const Value *V2, uint64_t V2Size,
1064 const AAMDNodes &V2AAInfo) {
11101065 // If the values are Selects with the same condition, we can do a more precise
11111066 // check: just check for aliases between the values on corresponding arms.
11121067 if (const SelectInst *SI2 = dyn_cast(V2))
11351090
11361091 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
11371092 /// another.
1138 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1139 const AAMDNodes &PNAAInfo,
1140 const Value *V2, uint64_t V2Size,
1141 const AAMDNodes &V2AAInfo) {
1093 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, uint64_t PNSize,
1094 const AAMDNodes &PNAAInfo, const Value *V2,
1095 uint64_t V2Size,
1096 const AAMDNodes &V2AAInfo) {
11421097 // Track phi nodes we have visited. We use this information when we determine
11431098 // value equivalence.
11441099 VisitedPhiBBs.insert(PN->getParent());
12411196
12421197 /// Provideis a bunch of ad-hoc rules to disambiguate in common cases, such as
12431198 /// array references.
1244 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1245 AAMDNodes V1AAInfo, const Value *V2,
1246 uint64_t V2Size,
1247 AAMDNodes V2AAInfo) {
1199 AliasResult BasicAAResult::aliasCheck(const Value *V1, uint64_t V1Size,
1200 AAMDNodes V1AAInfo, const Value *V2,
1201 uint64_t V2Size, AAMDNodes V2AAInfo) {
12481202 // If either of the memory references is empty, it doesn't matter what the
12491203 // pointer values are.
12501204 if (V1Size == 0 || V2Size == 0)
12721226 return NoAlias; // Scalars cannot alias each other
12731227
12741228 // Figure out what objects these things are pointing to if we can.
1275 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1276 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
1229 const Value *O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1230 const Value *O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
12771231
12781232 // Null values in the default address space don't point to any object, so they
12791233 // don't alias any other pointer.
13221276
13231277 // If the size of one access is larger than the entire object on the other
13241278 // side, then we know such behavior is undefined and can assume no alias.
1325 if (DL)
1326 if ((V1Size != MemoryLocation::UnknownSize &&
1327 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1328 (V2Size != MemoryLocation::UnknownSize &&
1329 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1330 return NoAlias;
1279 if ((V1Size != MemoryLocation::UnknownSize &&
1280 isObjectSmallerThan(O2, V1Size, DL, TLI)) ||
1281 (V2Size != MemoryLocation::UnknownSize &&
1282 isObjectSmallerThan(O1, V2Size, DL, TLI)))
1283 return NoAlias;
13311284
13321285 // Check the cache before climbing up use-def chains. This also terminates
13331286 // otherwise infinitely recursive queries.
13811334 // If both pointers are pointing into the same object and one of them
13821335 // accesses is accessing the entire object, then the accesses must
13831336 // overlap in some way.
1384 if (DL && O1 == O2)
1337 if (O1 == O2)
13851338 if ((V1Size != MemoryLocation::UnknownSize &&
1386 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1339 isObjectSize(O1, V1Size, DL, TLI)) ||
13871340 (V2Size != MemoryLocation::UnknownSize &&
1388 isObjectSize(O2, V2Size, *DL, *TLI)))
1341 isObjectSize(O2, V2Size, DL, TLI)))
13891342 return AliasCache[Locs] = PartialAlias;
13901343
1391 AliasResult Result =
1392 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1393 MemoryLocation(V2, V2Size, V2AAInfo));
1344 // Recurse back into the best AA results we have, potentially with refined
1345 // memory locations. We have already ensured that BasicAA has a MayAlias
1346 // cache result for these, so any recursion back into BasicAA won't loop.
1347 AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second);
13941348 return AliasCache[Locs] = Result;
13951349 }
13961350
14011355 /// visited phi nodes an making sure that the phis cannot reach the value. We
14021356 /// have to do this because we are looking through phi nodes (That is we say
14031357 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1404 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1405 const Value *V2) {
1358 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1359 const Value *V2) {
14061360 if (V != V2)
14071361 return false;
14081362
14151369
14161370 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
14171371 return false;
1418
1419 // Use dominance or loop info if available.
1420 DominatorTreeWrapperPass *DTWP =
1421 getAnalysisIfAvailable();
1422 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1423 auto *LIWP = getAnalysisIfAvailable();
1424 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
14251372
14261373 // Make sure that the visited phis cannot reach the Value. This ensures that
14271374 // the Values cannot come from different iterations of a potential cycle the
14371384 ///
14381385 /// Dest and Src are the variable indices from two decomposed GetElementPtr
14391386 /// instructions GEP1 and GEP2 which have common base pointers.
1440 void BasicAliasAnalysis::GetIndexDifference(
1387 void BasicAAResult::GetIndexDifference(
14411388 SmallVectorImpl &Dest,
14421389 const SmallVectorImpl &Src) {
14431390 if (Src.empty())
14731420 }
14741421 }
14751422
1476 bool BasicAliasAnalysis::constantOffsetHeuristic(
1423 bool BasicAAResult::constantOffsetHeuristic(
14771424 const SmallVectorImpl &VarIndices, uint64_t V1Size,
1478 uint64_t V2Size, int64_t BaseOffset, const DataLayout *DL,
1479 AssumptionCache *AC, DominatorTree *DT) {
1425 uint64_t V2Size, int64_t BaseOffset, AssumptionCache *AC,
1426 DominatorTree *DT) {
14801427 if (VarIndices.size() != 2 || V1Size == MemoryLocation::UnknownSize ||
1481 V2Size == MemoryLocation::UnknownSize || !DL)
1428 V2Size == MemoryLocation::UnknownSize)
14821429 return false;
14831430
14841431 const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
14981445 bool NSW = true, NUW = true;
14991446 unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
15001447 const Value *V0 = GetLinear