Polly 24.0.0git
IRBuilder.cpp
Go to the documentation of this file.
1//===------ PollyIRBuilder.cpp --------------------------------------------===//
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// The Polly IRBuilder file contains Polly specific extensions for the IRBuilder
10// that are used e.g. to emit the llvm.loop.parallel metadata.
11//
12//===----------------------------------------------------------------------===//
13
15#include "polly/ScopInfo.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/IR/Metadata.h"
19
20using namespace llvm;
21using namespace polly;
22
23static const int MaxArraysInAliasScops = 10;
24
25/// Get a self referencing id metadata node.
26///
27/// The MDNode looks like this (if arg0/arg1 are not null):
28///
29/// '!n = distinct !{!n, arg0, arg1}'
30///
31/// @return The self referencing id metadata node.
32static MDNode *getID(LLVMContext &Ctx, Metadata *arg0 = nullptr,
33 Metadata *arg1 = nullptr) {
34 MDNode *ID;
35 SmallVector<Metadata *, 3> Args;
36 // Reserve operand 0 for loop id self reference.
37 Args.push_back(nullptr);
38
39 if (arg0)
40 Args.push_back(arg0);
41 if (arg1)
42 Args.push_back(arg1);
43
44 ID = MDNode::getDistinct(Ctx, Args);
45 ID->replaceOperandWith(0, ID);
46 return ID;
47}
48
50 // Push an empty staging BandAttr.
51 LoopAttrEnv.emplace_back();
52}
53
55 assert(LoopAttrEnv.size() == 1 && "Loop stack imbalance");
56 assert(!getStagingAttrEnv() && "Forgot to clear staging attr env");
57}
58
60 SE = S.getSE();
61
62 LLVMContext &Ctx = SE->getContext();
63 AliasScopeDomain = getID(Ctx, MDString::get(Ctx, "polly.alias.scope.domain"));
64
65 AliasScopeMap.clear();
67
68 // We are only interested in arrays, but no scalar references. Scalars should
69 // be handled easily by basicaa.
70 SmallVector<ScopArrayInfo *, 10> Arrays;
71 for (ScopArrayInfo *Array : S.arrays())
72 if (Array->isArrayKind())
73 Arrays.push_back(Array);
74
75 // The construction of alias scopes is quadratic in the number of arrays
76 // involved. In case of too many arrays, skip the construction of alias
77 // information to avoid quadratic increases in compile time and code size.
78 if (Arrays.size() > MaxArraysInAliasScops)
79 return;
80
81 std::string AliasScopeStr = "polly.alias.scope.";
82 for (const ScopArrayInfo *Array : Arrays) {
83 assert(Array->getBasePtr() && "Base pointer must be present");
84 AliasScopeMap[Array->getBasePtr()] =
86 MDString::get(Ctx, (AliasScopeStr + Array->getName()).c_str()));
87 }
88
89 for (const ScopArrayInfo *Array : Arrays) {
90 MDNode *AliasScopeList = MDNode::get(Ctx, {});
91 for (const auto &AliasScopePair : AliasScopeMap) {
92 if (Array->getBasePtr() == AliasScopePair.first)
93 continue;
94
95 Metadata *Args = {AliasScopePair.second};
96 AliasScopeList =
97 MDNode::concatenate(AliasScopeList, MDNode::get(Ctx, Args));
98 }
99
100 OtherAliasScopeListMap[Array->getBasePtr()] = AliasScopeList;
101 }
102}
103
104void ScopAnnotator::pushLoop(Loop *L, bool IsParallel) {
105 ActiveLoops.push_back(L);
106
107 if (IsParallel) {
108 LLVMContext &Ctx = SE->getContext();
109 MDNode *AccessGroup = MDNode::getDistinct(Ctx, {});
110 ParallelLoops.push_back(AccessGroup);
111 }
112
113 // Open an empty BandAttr context for loops nested in this one.
114 LoopAttrEnv.emplace_back();
115}
116
117void ScopAnnotator::popLoop(bool IsParallel) {
118 ActiveLoops.pop_back();
119
120 if (IsParallel) {
121 assert(!ParallelLoops.empty() && "Expected a parallel loop to pop");
122 ParallelLoops.pop_back();
123 }
124
125 // Exit the subloop context.
126 assert(!getStagingAttrEnv() && "Forgot to clear staging attr env");
127 assert(LoopAttrEnv.size() >= 2 && "Popped too many");
128 LoopAttrEnv.pop_back();
129}
130
131static void addVectorizeMetadata(LLVMContext &Ctx,
132 SmallVector<Metadata *, 3> *Args,
133 bool EnableLoopVectorizer) {
134 MDString *PropName =
135 MDString::get(Ctx, EnableLoopVectorizer ? "llvm.loop.vectorize.enable"
136 : "llvm.loop.vectorize.disable");
137 Args->push_back(MDNode::get(Ctx, {PropName}));
138}
139
140void addParallelMetadata(LLVMContext &Ctx, SmallVector<Metadata *, 3> *Args,
141 llvm::SmallVector<llvm::MDNode *, 8> ParallelLoops) {
142 MDString *PropName = MDString::get(Ctx, "llvm.loop.parallel_accesses");
143 MDNode *AccGroup = ParallelLoops.back();
144 Args->push_back(MDNode::get(Ctx, {PropName, AccGroup}));
145}
146
148 CondBrInst *B, bool IsParallel,
149 std::optional<bool> EnableVectorizeMetadata) const {
150 LLVMContext &Ctx = SE->getContext();
151 SmallVector<Metadata *, 3> Args;
152
153 // For the LoopID self-reference.
154 Args.push_back(nullptr);
155
156 // Add the user-defined loop properties to the annotation, if any. Any
157 // additional properties are appended.
158 // FIXME: What to do if these conflict?
159 MDNode *MData = nullptr;
160 if (BandAttr *AttrEnv = getActiveAttrEnv()) {
161 MData = AttrEnv->Metadata;
162 if (MData)
163 llvm::append_range(Args, drop_begin(MData->operands(), 1));
164 }
165 if (IsParallel)
167 if (EnableVectorizeMetadata.has_value())
168 addVectorizeMetadata(Ctx, &Args, *EnableVectorizeMetadata);
169
170 // No metadata to annotate.
171 if (!MData && Args.size() <= 1)
172 return;
173
174 // Reuse the MData node if possible, this will avoid having to create another
175 // one that cannot be merged because LoopIDs are 'distinct'. However, we have
176 // to create a new one if we add properties.
177 if (!MData || Args.size() > MData->getNumOperands()) {
178 MData = MDNode::getDistinct(Ctx, Args);
179 MData->replaceOperandWith(0, MData);
180 }
181 B->setMetadata(LLVMContext::MD_loop, MData);
182}
183
184/// Get the pointer operand
185///
186/// @param Inst The instruction to be analyzed.
187/// @return the pointer operand in case @p Inst is a memory access
188/// instruction and nullptr otherwise.
189static llvm::Value *getMemAccInstPointerOperand(Instruction *Inst) {
190 auto MemInst = MemAccInst::dyn_cast(Inst);
191 if (!MemInst)
192 return nullptr;
193
194 return MemInst.getPointerOperand();
195}
196
197/// Find the base pointer of an array access.
198///
199/// This should be equivalent to ScalarEvolution::getPointerBase, which we
200/// cannot use here the IR is still under construction which ScalarEvolution
201/// assumes to not be modified.
202static Value *findBasePtr(Value *Val) {
203 while (true) {
204 if (auto *Gep = dyn_cast<GEPOperator>(Val)) {
205 Val = Gep->getPointerOperand();
206 continue;
207 }
208 if (auto *Cast = dyn_cast<BitCastOperator>(Val)) {
209 Val = Cast->getOperand(0);
210 continue;
211 }
212
213 break;
214 }
215
216 return Val;
217}
218
219void ScopAnnotator::annotate(Instruction *Inst) {
220 if (!Inst->mayReadOrWriteMemory())
221 return;
222
223 switch (ParallelLoops.size()) {
224 case 0:
225 // Not parallel to anything: no access group needed.
226 break;
227 case 1:
228 // Single parallel loop: use directly.
229 Inst->setMetadata(LLVMContext::MD_access_group,
230 cast<MDNode>(ParallelLoops.front()));
231 break;
232 default:
233 // Parallel to multiple loops: refer to list of access groups.
234 Inst->setMetadata(LLVMContext::MD_access_group,
235 MDNode::get(SE->getContext(),
236 ArrayRef<Metadata *>(
237 (Metadata *const *)ParallelLoops.data(),
238 ParallelLoops.size())));
239 break;
240 }
241
242 // TODO: Use the ScopArrayInfo once available here.
243 if (!AliasScopeDomain)
244 return;
245
246 // Do not apply annotations on memory operations that take more than one
247 // pointer. It would be ambiguous to which pointer the annotation applies.
248 // FIXME: How can we specify annotations for all pointer arguments?
249 if (isa<CallInst>(Inst) && !isa<MemSetInst>(Inst))
250 return;
251
252 auto *Ptr = getMemAccInstPointerOperand(Inst);
253 if (!Ptr)
254 return;
255
256 Value *BasePtr = findBasePtr(Ptr);
257 if (!BasePtr)
258 return;
259
260 auto AliasScope = AliasScopeMap.lookup(BasePtr);
261
262 if (!AliasScope) {
263 BasePtr = AlternativeAliasBases.lookup(BasePtr);
264 if (!BasePtr)
265 return;
266
267 AliasScope = AliasScopeMap.lookup(BasePtr);
268 if (!AliasScope)
269 return;
270 }
271
272 assert(OtherAliasScopeListMap.count(BasePtr) &&
273 "BasePtr either expected in AliasScopeMap and OtherAlias...Map");
274 auto *OtherAliasScopeList = OtherAliasScopeListMap[BasePtr];
275
276 Inst->setMetadata("alias.scope", MDNode::get(SE->getContext(), AliasScope));
277 Inst->setMetadata("noalias", OtherAliasScopeList);
278}
static MDNode * getID(LLVMContext &Ctx, Metadata *arg0=nullptr, Metadata *arg1=nullptr)
Get a self referencing id metadata node.
Definition IRBuilder.cpp:32
static void addVectorizeMetadata(LLVMContext &Ctx, SmallVector< Metadata *, 3 > *Args, bool EnableLoopVectorizer)
void addParallelMetadata(LLVMContext &Ctx, SmallVector< Metadata *, 3 > *Args, llvm::SmallVector< llvm::MDNode *, 8 > ParallelLoops)
static Value * findBasePtr(Value *Val)
Find the base pointer of an array access.
static llvm::Value * getMemAccInstPointerOperand(Instruction *Inst)
Get the pointer operand.
static const int MaxArraysInAliasScops
Definition IRBuilder.cpp:23
static MemAccInst dyn_cast(llvm::Value &V)
Definition ScopHelper.h:179
llvm::SmallVector< BandAttr *, 8 > LoopAttrEnv
Stack for surrounding BandAttr annotations.
Definition IRBuilder.h:89
llvm::SmallVector< llvm::MDNode *, 8 > ParallelLoops
Access groups for the parallel loops currently under construction.
Definition IRBuilder.h:103
void annotateLoopLatch(llvm::CondBrInst *B, bool IsParallel, std::optional< bool > EnableVectorizeMetadata=std::nullopt) const
Annotate the loop latch B.
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::MDNode * > OtherAliasScopeListMap
A map from base pointers to an alias scope list of other pointers.
Definition IRBuilder.h:113
BandAttr *& getStagingAttrEnv()
Definition IRBuilder.h:90
void buildAliasScopes(Scop &S)
Build all alias scopes for the given SCoP.
Definition IRBuilder.cpp:59
void annotate(llvm::Instruction *I)
Annotate the new instruction I for all parallel loops.
llvm::MapVector< llvm::AssertingVH< llvm::Value >, llvm::MDNode * > AliasScopeMap
A map from base pointers to its alias scope.
Definition IRBuilder.h:109
llvm::ScalarEvolution * SE
The ScalarEvolution analysis we use to find base pointers.
Definition IRBuilder.h:97
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > AlternativeAliasBases
Definition IRBuilder.h:116
void pushLoop(llvm::Loop *L, bool IsParallel)
Add a new loop L which is parallel if IsParallel is true.
llvm::SmallVector< llvm::Loop *, 8 > ActiveLoops
All loops currently under construction.
Definition IRBuilder.h:100
void popLoop(bool isParallel)
Remove the last added loop.
BandAttr * getActiveAttrEnv() const
Definition IRBuilder.h:91
llvm::MDNode * AliasScopeDomain
The alias scope domain for the current SCoP.
Definition IRBuilder.h:106
A class to store information about arrays in the SCoP.
Definition ScopInfo.h:215
Static Control Part.
Definition ScopInfo.h:1626
B()
const char * arg1
Definition isl_test.c:871
#define assert(exp)
@ Array
MemoryKind::Array: Models a one or multi-dimensional array.
Definition ScopInfo.h:111
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:150
Represent the attributes of a loop.
Definition ScopHelper.h:538
static TupleKindPtr Ctx