blob: 41dc3eeaae7ec22e6511039050675bc17ec00ab2 [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 {
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000653 isl_set *domain = getDomain();
654 std::string string = stringFromIslObj(domain);
655 isl_set_free(domain);
656 return string;
Tobias Grosser75805372011-04-29 06:27:02 +0000657}
658
659std::string ScopStmt::getScatteringStr() const {
660 return stringFromIslObj(getScattering());
661}
662
663unsigned ScopStmt::getNumParams() const {
664 return Parent.getNumParams();
665}
666
667unsigned ScopStmt::getNumIterators() const {
668 // The final read has one dimension with one element.
669 if (!BB)
670 return 1;
671
672 return IVS.size();
673}
674
675unsigned ScopStmt::getNumScattering() const {
676 return isl_map_dim(Scattering, isl_dim_out);
677}
678
679const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
680
681const PHINode *ScopStmt::getInductionVariableForDimension(unsigned Dimension)
682 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000683 return IVS[Dimension].first;
684}
685
686const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
687 return IVS[Dimension].second;
Tobias Grosser75805372011-04-29 06:27:02 +0000688}
689
690const SCEVAddRecExpr *ScopStmt::getSCEVForDimension(unsigned Dimension)
691 const {
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000692 PHINode *PN =
693 const_cast<PHINode*>(getInductionVariableForDimension(Dimension));
Tobias Grosser75805372011-04-29 06:27:02 +0000694 return cast<SCEVAddRecExpr>(getParent()->getSE()->getSCEV(PN));
695}
696
697isl_ctx *ScopStmt::getIslContext() {
698 return Parent.getCtx();
699}
700
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +0000701isl_set *ScopStmt::getDomain() const {
702 return isl_set_copy(Domain);
703}
704
Tobias Grosser75805372011-04-29 06:27:02 +0000705ScopStmt::~ScopStmt() {
706 while (!MemAccs.empty()) {
707 delete MemAccs.back();
708 MemAccs.pop_back();
709 }
710
711 isl_set_free(Domain);
712 isl_map_free(Scattering);
713}
714
715void ScopStmt::print(raw_ostream &OS) const {
716 OS << "\t" << getBaseName() << "\n";
717
718 OS.indent(12) << "Domain :=\n";
719
720 if (Domain) {
721 OS.indent(16) << getDomainStr() << ";\n";
722 } else
723 OS.indent(16) << "n/a\n";
724
725 OS.indent(12) << "Scattering :=\n";
726
727 if (Domain) {
728 OS.indent(16) << getScatteringStr() << ";\n";
729 } else
730 OS.indent(16) << "n/a\n";
731
732 for (MemoryAccessVec::const_iterator I = MemAccs.begin(), E = MemAccs.end();
733 I != E; ++I)
734 (*I)->print(OS);
735}
736
737void ScopStmt::dump() const { print(dbgs()); }
738
739//===----------------------------------------------------------------------===//
740/// Scop class implement
741Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution)
742 : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
743 MaxLoopDepth(tempScop.getMaxLoopDepth()) {
744 isl_ctx *ctx = isl_ctx_alloc();
745
746 ParamSetType &Params = tempScop.getParamSet();
747 Parameters.insert(Parameters.begin(), Params.begin(), Params.end());
748
749 isl_dim *dim = isl_dim_set_alloc(ctx, getNumParams(), 0);
750
751 // TODO: Insert relations between parameters.
752 // TODO: Insert constraints on parameters.
753 Context = isl_set_universe (dim);
754
755 SmallVector<Loop*, 8> NestLoops;
756 SmallVector<unsigned, 8> Scatter;
757
758 Scatter.assign(MaxLoopDepth + 1, 0);
759
760 // Build the iteration domain, access functions and scattering functions
761 // traversing the region tree.
762 buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
763 Stmts.push_back(new ScopStmt(*this, Scatter));
764
765 assert(NestLoops.empty() && "NestLoops not empty at top level!");
766}
767
768Scop::~Scop() {
769 isl_set_free(Context);
770
771 // Free the statements;
772 for (iterator I = begin(), E = end(); I != E; ++I)
773 delete *I;
774
775 // Do we need a singleton to manage this?
776 //isl_ctx_free(ctx);
777}
778
779std::string Scop::getContextStr() const {
780 return stringFromIslObj(getContext());
781}
782
783std::string Scop::getNameStr() const {
784 std::string ExitName, EntryName;
785 raw_string_ostream ExitStr(ExitName);
786 raw_string_ostream EntryStr(EntryName);
787
788 WriteAsOperand(EntryStr, R.getEntry(), false);
789 EntryStr.str();
790
791 if (R.getExit()) {
792 WriteAsOperand(ExitStr, R.getExit(), false);
793 ExitStr.str();
794 } else
795 ExitName = "FunctionExit";
796
797 return EntryName + "---" + ExitName;
798}
799
800void Scop::printContext(raw_ostream &OS) const {
801 OS << "Context:\n";
802
803 if (!Context) {
804 OS.indent(4) << "n/a\n\n";
805 return;
806 }
807
808 OS.indent(4) << getContextStr() << "\n";
809}
810
811void Scop::printStatements(raw_ostream &OS) const {
812 OS << "Statements {\n";
813
814 for (const_iterator SI = begin(), SE = end();SI != SE; ++SI)
815 OS.indent(4) << (**SI);
816
817 OS.indent(4) << "}\n";
818}
819
820
821void Scop::print(raw_ostream &OS) const {
822 printContext(OS.indent(4));
823 printStatements(OS.indent(4));
824}
825
826void Scop::dump() const { print(dbgs()); }
827
828isl_ctx *Scop::getCtx() const { return isl_set_get_ctx(Context); }
829
830ScalarEvolution *Scop::getSE() const { return SE; }
831
832bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
833 if (tempScop.getAccessFunctions(BB))
834 return false;
835
836 return true;
837}
838
839void Scop::buildScop(TempScop &tempScop,
840 const Region &CurRegion,
841 SmallVectorImpl<Loop*> &NestLoops,
842 SmallVectorImpl<unsigned> &Scatter,
843 LoopInfo &LI) {
844 Loop *L = castToLoop(CurRegion, LI);
845
846 if (L)
847 NestLoops.push_back(L);
848
849 unsigned loopDepth = NestLoops.size();
850 assert(Scatter.size() > loopDepth && "Scatter not big enough!");
851
852 for (Region::const_element_iterator I = CurRegion.element_begin(),
853 E = CurRegion.element_end(); I != E; ++I)
854 if (I->isSubRegion())
855 buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
856 else {
857 BasicBlock *BB = I->getNodeAs<BasicBlock>();
858
859 if (isTrivialBB(BB, tempScop))
860 continue;
861
862 Stmts.push_back(new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops,
863 Scatter));
864
865 // Increasing the Scattering function is OK for the moment, because
866 // we are using a depth first iterator and the program is well structured.
867 ++Scatter[loopDepth];
868 }
869
870 if (!L)
871 return;
872
873 // Exiting a loop region.
874 Scatter[loopDepth] = 0;
875 NestLoops.pop_back();
876 ++Scatter[loopDepth-1];
877}
878
879//===----------------------------------------------------------------------===//
880
881void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
882 AU.addRequired<LoopInfo>();
883 AU.addRequired<RegionInfo>();
884 AU.addRequired<ScalarEvolution>();
885 AU.addRequired<TempScopInfo>();
886 AU.setPreservesAll();
887}
888
889bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
890 LoopInfo &LI = getAnalysis<LoopInfo>();
891 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
892
893 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
894
895 // This region is no Scop.
896 if (!tempScop) {
897 scop = 0;
898 return false;
899 }
900
901 // Statistics.
902 ++ScopFound;
903 if (tempScop->getMaxLoopDepth() > 0) ++RichScopFound;
904
905 scop = new Scop(*tempScop, LI, SE);
906
907 return false;
908}
909
910char ScopInfo::ID = 0;
911
912
913static RegisterPass<ScopInfo>
914X("polly-scops", "Polly - Create polyhedral description of Scops");
915
916Pass *polly::createScopInfoPass() {
917 return new ScopInfo();
918}