blob: 1cf1930419a0cf8a086b7cc9ad41570348476906 [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"
41#include <sstream>
42#include <string>
43#include <vector>
44
45using namespace llvm;
46using namespace polly;
47
48STATISTIC(ScopFound, "Number of valid Scops");
49STATISTIC(RichScopFound, "Number of Scops containing a loop");
50
51
52//===----------------------------------------------------------------------===//
53static void setCoefficient(const SCEV *Coeff, mpz_t v, bool negative,
54 bool isSigned = true) {
55 if (Coeff) {
56 const SCEVConstant *C = dyn_cast<SCEVConstant>(Coeff);
57 const APInt &CI = C->getValue()->getValue();
58 MPZ_from_APInt(v, negative ? (-CI) : CI, isSigned);
59 } else
60 isl_int_set_si(v, 0);
61}
62
63static isl_map *getValueOf(const SCEVAffFunc &AffFunc,
64 const ScopStmt *Statement, isl_dim *dim) {
65
66 const SmallVectorImpl<const SCEV*> &Params =
67 Statement->getParent()->getParams();
68 unsigned num_in = Statement->getNumIterators(), num_param = Params.size();
69
70 const char *dimname = isl_dim_get_tuple_name(dim, isl_dim_set);
71 dim = isl_dim_alloc(isl_dim_get_ctx(dim), num_param,
72 isl_dim_size(dim, isl_dim_set), 1);
73 dim = isl_dim_set_tuple_name(dim, isl_dim_in, dimname);
74
75 assert((AffFunc.getType() == SCEVAffFunc::Eq
76 || AffFunc.getType() == SCEVAffFunc::ReadMem
77 || AffFunc.getType() == SCEVAffFunc::WriteMem)
78 && "AffFunc is not an equality");
79
80 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
81
82 isl_int v;
83 isl_int_init(v);
84
85 // Set single output dimension.
86 isl_int_set_si(v, -1);
87 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
88
89 // Set the coefficient for induction variables.
90 for (unsigned i = 0, e = num_in; i != e; ++i) {
91 setCoefficient(AffFunc.getCoeff(Statement->getSCEVForDimension(i)), v,
92 false, AffFunc.isSigned());
93 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
94 }
95
96 // Set the coefficient of parameters
97 for (unsigned i = 0, e = num_param; i != e; ++i) {
98 setCoefficient(AffFunc.getCoeff(Params[i]), v, false, AffFunc.isSigned());
99 isl_constraint_set_coefficient(c, isl_dim_param, i, v);
100 }
101
102 // Set the constant.
103 setCoefficient(AffFunc.getTransComp(), v, false, AffFunc.isSigned());
104 isl_constraint_set_constant(c, v);
105 isl_int_clear(v);
106
107 isl_basic_map *BasicMap = isl_basic_map_universe(isl_dim_copy(dim));
108 BasicMap = isl_basic_map_add_constraint(BasicMap, c);
109 return isl_map_from_basic_map(BasicMap);
110}
111//===----------------------------------------------------------------------===//
112
113MemoryAccess::~MemoryAccess() {
114 isl_map_free(getAccessFunction());
115}
116
117static void replace(std::string& str, const std::string& find,
118 const std::string& replace) {
119 size_t pos = 0;
120 while((pos = str.find(find, pos)) != std::string::npos)
121 {
122 str.replace(pos, find.length(), replace);
123 pos += replace.length();
124 }
125}
126
127static void makeIslCompatible(std::string& str) {
128 replace(str, ".", "_");
129}
130
131void MemoryAccess::setBaseName() {
132 raw_string_ostream OS(BaseName);
133 WriteAsOperand(OS, getBaseAddr(), false);
134 BaseName = OS.str();
135
136 // Remove the % in the name. This is not supported by isl.
137 BaseName.erase(0,1);
138 makeIslCompatible(BaseName);
139 BaseName = "MemRef_" + BaseName;
140}
141
142std::string MemoryAccess::getAccessFunctionStr() const {
143 return stringFromIslObj(getAccessFunction());
144}
145
146isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
147 isl_dim *dim = isl_dim_alloc(Statement->getIslContext(),
148 Statement->getNumParams(),
149 Statement->getNumIterators(), 1);
150 setBaseName();
151
152 dim = isl_dim_set_tuple_name(dim, isl_dim_out, getBaseName().c_str());
153 dim = isl_dim_set_tuple_name(dim, isl_dim_in, Statement->getBaseName());
154
155 return isl_basic_map_universe(dim);
156}
157
158MemoryAccess::MemoryAccess(const SCEVAffFunc &AffFunc, ScopStmt *Statement) {
159 BaseAddr = AffFunc.getBaseAddr();
160 Type = AffFunc.isRead() ? Read : Write;
161 statement = Statement;
162
163 setBaseName();
164
165 isl_dim *dim = isl_dim_set_alloc(Statement->getIslContext(),
166 Statement->getNumParams(),
167 Statement->getNumIterators());
168 dim = isl_dim_set_tuple_name(dim, isl_dim_set, Statement->getBaseName());
169
170 AccessRelation = getValueOf(AffFunc, Statement, dim);
171
172 // Devide the access function by the size of the elements in the function.
173 isl_dim *dim2 = isl_dim_alloc(Statement->getIslContext(),
174 Statement->getNumParams(), 1, 1);
175 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim2));
176 isl_constraint *c = isl_equality_alloc(dim2);
177 isl_int v;
178 isl_int_init(v);
179 isl_int_set_si(v, -1);
180 isl_constraint_set_coefficient(c, isl_dim_in, 0, v);
181 isl_int_set_si(v, AffFunc.getElemSizeInBytes());
182 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
183
184 bmap = isl_basic_map_add_constraint(bmap, c);
185 isl_map* dataSizeMap = isl_map_from_basic_map(bmap);
186
187 AccessRelation = isl_map_apply_range(AccessRelation, dataSizeMap);
188
189 AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_out,
190 getBaseName().c_str());
191}
192
193MemoryAccess::MemoryAccess(const Value *BaseAddress, ScopStmt *Statement) {
194 BaseAddr = BaseAddress;
195 Type = Read;
196 statement = Statement;
197
198 isl_basic_map *BasicAccessMap = createBasicAccessMap(Statement);
199 AccessRelation = isl_map_from_basic_map(BasicAccessMap);
200}
201
202void MemoryAccess::print(raw_ostream &OS) const {
203 OS.indent(12) << (isRead() ? "Read" : "Write") << "Access := \n";
204 OS.indent(16) << getAccessFunctionStr() << ";\n";
205}
206
207void MemoryAccess::dump() const {
208 print(errs());
209}
210
211// Create a map in the size of the provided set domain, that maps from the
212// one element of the provided set domain to another element of the provided
213// set domain.
214// The mapping is limited to all points that are equal in all but the last
215// dimension and for which the last dimension of the input is strict smaller
216// than the last dimension of the output.
217//
218// getEqualAndLarger(set[i0, i1, ..., iX]):
219//
220// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
221// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
222//
223static isl_map *getEqualAndLarger(isl_dim *setDomain) {
224 isl_dim *mapDomain = isl_dim_map_from_set(setDomain);
225 isl_basic_map *bmap = isl_basic_map_universe(mapDomain);
226
227 // Set all but the last dimension to be equal for the input and output
228 //
229 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
230 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
231 for (unsigned i = 0; i < isl_basic_map_n_in(bmap) - 1; ++i) {
232 isl_int v;
233 isl_int_init(v);
234 isl_constraint *c = isl_equality_alloc(isl_basic_map_get_dim(bmap));
235
236 isl_int_set_si(v, 1);
237 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
238 isl_int_set_si(v, -1);
239 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
240
241 bmap = isl_basic_map_add_constraint(bmap, c);
242
243 isl_int_clear(v);
244 }
245
246 // Set the last dimension of the input to be strict smaller than the
247 // last dimension of the output.
248 //
249 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
250 //
251 unsigned lastDimension = isl_basic_map_n_in(bmap) - 1;
252 isl_int v;
253 isl_int_init(v);
254 isl_constraint *c = isl_inequality_alloc(isl_basic_map_get_dim(bmap));
255 isl_int_set_si(v, -1);
256 isl_constraint_set_coefficient(c, isl_dim_in, lastDimension, v);
257 isl_int_set_si(v, 1);
258 isl_constraint_set_coefficient(c, isl_dim_out, lastDimension, v);
259 isl_int_set_si(v, -1);
260 isl_constraint_set_constant(c, v);
261 isl_int_clear(v);
262
263 bmap = isl_basic_map_add_constraint(bmap, c);
264
265 return isl_map_from_basic_map(bmap);
266}
267
268isl_set *MemoryAccess::getStride(const isl_set *domainSubset) const {
269 isl_map *accessRelation = isl_map_copy(getAccessFunction());
270 isl_set *scatteringDomain = isl_set_copy(const_cast<isl_set*>(domainSubset));
271 isl_map *scattering = isl_map_copy(getStatement()->getScattering());
272
273 scattering = isl_map_reverse(scattering);
274 int difference = isl_map_n_in(scattering) - isl_set_n_dim(scatteringDomain);
275 scattering = isl_map_project_out(scattering, isl_dim_in,
276 isl_set_n_dim(scatteringDomain),
277 difference);
278
279 // Remove all names of the scattering dimensions, as the names may be lost
280 // anyways during the project. This leads to consistent results.
281 scattering = isl_map_set_tuple_name(scattering, isl_dim_in, "");
282 scatteringDomain = isl_set_set_tuple_name(scatteringDomain, "");
283
284 isl_map *nextScatt = getEqualAndLarger(isl_set_get_dim(scatteringDomain));
285 nextScatt = isl_map_lexmin(nextScatt);
286
287 scattering = isl_map_intersect_domain(scattering, scatteringDomain);
288
289 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(scattering));
290 nextScatt = isl_map_apply_range(nextScatt, isl_map_copy(accessRelation));
291 nextScatt = isl_map_apply_domain(nextScatt, scattering);
292 nextScatt = isl_map_apply_domain(nextScatt, accessRelation);
293
294 return isl_map_deltas(nextScatt);
295}
296
297bool MemoryAccess::isStrideZero(const isl_set *domainSubset) const {
298 isl_set *stride = getStride(domainSubset);
299 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
300
301 isl_int v;
302 isl_int_init(v);
303 isl_int_set_si(v, 1);
304 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
305 isl_int_set_si(v, 0);
306 isl_constraint_set_constant(c, v);
307 isl_int_clear(v);
308
309 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
310
311 bset = isl_basic_set_add_constraint(bset, c);
312 isl_set *strideZero = isl_set_from_basic_set(bset);
313
314 return isl_set_is_equal(stride, strideZero);
315}
316
317bool MemoryAccess::isStrideOne(const isl_set *domainSubset) const {
318 isl_set *stride = getStride(domainSubset);
319 isl_constraint *c = isl_equality_alloc(isl_set_get_dim(stride));
320
321 isl_int v;
322 isl_int_init(v);
323 isl_int_set_si(v, 1);
324 isl_constraint_set_coefficient(c, isl_dim_set, 0, v);
325 isl_int_set_si(v, -1);
326 isl_constraint_set_constant(c, v);
327 isl_int_clear(v);
328
329 isl_basic_set *bset = isl_basic_set_universe(isl_set_get_dim(stride));
330
331 bset = isl_basic_set_add_constraint(bset, c);
332 isl_set *strideZero = isl_set_from_basic_set(bset);
333
334 return isl_set_is_equal(stride, strideZero);
335}
336
337
338//===----------------------------------------------------------------------===//
339void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
340 unsigned NumberOfIterators = getNumIterators();
341 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
342 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), Parent.getNumParams(),
343 NumberOfIterators, ScatDim);
344 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
345 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
346 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
347 isl_int v;
348 isl_int_init(v);
349
350 // Loop dimensions.
351 for (unsigned i = 0; i < NumberOfIterators; ++i) {
352 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
353 isl_int_set_si(v, 1);
354 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i + 1, v);
355 isl_int_set_si(v, -1);
356 isl_constraint_set_coefficient(c, isl_dim_in, i, v);
357
358 bmap = isl_basic_map_add_constraint(bmap, c);
359 }
360
361 // Constant dimensions
362 for (unsigned i = 0; i < NumberOfIterators + 1; ++i) {
363 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
364 isl_int_set_si(v, -1);
365 isl_constraint_set_coefficient(c, isl_dim_out, 2 * i, v);
366 isl_int_set_si(v, Scatter[i]);
367 isl_constraint_set_constant(c, v);
368
369 bmap = isl_basic_map_add_constraint(bmap, c);
370 }
371
372 // Fill scattering dimensions.
373 for (unsigned i = 2 * NumberOfIterators + 1; i < ScatDim ; ++i) {
374 isl_constraint *c = isl_equality_alloc(isl_dim_copy(dim));
375 isl_int_set_si(v, 1);
376 isl_constraint_set_coefficient(c, isl_dim_out, i, v);
377 isl_int_set_si(v, 0);
378 isl_constraint_set_constant(c, v);
379
380 bmap = isl_basic_map_add_constraint(bmap, c);
381 }
382
383 isl_int_clear(v);
384 isl_dim_free(dim);
385 Scattering = isl_map_from_basic_map(bmap);
386}
387
388void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
389 const AccFuncSetType *AccFuncs = tempScop.getAccessFunctions(BB);
390
391 for (AccFuncSetType::const_iterator I = AccFuncs->begin(),
392 E = AccFuncs->end(); I != E; ++I) {
393 MemAccs.push_back(new MemoryAccess(I->first, this));
394 InstructionToAccess[I->second] = MemAccs.back();
395 }
396}
397
398static isl_map *MapValueToLHS(isl_ctx *Context, unsigned ParameterNumber) {
399 std::string MapString;
400 isl_map *Map;
401
402 MapString = "{[i0] -> [i0, o1]}";
403 Map = isl_map_read_from_str(Context, MapString.c_str(), -1);
404 return isl_map_add_dims(Map, isl_dim_param, ParameterNumber);
405}
406
407static isl_map *MapValueToRHS(isl_ctx *Context, unsigned ParameterNumber) {
408 std::string MapString;
409 isl_map *Map;
410
411 MapString = "{[i0] -> [o0, i0]}";
412 Map = isl_map_read_from_str(Context, MapString.c_str(), -1);
413 return isl_map_add_dims(Map, isl_dim_param, ParameterNumber);
414}
415
416static isl_set *getComparison(isl_ctx *Context, const ICmpInst::Predicate Pred,
417 unsigned ParameterNumber) {
418 std::string SetString;
419
420 switch (Pred) {
421 case ICmpInst::ICMP_EQ:
422 SetString = "{[i0, i1] : i0 = i1}";
423 break;
424 case ICmpInst::ICMP_NE:
425 SetString = "{[i0, i1] : i0 + 1 <= i1; [i0, i1] : i0 - 1 >= i1}";
426 break;
427 case ICmpInst::ICMP_SLT:
428 SetString = "{[i0, i1] : i0 + 1 <= i1}";
429 break;
430 case ICmpInst::ICMP_ULT:
431 SetString = "{[i0, i1] : i0 + 1 <= i1}";
432 break;
433 case ICmpInst::ICMP_SGT:
434 SetString = "{[i0, i1] : i0 >= i1 + 1}";
435 break;
436 case ICmpInst::ICMP_UGT:
437 SetString = "{[i0, i1] : i0 >= i1 + 1}";
438 break;
439 case ICmpInst::ICMP_SLE:
440 SetString = "{[i0, i1] : i0 <= i1}";
441 break;
442 case ICmpInst::ICMP_ULE:
443 SetString = "{[i0, i1] : i0 <= i1}";
444 break;
445 case ICmpInst::ICMP_SGE:
446 SetString = "{[i0, i1] : i0 >= i1}";
447 break;
448 case ICmpInst::ICMP_UGE:
449 SetString = "{[i0, i1] : i0 >= i1}";
450 break;
451 default:
452 llvm_unreachable("Non integer predicate not supported");
453 }
454
455 isl_set *Set = isl_set_read_from_str(Context, SetString.c_str(), -1);
456 return isl_set_add_dims(Set, isl_dim_param, ParameterNumber);
457}
458
459static isl_set *compareValues(isl_map *LeftValue, isl_map *RightValue,
460 const ICmpInst::Predicate Predicate) {
461 isl_ctx *Context = isl_map_get_ctx(LeftValue);
462 unsigned NumberOfParameters = isl_map_n_param(LeftValue);
463
464 isl_map *MapToLHS = MapValueToLHS(Context, NumberOfParameters);
465 isl_map *MapToRHS = MapValueToRHS(Context, NumberOfParameters);
466
467 isl_map *LeftValueAtLHS = isl_map_apply_range(LeftValue, MapToLHS);
468 isl_map *RightValueAtRHS = isl_map_apply_range(RightValue, MapToRHS);
469
470 isl_map *BothValues = isl_map_intersect(LeftValueAtLHS, RightValueAtRHS);
471 isl_set *Comparison = getComparison(Context, Predicate, NumberOfParameters);
472
473 isl_map *ComparedValues = isl_map_intersect_range(BothValues, Comparison);
474 return isl_map_domain(ComparedValues);
475}
476
477isl_set *ScopStmt::toConditionSet(const Comparison &Comp, isl_dim *dim) const {
478 isl_map *LHSValue = getValueOf(*Comp.getLHS(), this, dim);
479 isl_map *RHSValue = getValueOf(*Comp.getRHS(), this, dim);
480
481 return compareValues(LHSValue, RHSValue, Comp.getPred());
482}
483
484isl_set *ScopStmt::toUpperLoopBound(const SCEVAffFunc &UpperBound, isl_dim *dim,
485 unsigned BoundedDimension) const {
486 // Set output dimension to bounded dimension.
487 isl_dim *RHSDim = isl_dim_alloc(Parent.getCtx(), getNumParams(),
488 getNumIterators(), 1);
489 RHSDim = isl_dim_set_tuple_name(RHSDim, isl_dim_in, getBaseName());
490 isl_constraint *c = isl_equality_alloc(isl_dim_copy(RHSDim));
491 isl_int v;
492 isl_int_init(v);
493 isl_int_set_si(v, 1);
494 isl_constraint_set_coefficient(c, isl_dim_in, BoundedDimension, v);
495 isl_int_set_si(v, -1);
496 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
497 isl_int_clear(v);
498 isl_basic_map *bmap = isl_basic_map_universe(RHSDim);
499 bmap = isl_basic_map_add_constraint(bmap, c);
500
501 isl_map *LHSValue = isl_map_from_basic_map(bmap);
502
503 isl_map *RHSValue = getValueOf(UpperBound, this, dim);
504
505 return compareValues(LHSValue, RHSValue, ICmpInst::ICMP_SLE);
506}
507
508void ScopStmt::buildIterationDomainFromLoops(TempScop &tempScop) {
509 isl_dim *dim = isl_dim_set_alloc(Parent.getCtx(), getNumParams(),
510 getNumIterators());
511 dim = isl_dim_set_tuple_name(dim, isl_dim_set, getBaseName());
512
513 Domain = isl_set_universe(isl_dim_copy(dim));
514
515 isl_int v;
516 isl_int_init(v);
517
518 for (int i = 0, e = getNumIterators(); i != e; ++i) {
519 // Lower bound: IV >= 0.
520 isl_basic_set *bset = isl_basic_set_universe(isl_dim_copy(dim));
521 isl_constraint *c = isl_inequality_alloc(isl_dim_copy(dim));
522 isl_int_set_si(v, 1);
523 isl_constraint_set_coefficient(c, isl_dim_set, i, v);
524 bset = isl_basic_set_add_constraint(bset, c);
525 Domain = isl_set_intersect(Domain, isl_set_from_basic_set(bset));
526
527 // Upper bound: IV <= NumberOfIterations.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000528 const Loop *L = getLoopForDimension(i);
Tobias Grosser75805372011-04-29 06:27:02 +0000529 const SCEVAffFunc &UpperBound = tempScop.getLoopBound(L);
530 isl_set *UpperBoundSet = toUpperLoopBound(UpperBound, isl_dim_copy(dim), i);
531 Domain = isl_set_intersect(Domain, UpperBoundSet);
532 }
533
534 isl_int_clear(v);
535}
536
537void ScopStmt::addConditionsToDomain(TempScop &tempScop,
538 const Region &CurRegion) {
539 isl_dim *dim = isl_set_get_dim(Domain);
540 const Region *TopR = tempScop.getMaxRegion().getParent(),
541 *CurR = &CurRegion;
542 const BasicBlock *CurEntry = BB;
543
544 // Build BB condition constrains, by traveling up the region tree.
545 do {
546 assert(CurR && "We exceed the top region?");
547 // Skip when multiple regions share the same entry.
548 if (CurEntry != CurR->getEntry()) {
549 if (const BBCond *Cnd = tempScop.getBBCond(CurEntry))
550 for (BBCond::const_iterator I = Cnd->begin(), E = Cnd->end();
551 I != E; ++I) {
552 isl_set *c = toConditionSet(*I, dim);
553 Domain = isl_set_intersect(Domain, c);
554 }
555 }
556 CurEntry = CurR->getEntry();
557 CurR = CurR->getParent();
558 } while (TopR != CurR);
559
560 isl_dim_free(dim);
561}
562
563void ScopStmt::buildIterationDomain(TempScop &tempScop, const Region &CurRegion)
564{
565 buildIterationDomainFromLoops(tempScop);
566 addConditionsToDomain(tempScop, CurRegion);
567}
568
569ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop,
570 const Region &CurRegion, BasicBlock &bb,
571 SmallVectorImpl<Loop*> &NestLoops,
572 SmallVectorImpl<unsigned> &Scatter)
573 : Parent(parent), BB(&bb), IVS(NestLoops.size()) {
574 // Setup the induction variables.
575 for (unsigned i = 0, e = NestLoops.size(); i < e; ++i) {
576 PHINode *PN = NestLoops[i]->getCanonicalInductionVariable();
577 assert(PN && "Non canonical IV in Scop!");
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000578 IVS[i] = std::make_pair(PN, NestLoops[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000579 }
580
581 raw_string_ostream OS(BaseName);
582 WriteAsOperand(OS, &bb, false);
583 BaseName = OS.str();
584
585 // Remove the % in the name. This is not supported by isl.
586 BaseName.erase(0, 1);
587 makeIslCompatible(BaseName);
588 BaseName = "Stmt_" + BaseName;
589
590 buildIterationDomain(tempScop, CurRegion);
591 buildScattering(Scatter);
592 buildAccesses(tempScop, CurRegion);
593
594 IsReduction = tempScop.is_Reduction(*BB);
595}
596
597ScopStmt::ScopStmt(Scop &parent, SmallVectorImpl<unsigned> &Scatter)
598 : Parent(parent), BB(NULL), IVS(0) {
599
600 BaseName = "FinalRead";
601
602 // Build iteration domain.
603 std::string IterationDomainString = "{[i0] : i0 = 0}";
604 Domain = isl_set_read_from_str(Parent.getCtx(), IterationDomainString.c_str(),
605 -1);
606 Domain = isl_set_add_dims(Domain, isl_dim_param, Parent.getNumParams());
607 Domain = isl_set_set_tuple_name(Domain, getBaseName());
608
609 // Build scattering.
610 unsigned ScatDim = Parent.getMaxLoopDepth() * 2 + 1;
611 isl_dim *dim = isl_dim_alloc(Parent.getCtx(), Parent.getNumParams(), 1,
612 ScatDim);
613 dim = isl_dim_set_tuple_name(dim, isl_dim_out, "scattering");
614 dim = isl_dim_set_tuple_name(dim, isl_dim_in, getBaseName());
615 isl_basic_map *bmap = isl_basic_map_universe(isl_dim_copy(dim));
616 isl_int v;
617 isl_int_init(v);
618
619 isl_constraint *c = isl_equality_alloc(dim);
620 isl_int_set_si(v, -1);
621 isl_constraint_set_coefficient(c, isl_dim_out, 0, v);
622
623 // TODO: This is incorrect. We should not use a very large number to ensure
624 // that this statement is executed last.
625 isl_int_set_si(v, 200000000);
626 isl_constraint_set_constant(c, v);
627
628 bmap = isl_basic_map_add_constraint(bmap, c);
629 isl_int_clear(v);
630 Scattering = isl_map_from_basic_map(bmap);
631
632 // Build memory accesses, use SetVector to keep the order of memory accesses
633 // and prevent the same memory access inserted more than once.
634 SetVector<const Value*> BaseAddressSet;
635
636 for (Scop::const_iterator SI = Parent.begin(), SE = Parent.end(); SI != SE;
637 ++SI) {
638 ScopStmt *Stmt = *SI;
639
640 for (MemoryAccessVec::const_iterator I = Stmt->memacc_begin(),
641 E = Stmt->memacc_end(); I != E; ++I)
642 BaseAddressSet.insert((*I)->getBaseAddr());
643 }
644
645 for (SetVector<const Value*>::iterator BI = BaseAddressSet.begin(),
646 BE = BaseAddressSet.end(); BI != BE; ++BI)
647 MemAccs.push_back(new MemoryAccess(*BI, this));
648
649 IsReduction = false;
650}
651
652std::string ScopStmt::getDomainStr() const {
653 return stringFromIslObj(getDomain());
654}
655
656std::string ScopStmt::getScatteringStr() const {
657 return stringFromIslObj(getScattering());
658}
659
660unsigned ScopStmt::getNumParams() const {
661 return Parent.getNumParams();
662}
663
664unsigned ScopStmt::getNumIterators() const {
665 // The final read has one dimension with one element.
666 if (!BB)
667 return 1;
668
669 return IVS.size();
670}
671
672unsigned ScopStmt::getNumScattering() const {
673 return isl_map_dim(Scattering, isl_dim_out);
674}
675
676const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
677
678const PHINode *ScopStmt::getInductionVariableForDimension(unsigned Dimension)
679 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000680 return IVS[Dimension].first;
681}
682
683const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
684 return IVS[Dimension].second;
Tobias Grosser75805372011-04-29 06:27:02 +0000685}
686
687const SCEVAddRecExpr *ScopStmt::getSCEVForDimension(unsigned Dimension)
688 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000689 PHINode *PN =
690 const_cast<PHINode*>(getInductionVariableForDimension(Dimension));
Tobias Grosser75805372011-04-29 06:27:02 +0000691 return cast<SCEVAddRecExpr>(getParent()->getSE()->getSCEV(PN));
692}
693
694isl_ctx *ScopStmt::getIslContext() {
695 return Parent.getCtx();
696}
697
698ScopStmt::~ScopStmt() {
699 while (!MemAccs.empty()) {
700 delete MemAccs.back();
701 MemAccs.pop_back();
702 }
703
704 isl_set_free(Domain);
705 isl_map_free(Scattering);
706}
707
708void ScopStmt::print(raw_ostream &OS) const {
709 OS << "\t" << getBaseName() << "\n";
710
711 OS.indent(12) << "Domain :=\n";
712
713 if (Domain) {
714 OS.indent(16) << getDomainStr() << ";\n";
715 } else
716 OS.indent(16) << "n/a\n";
717
718 OS.indent(12) << "Scattering :=\n";
719
720 if (Domain) {
721 OS.indent(16) << getScatteringStr() << ";\n";
722 } else
723 OS.indent(16) << "n/a\n";
724
725 for (MemoryAccessVec::const_iterator I = MemAccs.begin(), E = MemAccs.end();
726 I != E; ++I)
727 (*I)->print(OS);
728}
729
730void ScopStmt::dump() const { print(dbgs()); }
731
732//===----------------------------------------------------------------------===//
733/// Scop class implement
734Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution)
735 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
736 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
737 isl_ctx *ctx = isl_ctx_alloc();
738
739 ParamSetType &Params = tempScop.getParamSet();
740 Parameters.insert(Parameters.begin(), Params.begin(), Params.end());
741
742 isl_dim *dim = isl_dim_set_alloc(ctx, getNumParams(), 0);
743
744 // TODO: Insert relations between parameters.
745 // TODO: Insert constraints on parameters.
746 Context = isl_set_universe (dim);
747
748 SmallVector<Loop*, 8> NestLoops;
749 SmallVector<unsigned, 8> Scatter;
750
751 Scatter.assign(MaxLoopDepth + 1, 0);
752
753 // Build the iteration domain, access functions and scattering functions
754 // traversing the region tree.
755 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
756 Stmts.push_back(new ScopStmt(*this, Scatter));
757
758 assert(NestLoops.empty() && "NestLoops not empty at top level!");
759}
760
761Scop::~Scop() {
762 isl_set_free(Context);
763
764 // Free the statements;
765 for (iterator I = begin(), E = end(); I != E; ++I)
766 delete *I;
767
768 // Do we need a singleton to manage this?
769 //isl_ctx_free(ctx);
770}
771
772std::string Scop::getContextStr() const {
773 return stringFromIslObj(getContext());
774}
775
776std::string Scop::getNameStr() const {
777 std::string ExitName, EntryName;
778 raw_string_ostream ExitStr(ExitName);
779 raw_string_ostream EntryStr(EntryName);
780
781 WriteAsOperand(EntryStr, R.getEntry(), false);
782 EntryStr.str();
783
784 if (R.getExit()) {
785 WriteAsOperand(ExitStr, R.getExit(), false);
786 ExitStr.str();
787 } else
788 ExitName = "FunctionExit";
789
790 return EntryName + "---" + ExitName;
791}
792
793void Scop::printContext(raw_ostream &OS) const {
794 OS << "Context:\n";
795
796 if (!Context) {
797 OS.indent(4) << "n/a\n\n";
798 return;
799 }
800
801 OS.indent(4) << getContextStr() << "\n";
802}
803
804void Scop::printStatements(raw_ostream &OS) const {
805 OS << "Statements {\n";
806
807 for (const_iterator SI = begin(), SE = end();SI != SE; ++SI)
808 OS.indent(4) << (**SI);
809
810 OS.indent(4) << "}\n";
811}
812
813
814void Scop::print(raw_ostream &OS) const {
815 printContext(OS.indent(4));
816 printStatements(OS.indent(4));
817}
818
819void Scop::dump() const { print(dbgs()); }
820
821isl_ctx *Scop::getCtx() const { return isl_set_get_ctx(Context); }
822
823ScalarEvolution *Scop::getSE() const { return SE; }
824
825bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
826 if (tempScop.getAccessFunctions(BB))
827 return false;
828
829 return true;
830}
831
832void Scop::buildScop(TempScop &tempScop,
833 const Region &CurRegion,
834 SmallVectorImpl<Loop*> &NestLoops,
835 SmallVectorImpl<unsigned> &Scatter,
836 LoopInfo &LI) {
837 Loop *L = castToLoop(CurRegion, LI);
838
839 if (L)
840 NestLoops.push_back(L);
841
842 unsigned loopDepth = NestLoops.size();
843 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
844
845 for (Region::const_element_iterator I = CurRegion.element_begin(),
846 E = CurRegion.element_end(); I != E; ++I)
847 if (I->isSubRegion())
848 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
849 else {
850 BasicBlock *BB = I->getNodeAs<BasicBlock>();
851
852 if (isTrivialBB(BB, tempScop))
853 continue;
854
855 Stmts.push_back(new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops,
856 Scatter));
857
858 // Increasing the Scattering function is OK for the moment, because
859 // we are using a depth first iterator and the program is well structured.
860 ++Scatter[loopDepth];
861 }
862
863 if (!L)
864 return;
865
866 // Exiting a loop region.
867 Scatter[loopDepth] = 0;
868 NestLoops.pop_back();
869 ++Scatter[loopDepth-1];
870}
871
872//===----------------------------------------------------------------------===//
873
874void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
875 AU.addRequired<LoopInfo>();
876 AU.addRequired<RegionInfo>();
877 AU.addRequired<ScalarEvolution>();
878 AU.addRequired<TempScopInfo>();
879 AU.setPreservesAll();
880}
881
882bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
883 LoopInfo &LI = getAnalysis<LoopInfo>();
884 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
885
886 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
887
888 // This region is no Scop.
889 if (!tempScop) {
890 scop = 0;
891 return false;
892 }
893
894 // Statistics.
895 ++ScopFound;
896 if (tempScop->getMaxLoopDepth() > 0) ++RichScopFound;
897
898 scop = new Scop(*tempScop, LI, SE);
899
900 return false;
901}
902
903char ScopInfo::ID = 0;
904
905
906static RegisterPass<ScopInfo>
907X("polly-scops", "Polly - Create polyhedral description of Scops");
908
909Pass *polly::createScopInfoPass() {
910 return new ScopInfo();
911}