1 //===- ScopedNoAliasAA.cpp - Scoped No-Alias Alias Analysis ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ScopedNoAlias alias-analysis pass, which implements
10 // metadata-based scoped no-alias support.
11 //
12 // Alias-analysis scopes are defined by an id (which can be a string or some
13 // other metadata node), a domain node, and an optional descriptive string.
14 // A domain is defined by an id (which can be a string or some other metadata
15 // node), and an optional descriptive string.
16 //
17 // !dom0 =   metadata !{ metadata !"domain of foo()" }
18 // !scope1 = metadata !{ metadata !scope1, metadata !dom0, metadata !"scope 1" }
19 // !scope2 = metadata !{ metadata !scope2, metadata !dom0, metadata !"scope 2" }
20 //
21 // Loads and stores can be tagged with an alias-analysis scope, and also, with
22 // a noalias tag for a specific scope:
23 //
24 // ... = load %ptr1, !alias.scope !{ !scope1 }
25 // ... = load %ptr2, !alias.scope !{ !scope1, !scope2 }, !noalias !{ !scope1 }
26 //
27 // When evaluating an aliasing query, if one of the instructions is associated
28 // has a set of noalias scopes in some domain that is a superset of the alias
29 // scopes in that domain of some other instruction, then the two memory
30 // accesses are assumed not to alias.
31 //
32 //===----------------------------------------------------------------------===//
33 
34 #include "llvm/Analysis/ScopedNoAliasAA.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/Analysis/MemoryLocation.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 
45 using namespace llvm;
46 
47 // A handy option for disabling scoped no-alias functionality. The same effect
48 // can also be achieved by stripping the associated metadata tags from IR, but
49 // this option is sometimes more convenient.
50 static cl::opt<bool> EnableScopedNoAlias("enable-scoped-noalias",
51                                          cl::init(true), cl::Hidden);
52 
53 namespace {
54 
55 /// This is a simple wrapper around an MDNode which provides a higher-level
56 /// interface by hiding the details of how alias analysis information is encoded
57 /// in its operands.
58 class AliasScopeNode {
59   const MDNode *Node = nullptr;
60 
61 public:
62   AliasScopeNode() = default;
63   explicit AliasScopeNode(const MDNode *N) : Node(N) {}
64 
65   /// Get the MDNode for this AliasScopeNode.
66   const MDNode *getNode() const { return Node; }
67 
68   /// Get the MDNode for this AliasScopeNode's domain.
69   const MDNode *getDomain() const {
70     if (Node->getNumOperands() < 2)
71       return nullptr;
72     return dyn_cast_or_null<MDNode>(Node->getOperand(1));
73   }
74 };
75 
76 } // end anonymous namespace
77 
78 AliasResult ScopedNoAliasAAResult::alias(const MemoryLocation &LocA,
79                                          const MemoryLocation &LocB,
80                                          AAQueryInfo &AAQI) {
81   if (!EnableScopedNoAlias)
82     return AAResultBase::alias(LocA, LocB, AAQI);
83 
84   // Get the attached MDNodes.
85   const MDNode *AScopes = LocA.AATags.Scope, *BScopes = LocB.AATags.Scope;
86 
87   const MDNode *ANoAlias = LocA.AATags.NoAlias, *BNoAlias = LocB.AATags.NoAlias;
88 
89   if (!mayAliasInScopes(AScopes, BNoAlias))
90     return NoAlias;
91 
92   if (!mayAliasInScopes(BScopes, ANoAlias))
93     return NoAlias;
94 
95   // If they may alias, chain to the next AliasAnalysis.
96   return AAResultBase::alias(LocA, LocB, AAQI);
97 }
98 
99 ModRefInfo ScopedNoAliasAAResult::getModRefInfo(const CallBase *Call,
100                                                 const MemoryLocation &Loc,
101                                                 AAQueryInfo &AAQI) {
102   if (!EnableScopedNoAlias)
103     return AAResultBase::getModRefInfo(Call, Loc, AAQI);
104 
105   if (!mayAliasInScopes(Loc.AATags.Scope,
106                         Call->getMetadata(LLVMContext::MD_noalias)))
107     return ModRefInfo::NoModRef;
108 
109   if (!mayAliasInScopes(Call->getMetadata(LLVMContext::MD_alias_scope),
110                         Loc.AATags.NoAlias))
111     return ModRefInfo::NoModRef;
112 
113   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
114 }
115 
116 ModRefInfo ScopedNoAliasAAResult::getModRefInfo(const CallBase *Call1,
117                                                 const CallBase *Call2,
118                                                 AAQueryInfo &AAQI) {
119   if (!EnableScopedNoAlias)
120     return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
121 
122   if (!mayAliasInScopes(Call1->getMetadata(LLVMContext::MD_alias_scope),
123                         Call2->getMetadata(LLVMContext::MD_noalias)))
124     return ModRefInfo::NoModRef;
125 
126   if (!mayAliasInScopes(Call2->getMetadata(LLVMContext::MD_alias_scope),
127                         Call1->getMetadata(LLVMContext::MD_noalias)))
128     return ModRefInfo::NoModRef;
129 
130   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
131 }
132 
133 static void collectMDInDomain(const MDNode *List, const MDNode *Domain,
134                               SmallPtrSetImpl<const MDNode *> &Nodes) {
135   for (const MDOperand &MDOp : List->operands())
136     if (const MDNode *MD = dyn_cast<MDNode>(MDOp))
137       if (AliasScopeNode(MD).getDomain() == Domain)
138         Nodes.insert(MD);
139 }
140 
141 bool ScopedNoAliasAAResult::mayAliasInScopes(const MDNode *Scopes,
142                                              const MDNode *NoAlias) const {
143   if (!Scopes || !NoAlias)
144     return true;
145 
146   // Collect the set of scope domains relevant to the noalias scopes.
147   SmallPtrSet<const MDNode *, 16> Domains;
148   for (const MDOperand &MDOp : NoAlias->operands())
149     if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
150       if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
151         Domains.insert(Domain);
152 
153   // We alias unless, for some domain, the set of noalias scopes in that domain
154   // is a superset of the set of alias scopes in that domain.
155   for (const MDNode *Domain : Domains) {
156     SmallPtrSet<const MDNode *, 16> ScopeNodes;
157     collectMDInDomain(Scopes, Domain, ScopeNodes);
158     if (ScopeNodes.empty())
159       continue;
160 
161     SmallPtrSet<const MDNode *, 16> NANodes;
162     collectMDInDomain(NoAlias, Domain, NANodes);
163 
164     // To not alias, all of the nodes in ScopeNodes must be in NANodes.
165     bool FoundAll = true;
166     for (const MDNode *SMD : ScopeNodes)
167       if (!NANodes.count(SMD)) {
168         FoundAll = false;
169         break;
170       }
171 
172     if (FoundAll)
173       return false;
174   }
175 
176   return true;
177 }
178 
179 AnalysisKey ScopedNoAliasAA::Key;
180 
181 ScopedNoAliasAAResult ScopedNoAliasAA::run(Function &F,
182                                            FunctionAnalysisManager &AM) {
183   return ScopedNoAliasAAResult();
184 }
185 
186 char ScopedNoAliasAAWrapperPass::ID = 0;
187 
188 INITIALIZE_PASS(ScopedNoAliasAAWrapperPass, "scoped-noalias",
189                 "Scoped NoAlias Alias Analysis", false, true)
190 
191 ImmutablePass *llvm::createScopedNoAliasAAWrapperPass() {
192   return new ScopedNoAliasAAWrapperPass();
193 }
194 
195 ScopedNoAliasAAWrapperPass::ScopedNoAliasAAWrapperPass() : ImmutablePass(ID) {
196   initializeScopedNoAliasAAWrapperPassPass(*PassRegistry::getPassRegistry());
197 }
198 
199 bool ScopedNoAliasAAWrapperPass::doInitialization(Module &M) {
200   Result.reset(new ScopedNoAliasAAResult());
201   return false;
202 }
203 
204 bool ScopedNoAliasAAWrapperPass::doFinalization(Module &M) {
205   Result.reset();
206   return false;
207 }
208 
209 void ScopedNoAliasAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
210   AU.setPreservesAll();
211 }
212