10934e70eSTobias Grosser //===- IslAst.cpp - isl code generator interface --------------------------===//
20934e70eSTobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60934e70eSTobias Grosser //
70934e70eSTobias Grosser //===----------------------------------------------------------------------===//
80934e70eSTobias Grosser //
9234a4827STobias Grosser // The isl code generator interface takes a Scop and generates an isl_ast. This
100934e70eSTobias Grosser // ist_ast can either be returned directly or it can be pretty printed to
110934e70eSTobias Grosser // stdout.
120934e70eSTobias Grosser //
130934e70eSTobias Grosser // A typical isl_ast output looks like this:
140934e70eSTobias Grosser //
150934e70eSTobias Grosser // for (c2 = max(0, ceild(n + m, 2); c2 <= min(511, floord(5 * n, 3)); c2++) {
160934e70eSTobias Grosser // bb2(c2);
170934e70eSTobias Grosser // }
180934e70eSTobias Grosser //
19234a4827STobias Grosser // An in-depth discussion of our AST generation approach can be found in:
20234a4827STobias Grosser //
21234a4827STobias Grosser // Polyhedral AST generation is more than scanning polyhedra
22234a4827STobias Grosser // Tobias Grosser, Sven Verdoolaege, Albert Cohen
23a6d48f59SMichael Kruse // ACM Transactions on Programming Languages and Systems (TOPLAS),
24234a4827STobias Grosser // 37(4), July 2015
25234a4827STobias Grosser // http://www.grosser.es/#pub-polyhedral-AST-generation
26234a4827STobias Grosser //
270934e70eSTobias Grosser //===----------------------------------------------------------------------===//
280934e70eSTobias Grosser
290934e70eSTobias Grosser #include "polly/CodeGen/IslAst.h"
305624d3c9STobias Grosser #include "polly/CodeGen/CodeGeneration.h"
31f6557f98SJohannes Doerfert #include "polly/DependenceInfo.h"
3283628182STobias Grosser #include "polly/LinkAllPasses.h"
33637bd631STobias Grosser #include "polly/Options.h"
349248fde5SEugene Zelenko #include "polly/ScopDetection.h"
350934e70eSTobias Grosser #include "polly/ScopInfo.h"
369248fde5SEugene Zelenko #include "polly/ScopPass.h"
3701aea580STobias Grosser #include "polly/Support/GICHelper.h"
389248fde5SEugene Zelenko #include "llvm/ADT/Statistic.h"
399248fde5SEugene Zelenko #include "llvm/IR/Function.h"
400934e70eSTobias Grosser #include "llvm/Support/Debug.h"
419248fde5SEugene Zelenko #include "llvm/Support/raw_ostream.h"
420934e70eSTobias Grosser #include "isl/aff.h"
439248fde5SEugene Zelenko #include "isl/ast.h"
44ba0d0922STobias Grosser #include "isl/ast_build.h"
459248fde5SEugene Zelenko #include "isl/id.h"
469248fde5SEugene Zelenko #include "isl/isl-noexceptions.h"
479248fde5SEugene Zelenko #include "isl/printer.h"
489248fde5SEugene Zelenko #include "isl/schedule.h"
49ba0d0922STobias Grosser #include "isl/set.h"
50ba0d0922STobias Grosser #include "isl/union_map.h"
519248fde5SEugene Zelenko #include "isl/val.h"
529248fde5SEugene Zelenko #include <cassert>
539248fde5SEugene Zelenko #include <cstdlib>
54153a5083STobias Grosser
55c4968e50SJohannes Doerfert #define DEBUG_TYPE "polly-ast"
56c4968e50SJohannes Doerfert
570934e70eSTobias Grosser using namespace llvm;
580934e70eSTobias Grosser using namespace polly;
590934e70eSTobias Grosser
60c4968e50SJohannes Doerfert using IslAstUserPayload = IslAstInfo::IslAstUserPayload;
6195fef944SChandler Carruth
628b5344fdSTobias Grosser static cl::opt<bool>
638b5344fdSTobias Grosser PollyParallel("polly-parallel",
648b5344fdSTobias Grosser cl::desc("Generate thread parallel code (isl codegen only)"),
6536c7d79dSFangrui Song cl::cat(PollyCategory));
668b5344fdSTobias Grosser
67153a5083STobias Grosser static cl::opt<bool> PrintAccesses("polly-ast-print-accesses",
68153a5083STobias Grosser cl::desc("Print memory access functions"),
69153a5083STobias Grosser cl::cat(PollyCategory));
70153a5083STobias Grosser
71bf34f1d2STobias Grosser static cl::opt<bool> PollyParallelForce(
72bf34f1d2STobias Grosser "polly-parallel-force",
73a4377d3eSTobias Grosser cl::desc(
74a4377d3eSTobias Grosser "Force generation of thread parallel code ignoring any cost model"),
75*95a13425SFangrui Song cl::cat(PollyCategory));
76bf34f1d2STobias Grosser
77e602a076STobias Grosser static cl::opt<bool> UseContext("polly-ast-use-context",
78e602a076STobias Grosser cl::desc("Use context"), cl::Hidden,
7936c7d79dSFangrui Song cl::init(true), cl::cat(PollyCategory));
800934e70eSTobias Grosser
81e602a076STobias Grosser static cl::opt<bool> DetectParallel("polly-ast-detect-parallel",
82e602a076STobias Grosser cl::desc("Detect parallelism"), cl::Hidden,
83637bd631STobias Grosser cl::cat(PollyCategory));
84e36abf6dSTobias Grosser
8506ed5292SMichael Kruse STATISTIC(ScopsProcessed, "Number of SCoPs processed");
8606ed5292SMichael Kruse STATISTIC(ScopsBeneficial, "Number of beneficial SCoPs");
8706ed5292SMichael Kruse STATISTIC(BeneficialAffineLoops, "Number of beneficial affine loops");
8806ed5292SMichael Kruse STATISTIC(BeneficialBoxedLoops, "Number of beneficial boxed loops");
8906ed5292SMichael Kruse
9006ed5292SMichael Kruse STATISTIC(NumForLoops, "Number of for-loops");
9106ed5292SMichael Kruse STATISTIC(NumParallel, "Number of parallel for-loops");
9206ed5292SMichael Kruse STATISTIC(NumInnermostParallel, "Number of innermost parallel for-loops");
9306ed5292SMichael Kruse STATISTIC(NumOutermostParallel, "Number of outermost parallel for-loops");
9406ed5292SMichael Kruse STATISTIC(NumReductionParallel, "Number of reduction-parallel for-loops");
9506ed5292SMichael Kruse STATISTIC(NumExecutedInParallel, "Number of for-loops executed in parallel");
9606ed5292SMichael Kruse STATISTIC(NumIfConditions, "Number of if-conditions");
9706ed5292SMichael Kruse
9847197fe3SJohannes Doerfert namespace polly {
999248fde5SEugene Zelenko
100c80d6979STobias Grosser /// Temporary information used when building the ast.
101e36abf6dSTobias Grosser struct AstBuildUserInfo {
102c80d6979STobias Grosser /// Construct and initialize the helper struct for AST creation.
1039248fde5SEugene Zelenko AstBuildUserInfo() = default;
104af9b1e2dSJohannes Doerfert
105c80d6979STobias Grosser /// The dependence information used for the parallelism check.
1069248fde5SEugene Zelenko const Dependences *Deps = nullptr;
107e36abf6dSTobias Grosser
108c80d6979STobias Grosser /// Flag to indicate that we are inside a parallel for node.
1099248fde5SEugene Zelenko bool InParallelFor = false;
110af9b1e2dSJohannes Doerfert
1117860c5feSMichael Kruse /// Flag to indicate that we are inside an SIMD node.
1127860c5feSMichael Kruse bool InSIMD = false;
1137860c5feSMichael Kruse
114c80d6979STobias Grosser /// The last iterator id created for the current SCoP.
1159248fde5SEugene Zelenko isl_id *LastForNodeId = nullptr;
116e36abf6dSTobias Grosser };
117522478d2STobias Grosser } // namespace polly
11847197fe3SJohannes Doerfert
119c80d6979STobias Grosser /// Free an IslAstUserPayload object pointed to by @p Ptr.
freeIslAstUserPayload(void * Ptr)12047197fe3SJohannes Doerfert static void freeIslAstUserPayload(void *Ptr) {
12147197fe3SJohannes Doerfert delete ((IslAstInfo::IslAstUserPayload *)Ptr);
12247197fe3SJohannes Doerfert }
12347197fe3SJohannes Doerfert
124c80d6979STobias Grosser /// Print a string @p str in a single line using @p Printer.
printLine(__isl_take isl_printer * Printer,const std::string & str,__isl_keep isl_pw_aff * PWA=nullptr)1250eefb025SJohannes Doerfert static isl_printer *printLine(__isl_take isl_printer *Printer,
126377a620fSJohannes Doerfert const std::string &str,
127377a620fSJohannes Doerfert __isl_keep isl_pw_aff *PWA = nullptr) {
128e36abf6dSTobias Grosser Printer = isl_printer_start_line(Printer);
1290eefb025SJohannes Doerfert Printer = isl_printer_print_str(Printer, str.c_str());
130377a620fSJohannes Doerfert if (PWA)
131377a620fSJohannes Doerfert Printer = isl_printer_print_pw_aff(Printer, PWA);
1320eefb025SJohannes Doerfert return isl_printer_end_line(Printer);
133e36abf6dSTobias Grosser }
134e36abf6dSTobias Grosser
135c80d6979STobias Grosser /// Return all broken reductions as a string of clauses (OpenMP style).
getBrokenReductionsStr(const isl::ast_node & Node)13682fbc5d4Spatacca static const std::string getBrokenReductionsStr(const isl::ast_node &Node) {
137dc6ad99aSJohannes Doerfert IslAstInfo::MemoryAccessSet *BrokenReductions;
138dc6ad99aSJohannes Doerfert std::string str;
139dc6ad99aSJohannes Doerfert
140dc6ad99aSJohannes Doerfert BrokenReductions = IslAstInfo::getBrokenReductions(Node);
141dc6ad99aSJohannes Doerfert if (!BrokenReductions || BrokenReductions->empty())
142dc6ad99aSJohannes Doerfert return "";
143dc6ad99aSJohannes Doerfert
144dc6ad99aSJohannes Doerfert // Map each type of reduction to a comma separated list of the base addresses.
145dc6ad99aSJohannes Doerfert std::map<MemoryAccess::ReductionType, std::string> Clauses;
146dc6ad99aSJohannes Doerfert for (MemoryAccess *MA : *BrokenReductions)
147dc6ad99aSJohannes Doerfert if (MA->isWrite())
148dc6ad99aSJohannes Doerfert Clauses[MA->getReductionType()] +=
14926fb7d75STobias Grosser ", " + MA->getScopArrayInfo()->getName();
150dc6ad99aSJohannes Doerfert
151dc6ad99aSJohannes Doerfert // Now print the reductions sorted by type. Each type will cause a clause
152dc6ad99aSJohannes Doerfert // like: reduction (+ : sum0, sum1, sum2)
153dc6ad99aSJohannes Doerfert for (const auto &ReductionClause : Clauses) {
154dc6ad99aSJohannes Doerfert str += " reduction (";
155dc6ad99aSJohannes Doerfert str += MemoryAccess::getReductionOperatorStr(ReductionClause.first);
156dc6ad99aSJohannes Doerfert // Remove the first two symbols (", ") to make the output look pretty.
157dc6ad99aSJohannes Doerfert str += " : " + ReductionClause.second.substr(2) + ")";
158dc6ad99aSJohannes Doerfert }
159dc6ad99aSJohannes Doerfert
160dc6ad99aSJohannes Doerfert return str;
161dc6ad99aSJohannes Doerfert }
162dc6ad99aSJohannes Doerfert
163c80d6979STobias Grosser /// Callback executed for each for node in the ast in order to print it.
cbPrintFor(__isl_take isl_printer * Printer,__isl_take isl_ast_print_options * Options,__isl_keep isl_ast_node * Node,void *)1640eefb025SJohannes Doerfert static isl_printer *cbPrintFor(__isl_take isl_printer *Printer,
1650eefb025SJohannes Doerfert __isl_take isl_ast_print_options *Options,
1660eefb025SJohannes Doerfert __isl_keep isl_ast_node *Node, void *) {
16782fbc5d4Spatacca isl::pw_aff DD =
16882fbc5d4Spatacca IslAstInfo::getMinimalDependenceDistance(isl::manage_copy(Node));
16982fbc5d4Spatacca const std::string BrokenReductionsStr =
17082fbc5d4Spatacca getBrokenReductionsStr(isl::manage_copy(Node));
1718b5344fdSTobias Grosser const std::string KnownParallelStr = "#pragma known-parallel";
172377a620fSJohannes Doerfert const std::string DepDisPragmaStr = "#pragma minimal dependence distance: ";
173dc6ad99aSJohannes Doerfert const std::string SimdPragmaStr = "#pragma simd";
174dc6ad99aSJohannes Doerfert const std::string OmpPragmaStr = "#pragma omp parallel for";
1750eefb025SJohannes Doerfert
17682fbc5d4Spatacca if (!DD.is_null())
17782fbc5d4Spatacca Printer = printLine(Printer, DepDisPragmaStr, DD.get());
178377a620fSJohannes Doerfert
1791ab2753dSKevin Zhou if (IslAstInfo::isInnermostParallel(isl::manage_copy(Node)))
180dc6ad99aSJohannes Doerfert Printer = printLine(Printer, SimdPragmaStr + BrokenReductionsStr);
1810eefb025SJohannes Doerfert
18282fbc5d4Spatacca if (IslAstInfo::isExecutedInParallel(isl::manage_copy(Node)))
1838b5344fdSTobias Grosser Printer = printLine(Printer, OmpPragmaStr);
18450e34497SPrateek Pardeshi else if (IslAstInfo::isOutermostParallel(isl::manage_copy(Node)))
1858b5344fdSTobias Grosser Printer = printLine(Printer, KnownParallelStr + BrokenReductionsStr);
1860eefb025SJohannes Doerfert
1870eefb025SJohannes Doerfert return isl_ast_node_for_print(Node, Printer, Options);
188e36abf6dSTobias Grosser }
189e36abf6dSTobias Grosser
190c80d6979STobias Grosser /// Check if the current scheduling dimension is parallel.
191457f73eaSJohannes Doerfert ///
192457f73eaSJohannes Doerfert /// In case the dimension is parallel we also check if any reduction
193457f73eaSJohannes Doerfert /// dependences is broken when we exploit this parallelism. If so,
194457f73eaSJohannes Doerfert /// @p IsReductionParallel will be set to true. The reduction dependences we use
195457f73eaSJohannes Doerfert /// to check are actually the union of the transitive closure of the initial
196a6d48f59SMichael Kruse /// reduction dependences together with their reversal. Even though these
197457f73eaSJohannes Doerfert /// dependences connect all iterations with each other (thus they are cyclic)
198457f73eaSJohannes Doerfert /// we can perform the parallelism check as we are only interested in a zero
199457f73eaSJohannes Doerfert /// (or non-zero) dependence distance on the dimension in question.
astScheduleDimIsParallel(const isl::ast_build & Build,const Dependences * D,IslAstUserPayload * NodeInfo)200b7df372cSKevin Zhou static bool astScheduleDimIsParallel(const isl::ast_build &Build,
2017e6424baSJohannes Doerfert const Dependences *D,
202dc6ad99aSJohannes Doerfert IslAstUserPayload *NodeInfo) {
203457f73eaSJohannes Doerfert if (!D->hasValidDependences())
204457f73eaSJohannes Doerfert return false;
205457f73eaSJohannes Doerfert
206b7df372cSKevin Zhou isl::union_map Schedule = Build.get_schedule();
207b7df372cSKevin Zhou isl::union_map Dep = D->getDependences(
208b7df372cSKevin Zhou Dependences::TYPE_RAW | Dependences::TYPE_WAW | Dependences::TYPE_WAR);
209377a620fSJohannes Doerfert
210b7df372cSKevin Zhou if (!D->isParallel(Schedule.get(), Dep.release())) {
211b7df372cSKevin Zhou isl::union_map DepsAll =
21271e54ccdSHuihui Zhang D->getDependences(Dependences::TYPE_RAW | Dependences::TYPE_WAW |
213b7df372cSKevin Zhou Dependences::TYPE_WAR | Dependences::TYPE_TC_RED);
214b7df372cSKevin Zhou // TODO: We will need to change isParallel to stop the unwrapping
215b7df372cSKevin Zhou isl_pw_aff *MinimalDependenceDistanceIsl = nullptr;
216b7df372cSKevin Zhou D->isParallel(Schedule.get(), DepsAll.release(),
217b7df372cSKevin Zhou &MinimalDependenceDistanceIsl);
2187860c5feSMichael Kruse NodeInfo->MinimalDependenceDistance =
219b7df372cSKevin Zhou isl::manage(MinimalDependenceDistanceIsl);
220457f73eaSJohannes Doerfert return false;
22171e54ccdSHuihui Zhang }
222457f73eaSJohannes Doerfert
223b7df372cSKevin Zhou isl::union_map RedDeps = D->getDependences(Dependences::TYPE_TC_RED);
224b7df372cSKevin Zhou if (!D->isParallel(Schedule.get(), RedDeps.release()))
225dc6ad99aSJohannes Doerfert NodeInfo->IsReductionParallel = true;
226dc6ad99aSJohannes Doerfert
227b7df372cSKevin Zhou if (!NodeInfo->IsReductionParallel)
228dc6ad99aSJohannes Doerfert return true;
229dc6ad99aSJohannes Doerfert
230dc6ad99aSJohannes Doerfert for (const auto &MaRedPair : D->getReductionDependences()) {
231dc6ad99aSJohannes Doerfert if (!MaRedPair.second)
232dc6ad99aSJohannes Doerfert continue;
233b7df372cSKevin Zhou isl::union_map MaRedDeps = isl::manage_copy(MaRedPair.second);
234b7df372cSKevin Zhou if (!D->isParallel(Schedule.get(), MaRedDeps.release()))
235dc6ad99aSJohannes Doerfert NodeInfo->BrokenReductions.insert(MaRedPair.first);
236dc6ad99aSJohannes Doerfert }
237457f73eaSJohannes Doerfert return true;
238457f73eaSJohannes Doerfert }
239457f73eaSJohannes Doerfert
240e36abf6dSTobias Grosser // This method is executed before the construction of a for node. It creates
241e36abf6dSTobias Grosser // an isl_id that is used to annotate the subsequently generated ast for nodes.
242e36abf6dSTobias Grosser //
243e36abf6dSTobias Grosser // In this function we also run the following analyses:
244e36abf6dSTobias Grosser //
245e36abf6dSTobias Grosser // - Detection of openmp parallel loops
246e36abf6dSTobias Grosser //
astBuildBeforeFor(__isl_keep isl_ast_build * Build,void * User)247e602a076STobias Grosser static __isl_give isl_id *astBuildBeforeFor(__isl_keep isl_ast_build *Build,
248e602a076STobias Grosser void *User) {
249c4968e50SJohannes Doerfert AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
25099f6630cSJohannes Doerfert IslAstUserPayload *Payload = new IslAstUserPayload();
25199f6630cSJohannes Doerfert isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
252c4968e50SJohannes Doerfert Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
253af9b1e2dSJohannes Doerfert BuildInfo->LastForNodeId = Id;
254e36abf6dSTobias Grosser
255b7df372cSKevin Zhou Payload->IsParallel = astScheduleDimIsParallel(isl::manage_copy(Build),
256b7df372cSKevin Zhou BuildInfo->Deps, Payload);
257e36abf6dSTobias Grosser
2587860c5feSMichael Kruse // Test for parallelism only if we are not already inside a parallel loop
2597860c5feSMichael Kruse if (!BuildInfo->InParallelFor && !BuildInfo->InSIMD)
2607860c5feSMichael Kruse BuildInfo->InParallelFor = Payload->IsOutermostParallel =
2617860c5feSMichael Kruse Payload->IsParallel;
2627860c5feSMichael Kruse
263e36abf6dSTobias Grosser return Id;
264e36abf6dSTobias Grosser }
265e36abf6dSTobias Grosser
266e36abf6dSTobias Grosser // This method is executed after the construction of a for node.
267e36abf6dSTobias Grosser //
268e36abf6dSTobias Grosser // It performs the following actions:
269e36abf6dSTobias Grosser //
270e36abf6dSTobias Grosser // - Reset the 'InParallelFor' flag, as soon as we leave a for node,
271e36abf6dSTobias Grosser // that is marked as openmp parallel.
272e36abf6dSTobias Grosser //
273e36abf6dSTobias Grosser static __isl_give isl_ast_node *
astBuildAfterFor(__isl_take isl_ast_node * Node,__isl_keep isl_ast_build * Build,void * User)274c14582f2STobias Grosser astBuildAfterFor(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build,
275c14582f2STobias Grosser void *User) {
276e252c855SSebastian Pop isl_id *Id = isl_ast_node_get_annotation(Node);
27799f6630cSJohannes Doerfert assert(Id && "Post order visit assumes annotated for nodes");
27899f6630cSJohannes Doerfert IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
27999f6630cSJohannes Doerfert assert(Payload && "Post order visit assumes annotated for nodes");
28099f6630cSJohannes Doerfert
281c4968e50SJohannes Doerfert AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
2822a629efcSpatacca assert(Payload->Build.is_null() && "Build environment already set");
2832a629efcSpatacca Payload->Build = isl::manage_copy(Build);
28499f6630cSJohannes Doerfert Payload->IsInnermost = (Id == BuildInfo->LastForNodeId);
285eb283143SSebastian Pop
286dc6ad99aSJohannes Doerfert Payload->IsInnermostParallel =
2877860c5feSMichael Kruse Payload->IsInnermost && (BuildInfo->InSIMD || Payload->IsParallel);
2888e95dc65SJohannes Doerfert if (Payload->IsOutermostParallel)
28999f6630cSJohannes Doerfert BuildInfo->InParallelFor = false;
290e36abf6dSTobias Grosser
29104c4ce32SSebastian Pop isl_id_free(Id);
292e36abf6dSTobias Grosser return Node;
293e36abf6dSTobias Grosser }
294e36abf6dSTobias Grosser
astBuildBeforeMark(__isl_keep isl_id * MarkId,__isl_keep isl_ast_build * Build,void * User)29511001e15SRoman Gareev static isl_stat astBuildBeforeMark(__isl_keep isl_id *MarkId,
29611001e15SRoman Gareev __isl_keep isl_ast_build *Build,
29711001e15SRoman Gareev void *User) {
29811001e15SRoman Gareev if (!MarkId)
29911001e15SRoman Gareev return isl_stat_error;
30011001e15SRoman Gareev
30111001e15SRoman Gareev AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
3029248fde5SEugene Zelenko if (strcmp(isl_id_get_name(MarkId), "SIMD") == 0)
3037860c5feSMichael Kruse BuildInfo->InSIMD = true;
30411001e15SRoman Gareev
30511001e15SRoman Gareev return isl_stat_ok;
30611001e15SRoman Gareev }
30711001e15SRoman Gareev
30811001e15SRoman Gareev static __isl_give isl_ast_node *
astBuildAfterMark(__isl_take isl_ast_node * Node,__isl_keep isl_ast_build * Build,void * User)30911001e15SRoman Gareev astBuildAfterMark(__isl_take isl_ast_node *Node,
31011001e15SRoman Gareev __isl_keep isl_ast_build *Build, void *User) {
31111001e15SRoman Gareev assert(isl_ast_node_get_type(Node) == isl_ast_node_mark);
31211001e15SRoman Gareev AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
31311001e15SRoman Gareev auto *Id = isl_ast_node_mark_get_id(Node);
3149248fde5SEugene Zelenko if (strcmp(isl_id_get_name(Id), "SIMD") == 0)
3157860c5feSMichael Kruse BuildInfo->InSIMD = false;
31611001e15SRoman Gareev isl_id_free(Id);
31711001e15SRoman Gareev return Node;
31811001e15SRoman Gareev }
31911001e15SRoman Gareev
AtEachDomain(__isl_take isl_ast_node * Node,__isl_keep isl_ast_build * Build,void * User)320e602a076STobias Grosser static __isl_give isl_ast_node *AtEachDomain(__isl_take isl_ast_node *Node,
321c4968e50SJohannes Doerfert __isl_keep isl_ast_build *Build,
322c14582f2STobias Grosser void *User) {
32347b906c8SJohannes Doerfert assert(!isl_ast_node_get_annotation(Node) && "Node already annotated");
32499f6630cSJohannes Doerfert
32599f6630cSJohannes Doerfert IslAstUserPayload *Payload = new IslAstUserPayload();
32699f6630cSJohannes Doerfert isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
327c4968e50SJohannes Doerfert Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
3280934e70eSTobias Grosser
3292a629efcSpatacca Payload->Build = isl::manage_copy(Build);
33004c4ce32SSebastian Pop
33104c4ce32SSebastian Pop return isl_ast_node_set_annotation(Node, Id);
3320934e70eSTobias Grosser }
3330934e70eSTobias Grosser
334338b42c3SJohannes Doerfert // Build alias check condition given a pair of minimal/maximal access.
buildCondition(Scop & S,isl::ast_build Build,const Scop::MinMaxAccessTy * It0,const Scop::MinMaxAccessTy * It1)335701d943dSTobias Grosser static isl::ast_expr buildCondition(Scop &S, isl::ast_build Build,
3366b1e4613STobias Grosser const Scop::MinMaxAccessTy *It0,
337210b09aaSJohannes Doerfert const Scop::MinMaxAccessTy *It1) {
3386b1e4613STobias Grosser
33900fd43b3SPhilip Pfaffe isl::pw_multi_aff AFirst = It0->first;
34000fd43b3SPhilip Pfaffe isl::pw_multi_aff ASecond = It0->second;
34100fd43b3SPhilip Pfaffe isl::pw_multi_aff BFirst = It1->first;
34200fd43b3SPhilip Pfaffe isl::pw_multi_aff BSecond = It1->second;
3436b1e4613STobias Grosser
3446b1e4613STobias Grosser isl::id Left = AFirst.get_tuple_id(isl::dim::set);
3456b1e4613STobias Grosser isl::id Right = BFirst.get_tuple_id(isl::dim::set);
346ee8ad1c0STobias Grosser
347701d943dSTobias Grosser isl::ast_expr True =
3480813bd16SRiccardo Mori isl::ast_expr::from_val(isl::val::int_from_ui(Build.ctx(), 1));
349701d943dSTobias Grosser isl::ast_expr False =
3500813bd16SRiccardo Mori isl::ast_expr::from_val(isl::val::int_from_ui(Build.ctx(), 0));
351701d943dSTobias Grosser
352ee8ad1c0STobias Grosser const ScopArrayInfo *BaseLeft =
353ee8ad1c0STobias Grosser ScopArrayInfo::getFromId(Left)->getBasePtrOriginSAI();
354ee8ad1c0STobias Grosser const ScopArrayInfo *BaseRight =
355ee8ad1c0STobias Grosser ScopArrayInfo::getFromId(Right)->getBasePtrOriginSAI();
3566b1e4613STobias Grosser if (BaseLeft && BaseLeft == BaseRight)
357701d943dSTobias Grosser return True;
358701d943dSTobias Grosser
359701d943dSTobias Grosser isl::set Params = S.getContext();
360ee8ad1c0STobias Grosser
3616b1e4613STobias Grosser isl::ast_expr NonAliasGroup, MinExpr, MaxExpr;
362701d943dSTobias Grosser
363701d943dSTobias Grosser // In the following, we first check if any accesses will be empty under
364701d943dSTobias Grosser // the execution context of the scop and do not code generate them if this
365701d943dSTobias Grosser // is the case as isl will fail to derive valid AST expressions for such
366701d943dSTobias Grosser // accesses.
367701d943dSTobias Grosser
368701d943dSTobias Grosser if (!AFirst.intersect_params(Params).domain().is_empty() &&
369701d943dSTobias Grosser !BSecond.intersect_params(Params).domain().is_empty()) {
3706b1e4613STobias Grosser MinExpr = Build.access_from(AFirst).address_of();
3716b1e4613STobias Grosser MaxExpr = Build.access_from(BSecond).address_of();
3726b1e4613STobias Grosser NonAliasGroup = MaxExpr.le(MinExpr);
373701d943dSTobias Grosser }
374701d943dSTobias Grosser
375701d943dSTobias Grosser if (!BFirst.intersect_params(Params).domain().is_empty() &&
376701d943dSTobias Grosser !ASecond.intersect_params(Params).domain().is_empty()) {
3776b1e4613STobias Grosser MinExpr = Build.access_from(BFirst).address_of();
3786b1e4613STobias Grosser MaxExpr = Build.access_from(ASecond).address_of();
379701d943dSTobias Grosser
380701d943dSTobias Grosser isl::ast_expr Result = MaxExpr.le(MinExpr);
381701d943dSTobias Grosser if (!NonAliasGroup.is_null())
3826b1e4613STobias Grosser NonAliasGroup = isl::manage(
383701d943dSTobias Grosser isl_ast_expr_or(NonAliasGroup.release(), Result.release()));
384701d943dSTobias Grosser else
385701d943dSTobias Grosser NonAliasGroup = Result;
386701d943dSTobias Grosser }
387701d943dSTobias Grosser
388701d943dSTobias Grosser if (NonAliasGroup.is_null())
389701d943dSTobias Grosser NonAliasGroup = True;
390338b42c3SJohannes Doerfert
391338b42c3SJohannes Doerfert return NonAliasGroup;
392338b42c3SJohannes Doerfert }
393338b42c3SJohannes Doerfert
buildRunCondition(Scop & S,const isl::ast_build & Build)3944170d6cdSpatacca isl::ast_expr IslAst::buildRunCondition(Scop &S, const isl::ast_build &Build) {
3954170d6cdSpatacca isl::ast_expr RunCondition;
39664ca00c3STobias Grosser
397d764fcbdSTobias Grosser // The conditions that need to be checked at run-time for this scop are
39843788c57SJohannes Doerfert // available as an isl_set in the runtime check context from which we can
39943788c57SJohannes Doerfert // directly derive a run-time condition.
4004170d6cdSpatacca auto PosCond = Build.expr_from(S.getAssumedContext());
4012b852e2eSPhilip Pfaffe if (S.hasTrivialInvalidContext()) {
4024170d6cdSpatacca RunCondition = std::move(PosCond);
403066dbf3fSJohannes Doerfert } else {
4040813bd16SRiccardo Mori auto ZeroV = isl::val::zero(Build.ctx());
4054170d6cdSpatacca auto NegCond = Build.expr_from(S.getInvalidContext());
4064170d6cdSpatacca auto NotNegCond =
4074170d6cdSpatacca isl::ast_expr::from_val(std::move(ZeroV)).eq(std::move(NegCond));
4084170d6cdSpatacca RunCondition =
4094170d6cdSpatacca isl::manage(isl_ast_expr_and(PosCond.release(), NotNegCond.release()));
410066dbf3fSJohannes Doerfert }
411b164c795SJohannes Doerfert
412b164c795SJohannes Doerfert // Create the alias checks from the minimal/maximal accesses in each alias
413338b42c3SJohannes Doerfert // group which consists of read only and non read only (read write) accesses.
414338b42c3SJohannes Doerfert // This operation is by construction quadratic in the read-write pointers and
4156c3d19baSSiddharth Bhat // linear in the read only pointers in each alias group.
4162b852e2eSPhilip Pfaffe for (const Scop::MinMaxVectorPairTy &MinMaxAccessPair : S.getAliasGroups()) {
417210b09aaSJohannes Doerfert auto &MinMaxReadWrite = MinMaxAccessPair.first;
418210b09aaSJohannes Doerfert auto &MinMaxReadOnly = MinMaxAccessPair.second;
419210b09aaSJohannes Doerfert auto RWAccEnd = MinMaxReadWrite.end();
420338b42c3SJohannes Doerfert
421210b09aaSJohannes Doerfert for (auto RWAccIt0 = MinMaxReadWrite.begin(); RWAccIt0 != RWAccEnd;
422338b42c3SJohannes Doerfert ++RWAccIt0) {
423338b42c3SJohannes Doerfert for (auto RWAccIt1 = RWAccIt0 + 1; RWAccIt1 != RWAccEnd; ++RWAccIt1)
4244170d6cdSpatacca RunCondition = isl::manage(isl_ast_expr_and(
4254170d6cdSpatacca RunCondition.release(),
4264170d6cdSpatacca buildCondition(S, Build, RWAccIt0, RWAccIt1).release()));
427210b09aaSJohannes Doerfert for (const Scop::MinMaxAccessTy &ROAccIt : MinMaxReadOnly)
4284170d6cdSpatacca RunCondition = isl::manage(isl_ast_expr_and(
4294170d6cdSpatacca RunCondition.release(),
4304170d6cdSpatacca buildCondition(S, Build, RWAccIt0, &ROAccIt).release()));
431b164c795SJohannes Doerfert }
432b164c795SJohannes Doerfert }
43364ca00c3STobias Grosser
43464ca00c3STobias Grosser return RunCondition;
435e86109f5STobias Grosser }
436e86109f5STobias Grosser
437c80d6979STobias Grosser /// Simple cost analysis for a given SCoP.
4387ceb0402SJohannes Doerfert ///
4397ceb0402SJohannes Doerfert /// TODO: Improve this analysis and extract it to make it usable in other
4407ceb0402SJohannes Doerfert /// places too.
4417ceb0402SJohannes Doerfert /// In order to improve the cost model we could either keep track of
4427ceb0402SJohannes Doerfert /// performed optimizations (e.g., tiling) or compute properties on the
4437ceb0402SJohannes Doerfert /// original as well as optimized SCoP (e.g., #stride-one-accesses).
benefitsFromPolly(Scop & Scop,bool PerformParallelTest)4442b852e2eSPhilip Pfaffe static bool benefitsFromPolly(Scop &Scop, bool PerformParallelTest) {
445575aca8dSTobias Grosser if (PollyProcessUnprofitable)
4467ceb0402SJohannes Doerfert return true;
4477ceb0402SJohannes Doerfert
4487ceb0402SJohannes Doerfert // Check if nothing interesting happened.
4492b852e2eSPhilip Pfaffe if (!PerformParallelTest && !Scop.isOptimized() &&
4502b852e2eSPhilip Pfaffe Scop.getAliasGroups().empty())
4517ceb0402SJohannes Doerfert return false;
4527ceb0402SJohannes Doerfert
4537ceb0402SJohannes Doerfert // The default assumption is that Polly improves the code.
4547ceb0402SJohannes Doerfert return true;
4557ceb0402SJohannes Doerfert }
4567ceb0402SJohannes Doerfert
45706ed5292SMichael Kruse /// Collect statistics for the syntax tree rooted at @p Ast.
walkAstForStatistics(const isl::ast_node & Ast)4584170d6cdSpatacca static void walkAstForStatistics(const isl::ast_node &Ast) {
4594170d6cdSpatacca assert(!Ast.is_null());
46006ed5292SMichael Kruse isl_ast_node_foreach_descendant_top_down(
4614170d6cdSpatacca Ast.get(),
46206ed5292SMichael Kruse [](__isl_keep isl_ast_node *Node, void *User) -> isl_bool {
46306ed5292SMichael Kruse switch (isl_ast_node_get_type(Node)) {
46406ed5292SMichael Kruse case isl_ast_node_for:
46506ed5292SMichael Kruse NumForLoops++;
46682fbc5d4Spatacca if (IslAstInfo::isParallel(isl::manage_copy(Node)))
46706ed5292SMichael Kruse NumParallel++;
4681ab2753dSKevin Zhou if (IslAstInfo::isInnermostParallel(isl::manage_copy(Node)))
46906ed5292SMichael Kruse NumInnermostParallel++;
47050e34497SPrateek Pardeshi if (IslAstInfo::isOutermostParallel(isl::manage_copy(Node)))
47106ed5292SMichael Kruse NumOutermostParallel++;
47282fbc5d4Spatacca if (IslAstInfo::isReductionParallel(isl::manage_copy(Node)))
47306ed5292SMichael Kruse NumReductionParallel++;
47482fbc5d4Spatacca if (IslAstInfo::isExecutedInParallel(isl::manage_copy(Node)))
47506ed5292SMichael Kruse NumExecutedInParallel++;
47606ed5292SMichael Kruse break;
47706ed5292SMichael Kruse
47806ed5292SMichael Kruse case isl_ast_node_if:
47906ed5292SMichael Kruse NumIfConditions++;
48006ed5292SMichael Kruse break;
48106ed5292SMichael Kruse
48206ed5292SMichael Kruse default:
48306ed5292SMichael Kruse break;
48406ed5292SMichael Kruse }
48506ed5292SMichael Kruse
48606ed5292SMichael Kruse // Continue traversing subtrees.
48706ed5292SMichael Kruse return isl_bool_true;
48806ed5292SMichael Kruse },
48906ed5292SMichael Kruse nullptr);
49006ed5292SMichael Kruse }
49106ed5292SMichael Kruse
IslAst(Scop & Scop)4929248fde5SEugene Zelenko IslAst::IslAst(Scop &Scop) : S(Scop), Ctx(Scop.getSharedIslCtx()) {}
4939248fde5SEugene Zelenko
IslAst(IslAst && O)4949248fde5SEugene Zelenko IslAst::IslAst(IslAst &&O)
4954170d6cdSpatacca : S(O.S), Ctx(O.Ctx), RunCondition(std::move(O.RunCondition)),
4964170d6cdSpatacca Root(std::move(O.Root)) {}
4977ceb0402SJohannes Doerfert
init(const Dependences & D)498471a5e33SMichael Kruse void IslAst::init(const Dependences &D) {
4997ceb0402SJohannes Doerfert bool PerformParallelTest = PollyParallel || DetectParallel ||
5007ceb0402SJohannes Doerfert PollyVectorizerChoice != VECTORIZER_NONE;
50100fd43b3SPhilip Pfaffe auto ScheduleTree = S.getScheduleTree();
502bc3fbe49SRoman Gareev
5037ceb0402SJohannes Doerfert // Skip AST and code generation if there was no benefit achieved.
504471a5e33SMichael Kruse if (!benefitsFromPolly(S, PerformParallelTest))
5057ceb0402SJohannes Doerfert return;
5067ceb0402SJohannes Doerfert
50706ed5292SMichael Kruse auto ScopStats = S.getStatistics();
50806ed5292SMichael Kruse ScopsBeneficial++;
50906ed5292SMichael Kruse BeneficialAffineLoops += ScopStats.NumAffineLoops;
51006ed5292SMichael Kruse BeneficialBoxedLoops += ScopStats.NumBoxedLoops;
51106ed5292SMichael Kruse
51200fd43b3SPhilip Pfaffe auto Ctx = S.getIslCtx();
51300fd43b3SPhilip Pfaffe isl_options_set_ast_build_atomic_upper_bound(Ctx.get(), true);
51400fd43b3SPhilip Pfaffe isl_options_set_ast_build_detect_min_max(Ctx.get(), true);
5153717aa5dSTobias Grosser isl_ast_build *Build;
516c4968e50SJohannes Doerfert AstBuildUserInfo BuildInfo;
5170934e70eSTobias Grosser
5180934e70eSTobias Grosser if (UseContext)
5198ea1fc19STobias Grosser Build = isl_ast_build_from_context(S.getContext().release());
5200934e70eSTobias Grosser else
521b65ccc43STobias Grosser Build = isl_ast_build_from_context(
522b65ccc43STobias Grosser isl_set_universe(S.getParamSpace().release()));
5230934e70eSTobias Grosser
524c4968e50SJohannes Doerfert Build = isl_ast_build_set_at_each_domain(Build, AtEachDomain, nullptr);
5250934e70eSTobias Grosser
5267ceb0402SJohannes Doerfert if (PerformParallelTest) {
527e36abf6dSTobias Grosser BuildInfo.Deps = &D;
5289248fde5SEugene Zelenko BuildInfo.InParallelFor = false;
5297860c5feSMichael Kruse BuildInfo.InSIMD = false;
530e36abf6dSTobias Grosser
531c4968e50SJohannes Doerfert Build = isl_ast_build_set_before_each_for(Build, &astBuildBeforeFor,
532e36abf6dSTobias Grosser &BuildInfo);
533c4968e50SJohannes Doerfert Build =
534c4968e50SJohannes Doerfert isl_ast_build_set_after_each_for(Build, &astBuildAfterFor, &BuildInfo);
53511001e15SRoman Gareev
53611001e15SRoman Gareev Build = isl_ast_build_set_before_each_mark(Build, &astBuildBeforeMark,
53711001e15SRoman Gareev &BuildInfo);
53811001e15SRoman Gareev
53911001e15SRoman Gareev Build = isl_ast_build_set_after_each_mark(Build, &astBuildAfterMark,
54011001e15SRoman Gareev &BuildInfo);
541e36abf6dSTobias Grosser }
542e36abf6dSTobias Grosser
5434170d6cdSpatacca RunCondition = buildRunCondition(S, isl::manage_copy(Build));
5443717aa5dSTobias Grosser
5454170d6cdSpatacca Root = isl::manage(
5464170d6cdSpatacca isl_ast_build_node_from_schedule(Build, S.getScheduleTree().release()));
54706ed5292SMichael Kruse walkAstForStatistics(Root);
5483717aa5dSTobias Grosser
5493717aa5dSTobias Grosser isl_ast_build_free(Build);
5500934e70eSTobias Grosser }
5510934e70eSTobias Grosser
create(Scop & Scop,const Dependences & D)5522b852e2eSPhilip Pfaffe IslAst IslAst::create(Scop &Scop, const Dependences &D) {
5532b852e2eSPhilip Pfaffe IslAst Ast{Scop};
5542b852e2eSPhilip Pfaffe Ast.init(D);
555471a5e33SMichael Kruse return Ast;
556471a5e33SMichael Kruse }
557471a5e33SMichael Kruse
getAst()5584170d6cdSpatacca isl::ast_node IslAst::getAst() { return Root; }
getRunCondition()5594170d6cdSpatacca isl::ast_expr IslAst::getRunCondition() { return RunCondition; }
5600934e70eSTobias Grosser
getAst()5614170d6cdSpatacca isl::ast_node IslAstInfo::getAst() { return Ast.getAst(); }
getRunCondition()5624170d6cdSpatacca isl::ast_expr IslAstInfo::getRunCondition() { return Ast.getRunCondition(); }
5630934e70eSTobias Grosser
getNodePayload(const isl::ast_node & Node)564ea37ee5bSMichael Kruse IslAstUserPayload *IslAstInfo::getNodePayload(const isl::ast_node &Node) {
565ea37ee5bSMichael Kruse isl::id Id = Node.get_annotation();
5667c7978a1Spatacca if (Id.is_null())
5676e81905eSJohannes Doerfert return nullptr;
568ea37ee5bSMichael Kruse IslAstUserPayload *Payload = (IslAstUserPayload *)Id.get_user();
5696e81905eSJohannes Doerfert return Payload;
5706e81905eSJohannes Doerfert }
5716e81905eSJohannes Doerfert
isInnermost(const isl::ast_node & Node)572812ce7f9Spatacca bool IslAstInfo::isInnermost(const isl::ast_node &Node) {
573812ce7f9Spatacca IslAstUserPayload *Payload = getNodePayload(Node);
5740eefb025SJohannes Doerfert return Payload && Payload->IsInnermost;
5750eefb025SJohannes Doerfert }
5760eefb025SJohannes Doerfert
isParallel(const isl::ast_node & Node)57782fbc5d4Spatacca bool IslAstInfo::isParallel(const isl::ast_node &Node) {
57882fbc5d4Spatacca return IslAstInfo::isInnermostParallel(Node) ||
57982fbc5d4Spatacca IslAstInfo::isOutermostParallel(Node);
5806e81905eSJohannes Doerfert }
5816e81905eSJohannes Doerfert
isInnermostParallel(const isl::ast_node & Node)5821ab2753dSKevin Zhou bool IslAstInfo::isInnermostParallel(const isl::ast_node &Node) {
5831ab2753dSKevin Zhou IslAstUserPayload *Payload = getNodePayload(Node);
584ed67f8baSJohannes Doerfert return Payload && Payload->IsInnermostParallel;
5856e81905eSJohannes Doerfert }
5866e81905eSJohannes Doerfert
isOutermostParallel(const isl::ast_node & Node)58750e34497SPrateek Pardeshi bool IslAstInfo::isOutermostParallel(const isl::ast_node &Node) {
58850e34497SPrateek Pardeshi IslAstUserPayload *Payload = getNodePayload(Node);
589ed67f8baSJohannes Doerfert return Payload && Payload->IsOutermostParallel;
5906e81905eSJohannes Doerfert }
5916e81905eSJohannes Doerfert
isReductionParallel(const isl::ast_node & Node)59282fbc5d4Spatacca bool IslAstInfo::isReductionParallel(const isl::ast_node &Node) {
59382fbc5d4Spatacca IslAstUserPayload *Payload = getNodePayload(Node);
5946e81905eSJohannes Doerfert return Payload && Payload->IsReductionParallel;
5956e81905eSJohannes Doerfert }
5966e81905eSJohannes Doerfert
isExecutedInParallel(const isl::ast_node & Node)59782fbc5d4Spatacca bool IslAstInfo::isExecutedInParallel(const isl::ast_node &Node) {
598bf34f1d2STobias Grosser if (!PollyParallel)
599bf34f1d2STobias Grosser return false;
600bf34f1d2STobias Grosser
601bf34f1d2STobias Grosser // Do not parallelize innermost loops.
602bf34f1d2STobias Grosser //
603bf34f1d2STobias Grosser // Parallelizing innermost loops is often not profitable, especially if
604bf34f1d2STobias Grosser // they have a low number of iterations.
605bf34f1d2STobias Grosser //
606bf34f1d2STobias Grosser // TODO: Decide this based on the number of loop iterations that will be
607bf34f1d2STobias Grosser // executed. This can possibly require run-time checks, which again
608bf34f1d2STobias Grosser // raises the question of both run-time check overhead and code size
609bf34f1d2STobias Grosser // costs.
61082fbc5d4Spatacca if (!PollyParallelForce && isInnermost(Node))
611bf34f1d2STobias Grosser return false;
612bf34f1d2STobias Grosser
61382fbc5d4Spatacca return isOutermostParallel(Node) && !isReductionParallel(Node);
6148b5344fdSTobias Grosser }
6158b5344fdSTobias Grosser
getSchedule(const isl::ast_node & Node)61682fbc5d4Spatacca isl::union_map IslAstInfo::getSchedule(const isl::ast_node &Node) {
61782fbc5d4Spatacca IslAstUserPayload *Payload = getNodePayload(Node);
6182a629efcSpatacca return Payload ? Payload->Build.get_schedule() : isl::union_map();
619c4968e50SJohannes Doerfert }
620c4968e50SJohannes Doerfert
62182fbc5d4Spatacca isl::pw_aff
getMinimalDependenceDistance(const isl::ast_node & Node)62282fbc5d4Spatacca IslAstInfo::getMinimalDependenceDistance(const isl::ast_node &Node) {
62382fbc5d4Spatacca IslAstUserPayload *Payload = getNodePayload(Node);
6249b41d095Spatacca return Payload ? Payload->MinimalDependenceDistance : isl::pw_aff();
625377a620fSJohannes Doerfert }
626377a620fSJohannes Doerfert
627dc6ad99aSJohannes Doerfert IslAstInfo::MemoryAccessSet *
getBrokenReductions(const isl::ast_node & Node)62882fbc5d4Spatacca IslAstInfo::getBrokenReductions(const isl::ast_node &Node) {
62982fbc5d4Spatacca IslAstUserPayload *Payload = getNodePayload(Node);
630dc6ad99aSJohannes Doerfert return Payload ? &Payload->BrokenReductions : nullptr;
631dc6ad99aSJohannes Doerfert }
632dc6ad99aSJohannes Doerfert
getBuild(const isl::ast_node & Node)6332a629efcSpatacca isl::ast_build IslAstInfo::getBuild(const isl::ast_node &Node) {
6342a629efcSpatacca IslAstUserPayload *Payload = getNodePayload(Node);
6352a629efcSpatacca return Payload ? Payload->Build : isl::ast_build();
636a63b2579SJohannes Doerfert }
637a63b2579SJohannes Doerfert
runIslAst(Scop & Scop,function_ref<const Dependences & (Dependences::AnalysisLevel)> GetDeps)63808bab4b0SMichael Kruse static std::unique_ptr<IslAstInfo> runIslAst(
63908bab4b0SMichael Kruse Scop &Scop,
64008bab4b0SMichael Kruse function_ref<const Dependences &(Dependences::AnalysisLevel)> GetDeps) {
64108bab4b0SMichael Kruse // Skip SCoPs in case they're already handled by PPCGCodeGeneration.
64208bab4b0SMichael Kruse if (Scop.isToBeSkipped())
64308bab4b0SMichael Kruse return {};
64408bab4b0SMichael Kruse
64508bab4b0SMichael Kruse ScopsProcessed++;
64608bab4b0SMichael Kruse
64708bab4b0SMichael Kruse const Dependences &D = GetDeps(Dependences::AL_Statement);
64808bab4b0SMichael Kruse
64908bab4b0SMichael Kruse if (D.getSharedIslCtx() != Scop.getSharedIslCtx()) {
65008bab4b0SMichael Kruse LLVM_DEBUG(
65108bab4b0SMichael Kruse dbgs() << "Got dependence analysis for different SCoP/isl_ctx\n");
65208bab4b0SMichael Kruse return {};
65308bab4b0SMichael Kruse }
65408bab4b0SMichael Kruse
65508bab4b0SMichael Kruse std::unique_ptr<IslAstInfo> Ast = std::make_unique<IslAstInfo>(Scop, D);
65608bab4b0SMichael Kruse
65708bab4b0SMichael Kruse LLVM_DEBUG({
65808bab4b0SMichael Kruse if (Ast)
65908bab4b0SMichael Kruse Ast->print(dbgs());
66008bab4b0SMichael Kruse });
66108bab4b0SMichael Kruse
66208bab4b0SMichael Kruse return Ast;
66308bab4b0SMichael Kruse }
66408bab4b0SMichael Kruse
run(Scop & S,ScopAnalysisManager & SAM,ScopStandardAnalysisResults & SAR)6652b852e2eSPhilip Pfaffe IslAstInfo IslAstAnalysis::run(Scop &S, ScopAnalysisManager &SAM,
6662b852e2eSPhilip Pfaffe ScopStandardAnalysisResults &SAR) {
66708bab4b0SMichael Kruse auto GetDeps = [&](Dependences::AnalysisLevel Lvl) -> const Dependences & {
66808bab4b0SMichael Kruse return SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(Lvl);
66908bab4b0SMichael Kruse };
67008bab4b0SMichael Kruse
671a8cbddc9SKazu Hirata return std::move(*runIslAst(S, GetDeps));
6722b852e2eSPhilip Pfaffe }
6732b852e2eSPhilip Pfaffe
cbPrintUser(__isl_take isl_printer * P,__isl_take isl_ast_print_options * O,__isl_keep isl_ast_node * Node,void * User)674153a5083STobias Grosser static __isl_give isl_printer *cbPrintUser(__isl_take isl_printer *P,
675153a5083STobias Grosser __isl_take isl_ast_print_options *O,
676153a5083STobias Grosser __isl_keep isl_ast_node *Node,
677153a5083STobias Grosser void *User) {
678d3fdbda6SRiccardo Mori isl::ast_node_user AstNode = isl::manage_copy(Node).as<isl::ast_node_user>();
679d3fdbda6SRiccardo Mori isl::ast_expr NodeExpr = AstNode.expr();
680153a5083STobias Grosser isl::ast_expr CallExpr = NodeExpr.get_op_arg(0);
681153a5083STobias Grosser isl::id CallExprId = CallExpr.get_id();
682153a5083STobias Grosser ScopStmt *AccessStmt = (ScopStmt *)CallExprId.get_user();
683153a5083STobias Grosser
684153a5083STobias Grosser P = isl_printer_start_line(P);
685153a5083STobias Grosser P = isl_printer_print_str(P, AccessStmt->getBaseName());
686153a5083STobias Grosser P = isl_printer_print_str(P, "(");
687153a5083STobias Grosser P = isl_printer_end_line(P);
688153a5083STobias Grosser P = isl_printer_indent(P, 2);
689153a5083STobias Grosser
690153a5083STobias Grosser for (MemoryAccess *MemAcc : *AccessStmt) {
691153a5083STobias Grosser P = isl_printer_start_line(P);
692153a5083STobias Grosser
693153a5083STobias Grosser if (MemAcc->isRead())
694153a5083STobias Grosser P = isl_printer_print_str(P, "/* read */ &");
695153a5083STobias Grosser else
696153a5083STobias Grosser P = isl_printer_print_str(P, "/* write */ ");
697153a5083STobias Grosser
6982a629efcSpatacca isl::ast_build Build = IslAstInfo::getBuild(isl::manage_copy(Node));
699153a5083STobias Grosser if (MemAcc->isAffine()) {
700153a5083STobias Grosser isl_pw_multi_aff *PwmaPtr =
7013b196131STobias Grosser MemAcc->applyScheduleToAccessRelation(Build.get_schedule()).release();
702153a5083STobias Grosser isl::pw_multi_aff Pwma = isl::manage(PwmaPtr);
703153a5083STobias Grosser isl::ast_expr AccessExpr = Build.access_from(Pwma);
704153a5083STobias Grosser P = isl_printer_print_ast_expr(P, AccessExpr.get());
705153a5083STobias Grosser } else {
706153a5083STobias Grosser P = isl_printer_print_str(
707153a5083STobias Grosser P, MemAcc->getLatestScopArrayInfo()->getName().c_str());
708153a5083STobias Grosser P = isl_printer_print_str(P, "[*]");
709153a5083STobias Grosser }
710153a5083STobias Grosser P = isl_printer_end_line(P);
711153a5083STobias Grosser }
712153a5083STobias Grosser
713153a5083STobias Grosser P = isl_printer_indent(P, -2);
714153a5083STobias Grosser P = isl_printer_start_line(P);
715153a5083STobias Grosser P = isl_printer_print_str(P, ");");
716153a5083STobias Grosser P = isl_printer_end_line(P);
717153a5083STobias Grosser
718153a5083STobias Grosser isl_ast_print_options_free(O);
719153a5083STobias Grosser return P;
720153a5083STobias Grosser }
721153a5083STobias Grosser
print(raw_ostream & OS)7222b852e2eSPhilip Pfaffe void IslAstInfo::print(raw_ostream &OS) {
723f6583176SJohannes Doerfert isl_ast_print_options *Options;
7244170d6cdSpatacca isl::ast_node RootNode = Ast.getAst();
7253f52e354SJohannes Doerfert Function &F = S.getFunction();
7267ceb0402SJohannes Doerfert
7273f52e354SJohannes Doerfert OS << ":: isl ast :: " << F.getName() << " :: " << S.getNameStr() << "\n";
7287ceb0402SJohannes Doerfert
7294170d6cdSpatacca if (RootNode.is_null()) {
7307ceb0402SJohannes Doerfert OS << ":: isl ast generation and code generation was skipped!\n\n";
7313593739cSTobias Grosser OS << ":: This is either because no useful optimizations could be applied "
7323593739cSTobias Grosser "(use -polly-process-unprofitable to enforce code generation) or "
7333593739cSTobias Grosser "because earlier passes such as dependence analysis timed out (use "
7343593739cSTobias Grosser "-polly-dependences-computeout=0 to set dependence analysis timeout "
7353593739cSTobias Grosser "to infinity)\n\n";
7367ceb0402SJohannes Doerfert return;
7377ceb0402SJohannes Doerfert }
7387ceb0402SJohannes Doerfert
7394170d6cdSpatacca isl::ast_expr RunCondition = Ast.getRunCondition();
740f6583176SJohannes Doerfert char *RtCStr, *AstStr;
741f6583176SJohannes Doerfert
74200fd43b3SPhilip Pfaffe Options = isl_ast_print_options_alloc(S.getIslCtx().get());
743153a5083STobias Grosser
744153a5083STobias Grosser if (PrintAccesses)
745153a5083STobias Grosser Options =
746153a5083STobias Grosser isl_ast_print_options_set_print_user(Options, cbPrintUser, nullptr);
7470eefb025SJohannes Doerfert Options = isl_ast_print_options_set_print_for(Options, cbPrintFor, nullptr);
748f6583176SJohannes Doerfert
74900fd43b3SPhilip Pfaffe isl_printer *P = isl_printer_to_str(S.getIslCtx().get());
750932ec013STobias Grosser P = isl_printer_set_output_format(P, ISL_FORMAT_C);
7514170d6cdSpatacca P = isl_printer_print_ast_expr(P, RunCondition.get());
752f6583176SJohannes Doerfert RtCStr = isl_printer_get_str(P);
753f6583176SJohannes Doerfert P = isl_printer_flush(P);
754f6583176SJohannes Doerfert P = isl_printer_indent(P, 4);
7554170d6cdSpatacca P = isl_ast_node_print(RootNode.get(), P, Options);
756f6583176SJohannes Doerfert AstStr = isl_printer_get_str(P);
757f6583176SJohannes Doerfert
758349506a9SNicola Zaghen LLVM_DEBUG({
75901aea580STobias Grosser dbgs() << S.getContextStr() << "\n";
760cfe117deSpatacca dbgs() << stringFromIslObj(S.getScheduleTree(), "null");
76101aea580STobias Grosser });
762f6583176SJohannes Doerfert OS << "\nif (" << RtCStr << ")\n\n";
763f6583176SJohannes Doerfert OS << AstStr << "\n";
764f6583176SJohannes Doerfert OS << "else\n";
765f6583176SJohannes Doerfert OS << " { /* original code */ }\n\n";
766f6583176SJohannes Doerfert
767785ee20cSTobias Grosser free(RtCStr);
768785ee20cSTobias Grosser free(AstStr);
769785ee20cSTobias Grosser
770f6583176SJohannes Doerfert isl_printer_free(P);
771f6583176SJohannes Doerfert }
772f6583176SJohannes Doerfert
7732b852e2eSPhilip Pfaffe AnalysisKey IslAstAnalysis::Key;
run(Scop & S,ScopAnalysisManager & SAM,ScopStandardAnalysisResults & SAR,SPMUpdater & U)7742b852e2eSPhilip Pfaffe PreservedAnalyses IslAstPrinterPass::run(Scop &S, ScopAnalysisManager &SAM,
7752b852e2eSPhilip Pfaffe ScopStandardAnalysisResults &SAR,
7762b852e2eSPhilip Pfaffe SPMUpdater &U) {
7772b852e2eSPhilip Pfaffe auto &Ast = SAM.getResult<IslAstAnalysis>(S, SAR);
7789248fde5SEugene Zelenko Ast.print(OS);
7792b852e2eSPhilip Pfaffe return PreservedAnalyses::all();
7802b852e2eSPhilip Pfaffe }
7812b852e2eSPhilip Pfaffe
releaseMemory()7822b852e2eSPhilip Pfaffe void IslAstInfoWrapperPass::releaseMemory() { Ast.reset(); }
7832b852e2eSPhilip Pfaffe
runOnScop(Scop & Scop)7842b852e2eSPhilip Pfaffe bool IslAstInfoWrapperPass::runOnScop(Scop &Scop) {
78508bab4b0SMichael Kruse auto GetDeps = [this](Dependences::AnalysisLevel Lvl) -> const Dependences & {
78608bab4b0SMichael Kruse return getAnalysis<DependenceInfo>().getDependences(Lvl);
78708bab4b0SMichael Kruse };
78802ca346eSSingapuram Sanjay Srivallabh
78908bab4b0SMichael Kruse Ast = runIslAst(Scop, GetDeps);
79006ed5292SMichael Kruse
7912b852e2eSPhilip Pfaffe return false;
7922b852e2eSPhilip Pfaffe }
7939248fde5SEugene Zelenko
getAnalysisUsage(AnalysisUsage & AU) const7942b852e2eSPhilip Pfaffe void IslAstInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
7950934e70eSTobias Grosser // Get the Common analysis usage of ScopPasses.
7960934e70eSTobias Grosser ScopPass::getAnalysisUsage(AU);
7970e370cf1SMichael Kruse AU.addRequiredTransitive<ScopInfoRegionPass>();
798f6557f98SJohannes Doerfert AU.addRequired<DependenceInfo>();
799a4f447c2SMichael Kruse
800a4f447c2SMichael Kruse AU.addPreserved<DependenceInfo>();
8010934e70eSTobias Grosser }
8027242ad92STobias Grosser
printScop(raw_ostream & OS,Scop & S) const8032b852e2eSPhilip Pfaffe void IslAstInfoWrapperPass::printScop(raw_ostream &OS, Scop &S) const {
80408bab4b0SMichael Kruse OS << "Printing analysis 'Polly - Generate an AST of the SCoP (isl)'"
80508bab4b0SMichael Kruse << S.getName() << "' in function '" << S.getFunction().getName() << "':\n";
8062b852e2eSPhilip Pfaffe if (Ast)
8072b852e2eSPhilip Pfaffe Ast->print(OS);
8082b852e2eSPhilip Pfaffe }
8090934e70eSTobias Grosser
8102b852e2eSPhilip Pfaffe char IslAstInfoWrapperPass::ID = 0;
8117242ad92STobias Grosser
createIslAstInfoWrapperPassPass()8122b852e2eSPhilip Pfaffe Pass *polly::createIslAstInfoWrapperPassPass() {
8132b852e2eSPhilip Pfaffe return new IslAstInfoWrapperPass();
8142b852e2eSPhilip Pfaffe }
8152b852e2eSPhilip Pfaffe
8162b852e2eSPhilip Pfaffe INITIALIZE_PASS_BEGIN(IslAstInfoWrapperPass, "polly-ast",
8174d96c8d7STobias Grosser "Polly - Generate an AST of the SCoP (isl)", false,
8184d96c8d7STobias Grosser false);
81999191c78SJohannes Doerfert INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
820f6557f98SJohannes Doerfert INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
8212b852e2eSPhilip Pfaffe INITIALIZE_PASS_END(IslAstInfoWrapperPass, "polly-ast",
8224d96c8d7STobias Grosser "Polly - Generate an AST from the SCoP (isl)", false, false)
8235c028081SMichael Kruse
8245c028081SMichael Kruse //===----------------------------------------------------------------------===//
8255c028081SMichael Kruse
8265c028081SMichael Kruse namespace {
8275c028081SMichael Kruse /// Print result from IslAstInfoWrapperPass.
828bd93df93SMichael Kruse class IslAstInfoPrinterLegacyPass final : public ScopPass {
8295c028081SMichael Kruse public:
8305c028081SMichael Kruse static char ID;
8315c028081SMichael Kruse
IslAstInfoPrinterLegacyPass()8325c028081SMichael Kruse IslAstInfoPrinterLegacyPass() : IslAstInfoPrinterLegacyPass(outs()) {}
IslAstInfoPrinterLegacyPass(llvm::raw_ostream & OS)8335c028081SMichael Kruse explicit IslAstInfoPrinterLegacyPass(llvm::raw_ostream &OS)
8345c028081SMichael Kruse : ScopPass(ID), OS(OS) {}
8355c028081SMichael Kruse
runOnScop(Scop & S)8365c028081SMichael Kruse bool runOnScop(Scop &S) override {
8375c028081SMichael Kruse IslAstInfoWrapperPass &P = getAnalysis<IslAstInfoWrapperPass>();
8385c028081SMichael Kruse
8395c028081SMichael Kruse OS << "Printing analysis '" << P.getPassName() << "' for region: '"
8405c028081SMichael Kruse << S.getRegion().getNameStr() << "' in function '"
8415c028081SMichael Kruse << S.getFunction().getName() << "':\n";
8425c028081SMichael Kruse P.printScop(OS, S);
8435c028081SMichael Kruse
8445c028081SMichael Kruse return false;
8455c028081SMichael Kruse }
8465c028081SMichael Kruse
getAnalysisUsage(AnalysisUsage & AU) const8475c028081SMichael Kruse void getAnalysisUsage(AnalysisUsage &AU) const override {
8485c028081SMichael Kruse ScopPass::getAnalysisUsage(AU);
8495c028081SMichael Kruse AU.addRequired<IslAstInfoWrapperPass>();
8505c028081SMichael Kruse AU.setPreservesAll();
8515c028081SMichael Kruse }
8525c028081SMichael Kruse
8535c028081SMichael Kruse private:
8545c028081SMichael Kruse llvm::raw_ostream &OS;
8555c028081SMichael Kruse };
8565c028081SMichael Kruse
8575c028081SMichael Kruse char IslAstInfoPrinterLegacyPass::ID = 0;
8585c028081SMichael Kruse } // namespace
8595c028081SMichael Kruse
createIslAstInfoPrinterLegacyPass(raw_ostream & OS)8605c028081SMichael Kruse Pass *polly::createIslAstInfoPrinterLegacyPass(raw_ostream &OS) {
8615c028081SMichael Kruse return new IslAstInfoPrinterLegacyPass(OS);
8625c028081SMichael Kruse }
8635c028081SMichael Kruse
8645c028081SMichael Kruse INITIALIZE_PASS_BEGIN(IslAstInfoPrinterLegacyPass, "polly-print-ast",
8655c028081SMichael Kruse "Polly - Print the AST from a SCoP (isl)", false, false);
8665c028081SMichael Kruse INITIALIZE_PASS_DEPENDENCY(IslAstInfoWrapperPass);
8675c028081SMichael Kruse INITIALIZE_PASS_END(IslAstInfoPrinterLegacyPass, "polly-print-ast",
8685c028081SMichael Kruse "Polly - Print the AST from a SCoP (isl)", false, false)
869