blob: 91a8ea281a7e70595392967ea0302b840b136dce [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
15// This represantation is shared among several tools in the polyhedral
16// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
20#include "polly/ScopInfo.h"
21
22#include "polly/TempScopInfo.h"
23#include "polly/LinkAllPasses.h"
24#include "polly/Support/GICHelper.h"
25#include "polly/Support/ScopHelper.h"
26
27#include "llvm/Analysis/LoopInfo.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/Analysis/RegionIterator.h"
30#include "llvm/Assembly/Writer.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/Support/CommandLine.h"
34
35#define DEBUG_TYPE "polly-scops"
36#include "llvm/Support/Debug.h"
37
38#include "isl/constraint.h"
39#include "isl/set.h"
40#include "isl/map.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
42#include "isl/printer.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include <sstream>
44#include <string>
45#include <vector>
46
47using namespace llvm;
48using namespace polly;
49
50STATISTIC(ScopFound, "Number of valid Scops");
51STATISTIC(RichScopFound, "Number of Scops containing a loop");
52
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000053/// Convert an int into a string.
54static std::string convertInt(int number)
55{
56 if (number == 0)
57 return "0";
58 std::string temp = "";
59 std::string returnvalue = "";
60 while (number > 0)
61 {
62 temp += number % 10 + 48;
63 number /= 10;
64 }
65 for (unsigned i = 0; i < temp.length(); i++)
66 returnvalue+=temp[temp.length() - i - 1];
67 return returnvalue;
Tobias Grosser75805372011-04-29 06:27:02 +000068}
69
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000070/// Translate a SCEVExpression into an isl_pw_aff object.
71struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff*> {
72private:
73 isl_ctx *ctx;
74 int NbLoopDims;
75 const Scop *scop;
76
77 /// baseAdress is set if we analyze a memory access. It holds the base address
78 /// of this memory access.
79 const Value *baseAddress;
80
81public:
82 static isl_pw_aff *getPwAff(const ScopStmt *stmt, const SCEV *scev,
83 const Value *baseAddress) {
84 SCEVAffinator Affinator(stmt, baseAddress);
85 return Affinator.visit(scev);
86 }
87
88 isl_pw_aff *visit(const SCEV *scev) {
89 // In case the scev is contained in our list of parameters, we do not
90 // further analyze this expression, but create a new parameter in the
91 // isl_pw_aff. This allows us to treat subexpressions that we cannot
92 // translate into an piecewise affine expression, as constant parameters of
93 // the piecewise affine expression.
94 int i = 0;
95 for (Scop::const_param_iterator PI = scop->param_begin(),
96 PE = scop->param_end(); PI != PE; ++PI) {
97 if (*PI == scev) {
98 isl_id *ID = isl_id_alloc(ctx, ("p" + convertInt(i)).c_str(),
99 (void *) scev);
100 isl_dim *Dim = isl_dim_set_alloc(ctx, 1, NbLoopDims);
101 Dim = isl_dim_set_dim_id(Dim, isl_dim_param, 0, ID);
102
103 isl_set *Domain = isl_set_universe(isl_dim_copy(Dim));
104 isl_aff *Affine = isl_aff_zero(isl_local_space_from_dim(Dim));
105 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
106
107 return isl_pw_aff_alloc(Domain, Affine);
108 }
109 i++;
110 }
111
112 return SCEVVisitor<SCEVAffinator, isl_pw_aff*>::visit(scev);
113 }
114
115 SCEVAffinator(const ScopStmt *stmt, const Value *baseAddress) :
116 ctx(stmt->getParent()->getCtx()),
117 NbLoopDims(stmt->getNumIterators()),
118 scop(stmt->getParent()),
119 baseAddress(baseAddress) {};
120
121 __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Constant) {
122 ConstantInt *Value = Constant->getValue();
123 isl_int v;
124 isl_int_init(v);
125
126 // LLVM does not define if an integer value is interpreted as a signed or
127 // unsigned value. Hence, without further information, it is unknown how
128 // this value needs to be converted to GMP. At the moment, we only support
129 // signed operations. So we just interpret it as signed. Later, there are
130 // two options:
131 //
132 // 1. We always interpret any value as signed and convert the values on
133 // demand.
134 // 2. We pass down the signedness of the calculation and use it to interpret
135 // this constant correctly.
136 MPZ_from_APInt(v, Value->getValue(), /* isSigned */ true);
137
138 isl_dim *dim = isl_dim_set_alloc(ctx, 0, NbLoopDims);
139 isl_local_space *ls = isl_local_space_from_dim(isl_dim_copy(dim));
140 isl_aff *Affine = isl_aff_zero(ls);
141 isl_set *Domain = isl_set_universe(dim);
142
143 Affine = isl_aff_add_constant(Affine, v);
144 isl_int_clear(v);
145
146 return isl_pw_aff_alloc(Domain, Affine);
147 }
148
149 __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr* Expr) {
150 assert(0 && "Not yet supported");
151 }
152
153 __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr) {
154 assert(0 && "Not yet supported");
155 }
156
157 __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr* Expr) {
158 // Assuming the value is signed, a sign extension is basically a noop.
159 // TODO: Reconsider this as soon as we support unsigned values.
160 return visit(Expr->getOperand());
161 }
162
163 __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr* Expr) {
164 isl_pw_aff *Sum = visit(Expr->getOperand(0));
165
166 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
167 isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
168 Sum = isl_pw_aff_add(Sum, NextSummand);
169 }
170
171 // TODO: Check for NSW and NUW.
172
173 return Sum;
174 }
175
176 __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr* Expr) {
177 isl_pw_aff *Product = visit(Expr->getOperand(0));
178
179 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
180 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
181
182 if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
183 isl_pw_aff_free(Product);
184 isl_pw_aff_free(NextOperand);
185 return NULL;
186 }
187
188 Product = isl_pw_aff_mul(Product, NextOperand);
189 }
190
191 // TODO: Check for NSW and NUW.
192 return Product;
193 }
194
195 __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr* Expr) {
196 assert(0 && "Not yet supported");
197 }
198
199 int getLoopDepth(const Loop *L) {
200 Loop *outerLoop =
201 scop->getRegion().outermostLoopInRegion(const_cast<Loop*>(L));
202 return L->getLoopDepth() - outerLoop->getLoopDepth();
203 }
204
205 __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr* Expr) {
206 assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
207
208 isl_pw_aff *Start = visit(Expr->getStart());
209 isl_pw_aff *Step = visit(Expr->getOperand(1));
210 isl_dim *Dim = isl_dim_set_alloc (ctx, 0, NbLoopDims);
211 isl_local_space *LocalSpace = isl_local_space_from_dim (Dim);
212
213 int loopDimension = getLoopDepth(Expr->getLoop());
214
215 isl_aff *LAff = isl_aff_set_coefficient_si (isl_aff_zero (LocalSpace),
216 isl_dim_set, loopDimension, 1);
217 isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
218
219 // TODO: Do we need to check for NSW and NUW?
220 return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
221 }
222
223 __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr* Expr) {
224 isl_pw_aff *Max = visit(Expr->getOperand(0));
225
226 for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
227 isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
228 Max = isl_pw_aff_max(Max, NextOperand);
229 }
230
231 return Max;
232 }
233
234 __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr* Expr) {
235 assert(0 && "Not yet supported");
236 }
237
238 __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown* Expr) {
239 Value *Value = Expr->getValue();
240
241 isl_dim *Dim;
242
243 /// If baseAddress is set, we ignore its Value object in the scev and do not
244 /// add it to the isl_pw_aff. This is because it is regarded as defining the
245 /// name of an array, in contrast to its array subscript.
246 if (baseAddress != Value) {
247 isl_id *ID = isl_id_alloc(ctx, Value->getNameStr().c_str(), Value);
248 Dim = isl_dim_set_alloc(ctx, 1, NbLoopDims);
249 Dim = isl_dim_set_dim_id(Dim, isl_dim_param, 0, ID);
250 } else {
251 Dim = isl_dim_set_alloc(ctx, 0, NbLoopDims);
252 }
253
254 isl_set *Domain = isl_set_universe(isl_dim_copy(Dim));
255 isl_aff *Affine = isl_aff_zero(isl_local_space_from_dim(Dim));
256
257 if (baseAddress != Value)
258 Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
259
260 return isl_pw_aff_alloc(Domain, Affine);
261 }
262};
263
Tobias Grosser75805372011-04-29 06:27:02 +0000264//===----------------------------------------------------------------------===//
265
266MemoryAccess::~MemoryAccess() {
Tobias Grosser54a86e62011-08-18 06:31:46 +0000267 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000268 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000269}
270
271static void replace(std::string& str, const std::string& find,
272 const std::string& replace) {
273 size_t pos = 0;
274 while((pos = str.find(find, pos)) != std::string::npos)
275 {
276 str.replace(pos, find.length(), replace);
277 pos += replace.length();
278 }
279}
280
281static void makeIslCompatible(std::string& str) {
Tobias Grossereec4d56e2011-08-20 11:11:14 +0000282 str.erase(0, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000283 replace(str, ".", "_");
Tobias Grosser3b660f82011-08-03 00:12:11 +0000284 replace(str, "\"", "_");
Tobias Grosser75805372011-04-29 06:27:02 +0000285}
286
287void MemoryAccess::setBaseName() {
288 raw_string_ostream OS(BaseName);
289 WriteAsOperand(OS, getBaseAddr(), false);
290 BaseName = OS.str();
291
Tobias Grosser75805372011-04-29 06:27:02 +0000292 makeIslCompatible(BaseName);
293 BaseName = "MemRef_" + BaseName;
294}
295
296std::string MemoryAccess::getAccessFunctionStr() const {
297 return stringFromIslObj(getAccessFunction());
298}
299
300isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000301 isl_dim *dim = isl_dim_alloc(Statement->getIslContext(), 0,
Tobias Grosser75805372011-04-29 06:27:02 +0000302 Statement->getNumIterators(), 1);
303 setBaseName();
304
305 dim = isl_dim_set_tuple_name(dim, isl_dim_out, getBaseName().c_str());
306 dim = isl_dim_set_tuple_name(dim, isl_dim_in, Statement->getBaseName());
307
308 return isl_basic_map_universe(dim);
309}
310
311MemoryAccess::MemoryAccess(const SCEVAffFunc &AffFunc, ScopStmt *Statement) {
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000312 newAccessRelation = NULL;
Tobias Grosser75805372011-04-29 06:27:02 +0000313 BaseAddr = AffFunc.getBaseAddr();
314 Type = AffFunc.isRead() ? Read : Write;
315 statement = Statement;
316
317 setBaseName();
318
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000319 isl_pw_aff *Affine = SCEVAffinator::getPwAff(Statement, AffFunc.OriginalSCEV,
320 AffFunc.getBaseAddr());
Tobias Grosser75805372011-04-29 06:27:02 +0000321
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000322 // Devide the access function by the size of the elements in the array.
323 //
324 // A stride one array access in C expressed as A[i] is expressed in LLVM-IR
325 // as something like A[i * elementsize]. This hides the fact that two
326 // subsequent values of 'i' index two values that are stored next to each
327 // other in memory. By this devision we make this characteristic obvious
328 // again.
Tobias Grosser75805372011-04-29 06:27:02 +0000329 isl_int v;
330 isl_int_init(v);
Tobias Grosser75805372011-04-29 06:27:02 +0000331 isl_int_set_si(v, AffFunc.getElemSizeInBytes());
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000332 Affine = isl_pw_aff_scale_down(Affine, v);
333 isl_int_clear(v);
Tobias Grosser75805372011-04-29 06:27:02 +0000334
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000335 AccessRelation = isl_map_from_pw_aff(Affine);
336 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_in,
337 Statement->getBaseName());
Tobias Grosser75805372011-04-29 06:27:02 +0000338 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_out,
339 getBaseName().c_str());
Tobias Grosser30b8a092011-08-18 07:51:37 +0000340
Tobias Grosser7d4cee42011-08-19 23:34:28 +0000341 isl_dim *Model = isl_set_get_dim(Statement->getParent()->getContext());
342 AccessRelation = isl_map_align_params(AccessRelation, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000343}
344
345MemoryAccess::MemoryAccess(const Value *BaseAddress, ScopStmt *Statement) {
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000346 newAccessRelation = NULL;
Tobias Grosser75805372011-04-29 06:27:02 +0000347 BaseAddr = BaseAddress;
348 Type = Read;
349 statement = Statement;
350
351 isl_basic_map *BasicAccessMap = createBasicAccessMap(Statement);
352 AccessRelation = isl_map_from_basic_map(BasicAccessMap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000353 isl_dim *Model = isl_set_get_dim(Statement->getParent()->getContext());
354 AccessRelation = isl_map_align_params(AccessRelation, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000355}
356
357void MemoryAccess::print(raw_ostream &OS) const {
358 OS.indent(12) << (isRead() ? "Read" : "Write") << "Access := \n";
359 OS.indent(16) << getAccessFunctionStr() << ";\n";
360}
361
362void MemoryAccess::dump() const {
363 print(errs());
364}
365
366// Create a map in the size of the provided set domain, that maps from the
367// one element of the provided set domain to another element of the provided
368// set domain.
369// The mapping is limited to all points that are equal in all but the last
370// dimension and for which the last dimension of the input is strict smaller
371// than the last dimension of the output.
372//
373// getEqualAndLarger(set[i0, i1, ..., iX]):
374//
375// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
376// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
377//
378static isl_map *getEqualAndLarger(isl_dim *setDomain) {
379 isl_dim *mapDomain = isl_dim_map_from_set(setDomain);
380 isl_basic_map *bmap = isl_basic_map_universe(mapDomain);
381
382 // Set all but the last dimension to be equal for the input and output
383 //
384 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
385 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
386 for (unsigned i = 0; i < isl_basic_map_n_in(bmap) - 1; ++i) {
387 isl_int v;
388 isl_int_init(v);
389 isl_constraint *c = isl_equality_alloc(isl_basic_map_get_dim(bmap));
390
391 isl_int_set_si(v, 1);
392 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
393 isl_int_set_si(v, -1);
394 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
395
396 bmap = isl_basic_map_add_constraint(bmap, c);
397
398 isl_int_clear(v);
399 }
400
401 // Set the last dimension of the input to be strict smaller than the
402 // last dimension of the output.
403 //
404 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
405 //
406 unsigned lastDimension = isl_basic_map_n_in(bmap) - 1;
407 isl_int v;
408 isl_int_init(v);
409 isl_constraint *c = isl_inequality_alloc(isl_basic_map_get_dim(bmap));
410 isl_int_set_si(v, -1);
411 isl_constraint_set_coefficient(c, isl_dim_in, lastDimension, v);
412 isl_int_set_si(v, 1);
413 isl_constraint_set_coefficient(c, isl_dim_out, lastDimension, v);
414 isl_int_set_si(v, -1);
415 isl_constraint_set_constant(c, v);
416 isl_int_clear(v);
417
418 bmap = isl_basic_map_add_constraint(bmap, c);
419
420 return isl_map_from_basic_map(bmap);
421}
422
423isl_set *MemoryAccess::getStride(const isl_set *domainSubset) const {
424 isl_map *accessRelation = isl_map_copy(getAccessFunction());
425 isl_set *scatteringDomain = isl_set_copy(const_cast<isl_set*>(domainSubset));
426 isl_map *scattering = isl_map_copy(getStatement()->getScattering());
427
428 scattering = isl_map_reverse(scattering);
429 int difference = isl_map_n_in(scattering) - isl_set_n_dim(scatteringDomain);
430 scattering = isl_map_project_out(scattering, isl_dim_in,
431 isl_set_n_dim(scatteringDomain),
432 difference);
433
434 // Remove all names of the scattering dimensions, as the names may be lost
435 // anyways during the project. This leads to consistent results.
436 scattering = isl_map_set_tuple_name(scattering, isl_dim_in, "");
437 scatteringDomain = isl_set_set_tuple_name(scatteringDomain, "");
438
439 isl_map *nextScatt = getEqualAndLarger(isl_set_get_dim(scatteringDomain));
440 nextScatt = isl_map_lexmin(nextScatt);
441
442 scattering = isl_map_intersect_domain(scattering, scatteringDomain);
443
444 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(scattering));
445 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(accessRelation));
446 nextScatt = isl_map_apply_domain(nextScatt, scattering);
447 nextScatt = isl_map_apply_domain(nextScatt, accessRelation);
448
449 return isl_map_deltas(nextScatt);
450}
451
452bool MemoryAccess::isStrideZero(const isl_set *domainSubset) const {
453 isl_set *stride = getStride(domainSubset);
454 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
455
456 isl_int v;
457 isl_int_init(v);
458 isl_int_set_si(v, 1);
459 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
460 isl_int_set_si(v, 0);
461 isl_constraint_set_constant(c, v);
462 isl_int_clear(v);
463
464 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
465
466 bset = isl_basic_set_add_constraint(bset, c);
467 isl_set *strideZero = isl_set_from_basic_set(bset);
468
469 return isl_set_is_equal(stride, strideZero);
470}
471
472bool MemoryAccess::isStrideOne(const isl_set *domainSubset) const {
473 isl_set *stride = getStride(domainSubset);
474 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
475
476 isl_int v;
477 isl_int_init(v);
478 isl_int_set_si(v, 1);
479 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
480 isl_int_set_si(v, -1);
481 isl_constraint_set_constant(c, v);
482 isl_int_clear(v);
483
484 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
485
486 bset = isl_basic_set_add_constraint(bset, c);
487 isl_set *strideZero = isl_set_from_basic_set(bset);
488
489 return isl_set_is_equal(stride, strideZero);
490}
491
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000492void MemoryAccess::setNewAccessFunction(isl_map *newAccess) {
493 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000494}
Tobias Grosser75805372011-04-29 06:27:02 +0000495
496//===----------------------------------------------------------------------===//
497void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
498 unsigned NumberOfIterators = getNumIterators();
499 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000500 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), 0, NumberOfIterators, ScatDim);
Tobias Grosser75805372011-04-29 06:27:02 +0000501 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
502 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
503 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
504 isl_int v;
505 isl_int_init(v);
506
507 // Loop dimensions.
508 for (unsigned i = 0; i < NumberOfIterators; ++i) {
509 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
510 isl_int_set_si(v, 1);
511 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i + 1, v);
512 isl_int_set_si(v, -1);
513 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
514
515 bmap = isl_basic_map_add_constraint(bmap, c);
516 }
517
518 // Constant dimensions
519 for (unsigned i = 0; i < NumberOfIterators + 1; ++i) {
520 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
521 isl_int_set_si(v, -1);
522 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i, v);
523 isl_int_set_si(v, Scatter[i]);
524 isl_constraint_set_constant(c, v);
525
526 bmap = isl_basic_map_add_constraint(bmap, c);
527 }
528
529 // Fill scattering dimensions.
530 for (unsigned i = 2 * NumberOfIterators + 1; i < ScatDim ; ++i) {
531 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
532 isl_int_set_si(v, 1);
533 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
534 isl_int_set_si(v, 0);
535 isl_constraint_set_constant(c, v);
536
537 bmap = isl_basic_map_add_constraint(bmap, c);
538 }
539
540 isl_int_clear(v);
541 isl_dim_free(dim);
542 Scattering = isl_map_from_basic_map(bmap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000543 isl_dim *Model = isl_set_get_dim(getParent()->getContext());
544 Scattering = isl_map_align_params(Scattering, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000545}
546
547void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
548 const AccFuncSetType *AccFuncs = tempScop.getAccessFunctions(BB);
549
550 for (AccFuncSetType::const_iterator I = AccFuncs->begin(),
551 E = AccFuncs->end(); I != E; ++I) {
552 MemAccs.push_back(new MemoryAccess(I->first, this));
553 InstructionToAccess[I->second] = MemAccs.back();
554 }
555}
556
Tobias Grosserd2795d02011-08-18 07:51:40 +0000557isl_set *ScopStmt::toConditionSet(const Comparison &Comp, isl_dim *dim) const {
558 isl_pw_aff *LHS = SCEVAffinator::getPwAff(this, Comp.getLHS()->OriginalSCEV,
559 0);
560 isl_pw_aff *RHS = SCEVAffinator::getPwAff(this, Comp.getRHS()->OriginalSCEV,
561 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000562
Tobias Grosserd2795d02011-08-18 07:51:40 +0000563 isl_set *set;
Tobias Grosser75805372011-04-29 06:27:02 +0000564
Tobias Grosserd2795d02011-08-18 07:51:40 +0000565 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000566 case ICmpInst::ICMP_EQ:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000567 set = isl_pw_aff_eq_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000568 break;
569 case ICmpInst::ICMP_NE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000570 set = isl_pw_aff_ne_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000571 break;
572 case ICmpInst::ICMP_SLT:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000573 set = isl_pw_aff_lt_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000574 break;
575 case ICmpInst::ICMP_SLE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000576 set = isl_pw_aff_le_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000577 break;
Tobias Grosserd2795d02011-08-18 07:51:40 +0000578 case ICmpInst::ICMP_SGT:
579 set = isl_pw_aff_gt_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000580 break;
581 case ICmpInst::ICMP_SGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000582 set = isl_pw_aff_ge_set(LHS, RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000583 break;
Tobias Grosserd2795d02011-08-18 07:51:40 +0000584 case ICmpInst::ICMP_ULT:
585 case ICmpInst::ICMP_UGT:
586 case ICmpInst::ICMP_ULE:
Tobias Grosser75805372011-04-29 06:27:02 +0000587 case ICmpInst::ICMP_UGE:
Tobias Grosserd2795d02011-08-18 07:51:40 +0000588 llvm_unreachable("Unsigned comparisons not yet supported");
Tobias Grosser75805372011-04-29 06:27:02 +0000589 default:
590 llvm_unreachable("Non integer predicate not supported");
591 }
592
Tobias Grosserd2795d02011-08-18 07:51:40 +0000593 set = isl_set_set_tuple_name(set, isl_dim_get_tuple_name(dim, isl_dim_set));
594
595 return set;
Tobias Grosser75805372011-04-29 06:27:02 +0000596}
597
Tobias Grosserd2795d02011-08-18 07:51:40 +0000598isl_set *ScopStmt::toUpperLoopBound(const SCEVAffFunc &UpperBound, isl_dim *Dim,
Tobias Grosser75805372011-04-29 06:27:02 +0000599 unsigned BoundedDimension) const {
Tobias Grosserd2795d02011-08-18 07:51:40 +0000600 // FIXME: We should choose a consistent scheme of when to name the dimensions.
601 isl_dim *UnnamedDim = isl_dim_copy(Dim);
602 UnnamedDim = isl_dim_set_tuple_name(UnnamedDim, isl_dim_set, 0);
603 isl_local_space *LocalSpace = isl_local_space_from_dim (UnnamedDim);
604 isl_aff *LAff = isl_aff_set_coefficient_si (isl_aff_zero (LocalSpace),
605 isl_dim_set, BoundedDimension, 1);
606 isl_pw_aff *BoundedDim = isl_pw_aff_from_aff(LAff);
607 isl_pw_aff *Bound = SCEVAffinator::getPwAff(this, UpperBound.OriginalSCEV, 0);
608 isl_set *set = isl_pw_aff_le_set(BoundedDim, Bound);
609 set = isl_set_set_tuple_name(set, isl_dim_get_tuple_name(Dim, isl_dim_set));
610 return set;
Tobias Grosser75805372011-04-29 06:27:02 +0000611}
612
613void ScopStmt::buildIterationDomainFromLoops(TempScop &tempScop) {
Tobias Grosser30b8a092011-08-18 07:51:37 +0000614 isl_dim *dim = isl_dim_set_alloc(Parent.getCtx(), 0,
Tobias Grosser75805372011-04-29 06:27:02 +0000615 getNumIterators());
616 dim = isl_dim_set_tuple_name(dim, isl_dim_set, getBaseName());
617
618 Domain = isl_set_universe(isl_dim_copy(dim));
Tobias Grosser30b8a092011-08-18 07:51:37 +0000619 Domain = isl_set_align_params(Domain, isl_set_get_dim(Parent.getContext()));
Tobias Grosser75805372011-04-29 06:27:02 +0000620
621 isl_int v;
622 isl_int_init(v);
623
624 for (int i = 0, e = getNumIterators(); i != e; ++i) {
625 // Lower bound: IV >= 0.
626 isl_basic_set *bset = isl_basic_set_universe(isl_dim_copy(dim));
627 isl_constraint *c = isl_inequality_alloc(isl_dim_copy(dim));
628 isl_int_set_si(v, 1);
629 isl_constraint_set_coefficient(c, isl_dim_set, i, v);
630 bset = isl_basic_set_add_constraint(bset, c);
631 Domain = isl_set_intersect(Domain, isl_set_from_basic_set(bset));
632
633 // Upper bound: IV <= NumberOfIterations.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000634 const Loop *L = getLoopForDimension(i);
Tobias Grosser75805372011-04-29 06:27:02 +0000635 const SCEVAffFunc &UpperBound = tempScop.getLoopBound(L);
636 isl_set *UpperBoundSet = toUpperLoopBound(UpperBound, isl_dim_copy(dim), i);
637 Domain = isl_set_intersect(Domain, UpperBoundSet);
638 }
639
640 isl_int_clear(v);
641}
642
643void ScopStmt::addConditionsToDomain(TempScop &tempScop,
644 const Region &CurRegion) {
645 isl_dim *dim = isl_set_get_dim(Domain);
646 const Region *TopR = tempScop.getMaxRegion().getParent(),
647 *CurR = &CurRegion;
648 const BasicBlock *CurEntry = BB;
649
650 // Build BB condition constrains, by traveling up the region tree.
651 do {
652 assert(CurR && "We exceed the top region?");
653 // Skip when multiple regions share the same entry.
654 if (CurEntry != CurR->getEntry()) {
655 if (const BBCond *Cnd = tempScop.getBBCond(CurEntry))
656 for (BBCond::const_iterator I = Cnd->begin(), E = Cnd->end();
657 I != E; ++I) {
658 isl_set *c = toConditionSet(*I, dim);
659 Domain = isl_set_intersect(Domain, c);
660 }
661 }
662 CurEntry = CurR->getEntry();
663 CurR = CurR->getParent();
664 } while (TopR != CurR);
665
666 isl_dim_free(dim);
667}
668
669void ScopStmt::buildIterationDomain(TempScop &tempScop, const Region &CurRegion)
670{
671 buildIterationDomainFromLoops(tempScop);
672 addConditionsToDomain(tempScop, CurRegion);
673}
674
675ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop,
676 const Region &CurRegion, BasicBlock &bb,
677 SmallVectorImpl<Loop*> &NestLoops,
678 SmallVectorImpl<unsigned> &Scatter)
679 : Parent(parent), BB(&bb), IVS(NestLoops.size()) {
680 // Setup the induction variables.
681 for (unsigned i = 0, e = NestLoops.size(); i < e; ++i) {
682 PHINode *PN = NestLoops[i]->getCanonicalInductionVariable();
683 assert(PN && "Non canonical IV in Scop!");
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000684 IVS[i] = std::make_pair(PN, NestLoops[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000685 }
686
687 raw_string_ostream OS(BaseName);
688 WriteAsOperand(OS, &bb, false);
689 BaseName = OS.str();
690
Tobias Grosser75805372011-04-29 06:27:02 +0000691 makeIslCompatible(BaseName);
692 BaseName = "Stmt_" + BaseName;
693
694 buildIterationDomain(tempScop, CurRegion);
695 buildScattering(Scatter);
696 buildAccesses(tempScop, CurRegion);
697
698 IsReduction = tempScop.is_Reduction(*BB);
699}
700
701ScopStmt::ScopStmt(Scop &parent, SmallVectorImpl<unsigned> &Scatter)
702 : Parent(parent), BB(NULL), IVS(0) {
703
704 BaseName = "FinalRead";
705
706 // Build iteration domain.
707 std::string IterationDomainString = "{[i0] : i0 = 0}";
708 Domain = isl_set_read_from_str(Parent.getCtx(), IterationDomainString.c_str(),
709 -1);
Tobias Grosser75805372011-04-29 06:27:02 +0000710 Domain = isl_set_set_tuple_name(Domain, getBaseName());
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000711 isl_dim *Model = isl_set_get_dim(getParent()->getContext());
712 Domain = isl_set_align_params(Domain, isl_dim_copy(Model));
Tobias Grosser75805372011-04-29 06:27:02 +0000713
714 // Build scattering.
715 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000716 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), 0, 1, ScatDim);
Tobias Grosser75805372011-04-29 06:27:02 +0000717 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
718 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
719 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
720 isl_int v;
721 isl_int_init(v);
722
723 isl_constraint *c = isl_equality_alloc(dim);
724 isl_int_set_si(v, -1);
725 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
726
727 // TODO: This is incorrect. We should not use a very large number to ensure
728 // that this statement is executed last.
729 isl_int_set_si(v, 200000000);
730 isl_constraint_set_constant(c, v);
731
732 bmap = isl_basic_map_add_constraint(bmap, c);
733 isl_int_clear(v);
734 Scattering = isl_map_from_basic_map(bmap);
Tobias Grosserfa7bc2f2011-08-20 00:03:28 +0000735 Scattering = isl_map_align_params(Scattering, Model);
Tobias Grosser75805372011-04-29 06:27:02 +0000736
737 // Build memory accesses, use SetVector to keep the order of memory accesses
738 // and prevent the same memory access inserted more than once.
739 SetVector<const Value*> BaseAddressSet;
740
741 for (Scop::const_iterator SI = Parent.begin(), SE = Parent.end(); SI != SE;
742 ++SI) {
743 ScopStmt *Stmt = *SI;
744
745 for (MemoryAccessVec::const_iterator I = Stmt->memacc_begin(),
746 E = Stmt->memacc_end(); I != E; ++I)
747 BaseAddressSet.insert((*I)->getBaseAddr());
748 }
749
750 for (SetVector<const Value*>::iterator BI = BaseAddressSet.begin(),
751 BE = BaseAddressSet.end(); BI != BE; ++BI)
752 MemAccs.push_back(new MemoryAccess(*BI, this));
753
754 IsReduction = false;
755}
756
757std::string ScopStmt::getDomainStr() const {
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000758 isl_set *domain = getDomain();
759 std::string string = stringFromIslObj(domain);
760 isl_set_free(domain);
761 return string;
Tobias Grosser75805372011-04-29 06:27:02 +0000762}
763
764std::string ScopStmt::getScatteringStr() const {
765 return stringFromIslObj(getScattering());
766}
767
768unsigned ScopStmt::getNumParams() const {
769 return Parent.getNumParams();
770}
771
772unsigned ScopStmt::getNumIterators() const {
773 // The final read has one dimension with one element.
774 if (!BB)
775 return 1;
776
777 return IVS.size();
778}
779
780unsigned ScopStmt::getNumScattering() const {
781 return isl_map_dim(Scattering, isl_dim_out);
782}
783
784const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
785
786const PHINode *ScopStmt::getInductionVariableForDimension(unsigned Dimension)
787 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000788 return IVS[Dimension].first;
789}
790
791const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
792 return IVS[Dimension].second;
Tobias Grosser75805372011-04-29 06:27:02 +0000793}
794
795const SCEVAddRecExpr *ScopStmt::getSCEVForDimension(unsigned Dimension)
796 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000797 PHINode *PN =
798 const_cast<PHINode*>(getInductionVariableForDimension(Dimension));
Tobias Grosser75805372011-04-29 06:27:02 +0000799 return cast<SCEVAddRecExpr>(getParent()->getSE()->getSCEV(PN));
800}
801
802isl_ctx *ScopStmt::getIslContext() {
803 return Parent.getCtx();
804}
805
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000806isl_set *ScopStmt::getDomain() const {
807 return isl_set_copy(Domain);
808}
809
Tobias Grosser75805372011-04-29 06:27:02 +0000810ScopStmt::~ScopStmt() {
811 while (!MemAccs.empty()) {
812 delete MemAccs.back();
813 MemAccs.pop_back();
814 }
815
816 isl_set_free(Domain);
817 isl_map_free(Scattering);
818}
819
820void ScopStmt::print(raw_ostream &OS) const {
821 OS << "\t" << getBaseName() << "\n";
822
823 OS.indent(12) << "Domain :=\n";
824
825 if (Domain) {
826 OS.indent(16) << getDomainStr() << ";\n";
827 } else
828 OS.indent(16) << "n/a\n";
829
830 OS.indent(12) << "Scattering :=\n";
831
832 if (Domain) {
833 OS.indent(16) << getScatteringStr() << ";\n";
834 } else
835 OS.indent(16) << "n/a\n";
836
837 for (MemoryAccessVec::const_iterator I = MemAccs.begin(), E = MemAccs.end();
838 I != E; ++I)
839 (*I)->print(OS);
840}
841
842void ScopStmt::dump() const { print(dbgs()); }
843
844//===----------------------------------------------------------------------===//
845/// Scop class implement
846Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution)
847 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
848 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
849 isl_ctx *ctx = isl_ctx_alloc();
850
851 ParamSetType &Params = tempScop.getParamSet();
852 Parameters.insert(Parameters.begin(), Params.begin(), Params.end());
853
854 isl_dim *dim = isl_dim_set_alloc(ctx, getNumParams(), 0);
855
Tobias Grosser30b8a092011-08-18 07:51:37 +0000856 int i = 0;
857 for (ParamSetType::iterator PI = Params.begin(), PE = Params.end();
858 PI != PE; ++PI) {
859 const SCEV *scev = *PI;
860 isl_id *id = isl_id_alloc(ctx,
861 ("p" + convertInt(i)).c_str(),
862 (void *) scev);
863 dim = isl_dim_set_dim_id(dim, isl_dim_param, i, id);
864 i++;
865 }
866
Tobias Grosser75805372011-04-29 06:27:02 +0000867 // TODO: Insert relations between parameters.
868 // TODO: Insert constraints on parameters.
869 Context = isl_set_universe (dim);
870
871 SmallVector<Loop*, 8> NestLoops;
872 SmallVector<unsigned, 8> Scatter;
873
874 Scatter.assign(MaxLoopDepth + 1, 0);
875
876 // Build the iteration domain, access functions and scattering functions
877 // traversing the region tree.
878 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
879 Stmts.push_back(new ScopStmt(*this, Scatter));
880
Tobias Grosser75805372011-04-29 06:27:02 +0000881 assert(NestLoops.empty() && "NestLoops not empty at top level!");
882}
883
884Scop::~Scop() {
885 isl_set_free(Context);
886
887 // Free the statements;
888 for (iterator I = begin(), E = end(); I != E; ++I)
889 delete *I;
890
891 // Do we need a singleton to manage this?
892 //isl_ctx_free(ctx);
893}
894
895std::string Scop::getContextStr() const {
896 return stringFromIslObj(getContext());
897}
898
899std::string Scop::getNameStr() const {
900 std::string ExitName, EntryName;
901 raw_string_ostream ExitStr(ExitName);
902 raw_string_ostream EntryStr(EntryName);
903
904 WriteAsOperand(EntryStr, R.getEntry(), false);
905 EntryStr.str();
906
907 if (R.getExit()) {
908 WriteAsOperand(ExitStr, R.getExit(), false);
909 ExitStr.str();
910 } else
911 ExitName = "FunctionExit";
912
913 return EntryName + "---" + ExitName;
914}
915
916void Scop::printContext(raw_ostream &OS) const {
917 OS << "Context:\n";
918
919 if (!Context) {
920 OS.indent(4) << "n/a\n\n";
921 return;
922 }
923
924 OS.indent(4) << getContextStr() << "\n";
925}
926
927void Scop::printStatements(raw_ostream &OS) const {
928 OS << "Statements {\n";
929
930 for (const_iterator SI = begin(), SE = end();SI != SE; ++SI)
931 OS.indent(4) << (**SI);
932
933 OS.indent(4) << "}\n";
934}
935
936
937void Scop::print(raw_ostream &OS) const {
938 printContext(OS.indent(4));
939 printStatements(OS.indent(4));
940}
941
942void Scop::dump() const { print(dbgs()); }
943
944isl_ctx *Scop::getCtx() const { return isl_set_get_ctx(Context); }
945
946ScalarEvolution *Scop::getSE() const { return SE; }
947
948bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
949 if (tempScop.getAccessFunctions(BB))
950 return false;
951
952 return true;
953}
954
955void Scop::buildScop(TempScop &tempScop,
956 const Region &CurRegion,
957 SmallVectorImpl<Loop*> &NestLoops,
958 SmallVectorImpl<unsigned> &Scatter,
959 LoopInfo &LI) {
960 Loop *L = castToLoop(CurRegion, LI);
961
962 if (L)
963 NestLoops.push_back(L);
964
965 unsigned loopDepth = NestLoops.size();
966 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
967
968 for (Region::const_element_iterator I = CurRegion.element_begin(),
969 E = CurRegion.element_end(); I != E; ++I)
970 if (I->isSubRegion())
971 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
972 else {
973 BasicBlock *BB = I->getNodeAs<BasicBlock>();
974
975 if (isTrivialBB(BB, tempScop))
976 continue;
977
978 Stmts.push_back(new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops,
979 Scatter));
980
981 // Increasing the Scattering function is OK for the moment, because
982 // we are using a depth first iterator and the program is well structured.
983 ++Scatter[loopDepth];
984 }
985
986 if (!L)
987 return;
988
989 // Exiting a loop region.
990 Scatter[loopDepth] = 0;
991 NestLoops.pop_back();
992 ++Scatter[loopDepth-1];
993}
994
995//===----------------------------------------------------------------------===//
996
997void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
998 AU.addRequired<LoopInfo>();
999 AU.addRequired<RegionInfo>();
1000 AU.addRequired<ScalarEvolution>();
1001 AU.addRequired<TempScopInfo>();
1002 AU.setPreservesAll();
1003}
1004
1005bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1006 LoopInfo &LI = getAnalysis<LoopInfo>();
1007 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1008
1009 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1010
1011 // This region is no Scop.
1012 if (!tempScop) {
1013 scop = 0;
1014 return false;
1015 }
1016
1017 // Statistics.
1018 ++ScopFound;
1019 if (tempScop->getMaxLoopDepth() > 0) ++RichScopFound;
1020
1021 scop = new Scop(*tempScop, LI, SE);
1022
1023 return false;
1024}
1025
1026char ScopInfo::ID = 0;
1027
1028
1029static RegisterPass<ScopInfo>
1030X("polly-scops", "Polly - Create polyhedral description of Scops");
1031
1032Pass *polly::createScopInfoPass() {
1033 return new ScopInfo();
1034}