1 //===- IslAst.cpp - isl code generator interface --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The isl code generator interface takes a Scop and generates an isl_ast. This
10 // ist_ast can either be returned directly or it can be pretty printed to
11 // stdout.
12 //
13 // A typical isl_ast output looks like this:
14 //
15 // for (c2 = max(0, ceild(n + m, 2); c2 <= min(511, floord(5 * n, 3)); c2++) {
16 //   bb2(c2);
17 // }
18 //
19 // An in-depth discussion of our AST generation approach can be found in:
20 //
21 // Polyhedral AST generation is more than scanning polyhedra
22 // Tobias Grosser, Sven Verdoolaege, Albert Cohen
23 // ACM Transactions on Programming Languages and Systems (TOPLAS),
24 // 37(4), July 2015
25 // http://www.grosser.es/#pub-polyhedral-AST-generation
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "polly/CodeGen/IslAst.h"
30 #include "polly/CodeGen/CodeGeneration.h"
31 #include "polly/DependenceInfo.h"
32 #include "polly/LinkAllPasses.h"
33 #include "polly/Options.h"
34 #include "polly/ScopDetection.h"
35 #include "polly/ScopInfo.h"
36 #include "polly/ScopPass.h"
37 #include "polly/Support/GICHelper.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "isl/aff.h"
43 #include "isl/ast.h"
44 #include "isl/ast_build.h"
45 #include "isl/id.h"
46 #include "isl/isl-noexceptions.h"
47 #include "isl/printer.h"
48 #include "isl/schedule.h"
49 #include "isl/set.h"
50 #include "isl/union_map.h"
51 #include "isl/val.h"
52 #include <cassert>
53 #include <cstdlib>
54 
55 #define DEBUG_TYPE "polly-ast"
56 
57 using namespace llvm;
58 using namespace polly;
59 
60 using IslAstUserPayload = IslAstInfo::IslAstUserPayload;
61 
62 static cl::opt<bool>
63     PollyParallel("polly-parallel",
64                   cl::desc("Generate thread parallel code (isl codegen only)"),
65                   cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
66 
67 static cl::opt<bool> PrintAccesses("polly-ast-print-accesses",
68                                    cl::desc("Print memory access functions"),
69                                    cl::init(false), cl::ZeroOrMore,
70                                    cl::cat(PollyCategory));
71 
72 static cl::opt<bool> PollyParallelForce(
73     "polly-parallel-force",
74     cl::desc(
75         "Force generation of thread parallel code ignoring any cost model"),
76     cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
77 
78 static cl::opt<bool> UseContext("polly-ast-use-context",
79                                 cl::desc("Use context"), cl::Hidden,
80                                 cl::init(true), cl::ZeroOrMore,
81                                 cl::cat(PollyCategory));
82 
83 static cl::opt<bool> DetectParallel("polly-ast-detect-parallel",
84                                     cl::desc("Detect parallelism"), cl::Hidden,
85                                     cl::init(false), cl::ZeroOrMore,
86                                     cl::cat(PollyCategory));
87 
88 STATISTIC(ScopsProcessed, "Number of SCoPs processed");
89 STATISTIC(ScopsBeneficial, "Number of beneficial SCoPs");
90 STATISTIC(BeneficialAffineLoops, "Number of beneficial affine loops");
91 STATISTIC(BeneficialBoxedLoops, "Number of beneficial boxed loops");
92 
93 STATISTIC(NumForLoops, "Number of for-loops");
94 STATISTIC(NumParallel, "Number of parallel for-loops");
95 STATISTIC(NumInnermostParallel, "Number of innermost parallel for-loops");
96 STATISTIC(NumOutermostParallel, "Number of outermost parallel for-loops");
97 STATISTIC(NumReductionParallel, "Number of reduction-parallel for-loops");
98 STATISTIC(NumExecutedInParallel, "Number of for-loops executed in parallel");
99 STATISTIC(NumIfConditions, "Number of if-conditions");
100 
101 namespace polly {
102 
103 /// Temporary information used when building the ast.
104 struct AstBuildUserInfo {
105   /// Construct and initialize the helper struct for AST creation.
106   AstBuildUserInfo() = default;
107 
108   /// The dependence information used for the parallelism check.
109   const Dependences *Deps = nullptr;
110 
111   /// Flag to indicate that we are inside a parallel for node.
112   bool InParallelFor = false;
113 
114   /// Flag to indicate that we are inside an SIMD node.
115   bool InSIMD = false;
116 
117   /// The last iterator id created for the current SCoP.
118   isl_id *LastForNodeId = nullptr;
119 };
120 } // namespace polly
121 
122 /// Free an IslAstUserPayload object pointed to by @p Ptr.
123 static void freeIslAstUserPayload(void *Ptr) {
124   delete ((IslAstInfo::IslAstUserPayload *)Ptr);
125 }
126 
127 IslAstInfo::IslAstUserPayload::~IslAstUserPayload() {
128   isl_ast_build_free(Build);
129 }
130 
131 /// Print a string @p str in a single line using @p Printer.
132 static isl_printer *printLine(__isl_take isl_printer *Printer,
133                               const std::string &str,
134                               __isl_keep isl_pw_aff *PWA = nullptr) {
135   Printer = isl_printer_start_line(Printer);
136   Printer = isl_printer_print_str(Printer, str.c_str());
137   if (PWA)
138     Printer = isl_printer_print_pw_aff(Printer, PWA);
139   return isl_printer_end_line(Printer);
140 }
141 
142 /// Return all broken reductions as a string of clauses (OpenMP style).
143 static const std::string getBrokenReductionsStr(const isl::ast_node &Node) {
144   IslAstInfo::MemoryAccessSet *BrokenReductions;
145   std::string str;
146 
147   BrokenReductions = IslAstInfo::getBrokenReductions(Node);
148   if (!BrokenReductions || BrokenReductions->empty())
149     return "";
150 
151   // Map each type of reduction to a comma separated list of the base addresses.
152   std::map<MemoryAccess::ReductionType, std::string> Clauses;
153   for (MemoryAccess *MA : *BrokenReductions)
154     if (MA->isWrite())
155       Clauses[MA->getReductionType()] +=
156           ", " + MA->getScopArrayInfo()->getName();
157 
158   // Now print the reductions sorted by type. Each type will cause a clause
159   // like:  reduction (+ : sum0, sum1, sum2)
160   for (const auto &ReductionClause : Clauses) {
161     str += " reduction (";
162     str += MemoryAccess::getReductionOperatorStr(ReductionClause.first);
163     // Remove the first two symbols (", ") to make the output look pretty.
164     str += " : " + ReductionClause.second.substr(2) + ")";
165   }
166 
167   return str;
168 }
169 
170 /// Callback executed for each for node in the ast in order to print it.
171 static isl_printer *cbPrintFor(__isl_take isl_printer *Printer,
172                                __isl_take isl_ast_print_options *Options,
173                                __isl_keep isl_ast_node *Node, void *) {
174   isl::pw_aff DD =
175       IslAstInfo::getMinimalDependenceDistance(isl::manage_copy(Node));
176   const std::string BrokenReductionsStr =
177       getBrokenReductionsStr(isl::manage_copy(Node));
178   const std::string KnownParallelStr = "#pragma known-parallel";
179   const std::string DepDisPragmaStr = "#pragma minimal dependence distance: ";
180   const std::string SimdPragmaStr = "#pragma simd";
181   const std::string OmpPragmaStr = "#pragma omp parallel for";
182 
183   if (!DD.is_null())
184     Printer = printLine(Printer, DepDisPragmaStr, DD.get());
185 
186   if (IslAstInfo::isInnermostParallel(isl::manage_copy(Node)))
187     Printer = printLine(Printer, SimdPragmaStr + BrokenReductionsStr);
188 
189   if (IslAstInfo::isExecutedInParallel(isl::manage_copy(Node)))
190     Printer = printLine(Printer, OmpPragmaStr);
191   else if (IslAstInfo::isOutermostParallel(isl::manage_copy(Node)))
192     Printer = printLine(Printer, KnownParallelStr + BrokenReductionsStr);
193 
194   return isl_ast_node_for_print(Node, Printer, Options);
195 }
196 
197 /// Check if the current scheduling dimension is parallel.
198 ///
199 /// In case the dimension is parallel we also check if any reduction
200 /// dependences is broken when we exploit this parallelism. If so,
201 /// @p IsReductionParallel will be set to true. The reduction dependences we use
202 /// to check are actually the union of the transitive closure of the initial
203 /// reduction dependences together with their reversal. Even though these
204 /// dependences connect all iterations with each other (thus they are cyclic)
205 /// we can perform the parallelism check as we are only interested in a zero
206 /// (or non-zero) dependence distance on the dimension in question.
207 static bool astScheduleDimIsParallel(const isl::ast_build &Build,
208                                      const Dependences *D,
209                                      IslAstUserPayload *NodeInfo) {
210   if (!D->hasValidDependences())
211     return false;
212 
213   isl::union_map Schedule = Build.get_schedule();
214   isl::union_map Dep = D->getDependences(
215       Dependences::TYPE_RAW | Dependences::TYPE_WAW | Dependences::TYPE_WAR);
216 
217   if (!D->isParallel(Schedule.get(), Dep.release())) {
218     isl::union_map DepsAll =
219         D->getDependences(Dependences::TYPE_RAW | Dependences::TYPE_WAW |
220                           Dependences::TYPE_WAR | Dependences::TYPE_TC_RED);
221     // TODO: We will need to change isParallel to stop the unwrapping
222     isl_pw_aff *MinimalDependenceDistanceIsl = nullptr;
223     D->isParallel(Schedule.get(), DepsAll.release(),
224                   &MinimalDependenceDistanceIsl);
225     NodeInfo->MinimalDependenceDistance =
226         isl::manage(MinimalDependenceDistanceIsl);
227     return false;
228   }
229 
230   isl::union_map RedDeps = D->getDependences(Dependences::TYPE_TC_RED);
231   if (!D->isParallel(Schedule.get(), RedDeps.release()))
232     NodeInfo->IsReductionParallel = true;
233 
234   if (!NodeInfo->IsReductionParallel)
235     return true;
236 
237   for (const auto &MaRedPair : D->getReductionDependences()) {
238     if (!MaRedPair.second)
239       continue;
240     isl::union_map MaRedDeps = isl::manage_copy(MaRedPair.second);
241     if (!D->isParallel(Schedule.get(), MaRedDeps.release()))
242       NodeInfo->BrokenReductions.insert(MaRedPair.first);
243   }
244   return true;
245 }
246 
247 // This method is executed before the construction of a for node. It creates
248 // an isl_id that is used to annotate the subsequently generated ast for nodes.
249 //
250 // In this function we also run the following analyses:
251 //
252 // - Detection of openmp parallel loops
253 //
254 static __isl_give isl_id *astBuildBeforeFor(__isl_keep isl_ast_build *Build,
255                                             void *User) {
256   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
257   IslAstUserPayload *Payload = new IslAstUserPayload();
258   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
259   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
260   BuildInfo->LastForNodeId = Id;
261 
262   Payload->IsParallel = astScheduleDimIsParallel(isl::manage_copy(Build),
263                                                  BuildInfo->Deps, Payload);
264 
265   // Test for parallelism only if we are not already inside a parallel loop
266   if (!BuildInfo->InParallelFor && !BuildInfo->InSIMD)
267     BuildInfo->InParallelFor = Payload->IsOutermostParallel =
268         Payload->IsParallel;
269 
270   return Id;
271 }
272 
273 // This method is executed after the construction of a for node.
274 //
275 // It performs the following actions:
276 //
277 // - Reset the 'InParallelFor' flag, as soon as we leave a for node,
278 //   that is marked as openmp parallel.
279 //
280 static __isl_give isl_ast_node *
281 astBuildAfterFor(__isl_take isl_ast_node *Node, __isl_keep isl_ast_build *Build,
282                  void *User) {
283   isl_id *Id = isl_ast_node_get_annotation(Node);
284   assert(Id && "Post order visit assumes annotated for nodes");
285   IslAstUserPayload *Payload = (IslAstUserPayload *)isl_id_get_user(Id);
286   assert(Payload && "Post order visit assumes annotated for nodes");
287 
288   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
289   assert(!Payload->Build && "Build environment already set");
290   Payload->Build = isl_ast_build_copy(Build);
291   Payload->IsInnermost = (Id == BuildInfo->LastForNodeId);
292 
293   Payload->IsInnermostParallel =
294       Payload->IsInnermost && (BuildInfo->InSIMD || Payload->IsParallel);
295   if (Payload->IsOutermostParallel)
296     BuildInfo->InParallelFor = false;
297 
298   isl_id_free(Id);
299   return Node;
300 }
301 
302 static isl_stat astBuildBeforeMark(__isl_keep isl_id *MarkId,
303                                    __isl_keep isl_ast_build *Build,
304                                    void *User) {
305   if (!MarkId)
306     return isl_stat_error;
307 
308   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
309   if (strcmp(isl_id_get_name(MarkId), "SIMD") == 0)
310     BuildInfo->InSIMD = true;
311 
312   return isl_stat_ok;
313 }
314 
315 static __isl_give isl_ast_node *
316 astBuildAfterMark(__isl_take isl_ast_node *Node,
317                   __isl_keep isl_ast_build *Build, void *User) {
318   assert(isl_ast_node_get_type(Node) == isl_ast_node_mark);
319   AstBuildUserInfo *BuildInfo = (AstBuildUserInfo *)User;
320   auto *Id = isl_ast_node_mark_get_id(Node);
321   if (strcmp(isl_id_get_name(Id), "SIMD") == 0)
322     BuildInfo->InSIMD = false;
323   isl_id_free(Id);
324   return Node;
325 }
326 
327 static __isl_give isl_ast_node *AtEachDomain(__isl_take isl_ast_node *Node,
328                                              __isl_keep isl_ast_build *Build,
329                                              void *User) {
330   assert(!isl_ast_node_get_annotation(Node) && "Node already annotated");
331 
332   IslAstUserPayload *Payload = new IslAstUserPayload();
333   isl_id *Id = isl_id_alloc(isl_ast_build_get_ctx(Build), "", Payload);
334   Id = isl_id_set_free_user(Id, freeIslAstUserPayload);
335 
336   Payload->Build = isl_ast_build_copy(Build);
337 
338   return isl_ast_node_set_annotation(Node, Id);
339 }
340 
341 // Build alias check condition given a pair of minimal/maximal access.
342 static isl::ast_expr buildCondition(Scop &S, isl::ast_build Build,
343                                     const Scop::MinMaxAccessTy *It0,
344                                     const Scop::MinMaxAccessTy *It1) {
345 
346   isl::pw_multi_aff AFirst = It0->first;
347   isl::pw_multi_aff ASecond = It0->second;
348   isl::pw_multi_aff BFirst = It1->first;
349   isl::pw_multi_aff BSecond = It1->second;
350 
351   isl::id Left = AFirst.get_tuple_id(isl::dim::set);
352   isl::id Right = BFirst.get_tuple_id(isl::dim::set);
353 
354   isl::ast_expr True =
355       isl::ast_expr::from_val(isl::val::int_from_ui(Build.get_ctx(), 1));
356   isl::ast_expr False =
357       isl::ast_expr::from_val(isl::val::int_from_ui(Build.get_ctx(), 0));
358 
359   const ScopArrayInfo *BaseLeft =
360       ScopArrayInfo::getFromId(Left)->getBasePtrOriginSAI();
361   const ScopArrayInfo *BaseRight =
362       ScopArrayInfo::getFromId(Right)->getBasePtrOriginSAI();
363   if (BaseLeft && BaseLeft == BaseRight)
364     return True;
365 
366   isl::set Params = S.getContext();
367 
368   isl::ast_expr NonAliasGroup, MinExpr, MaxExpr;
369 
370   // In the following, we first check if any accesses will be empty under
371   // the execution context of the scop and do not code generate them if this
372   // is the case as isl will fail to derive valid AST expressions for such
373   // accesses.
374 
375   if (!AFirst.intersect_params(Params).domain().is_empty() &&
376       !BSecond.intersect_params(Params).domain().is_empty()) {
377     MinExpr = Build.access_from(AFirst).address_of();
378     MaxExpr = Build.access_from(BSecond).address_of();
379     NonAliasGroup = MaxExpr.le(MinExpr);
380   }
381 
382   if (!BFirst.intersect_params(Params).domain().is_empty() &&
383       !ASecond.intersect_params(Params).domain().is_empty()) {
384     MinExpr = Build.access_from(BFirst).address_of();
385     MaxExpr = Build.access_from(ASecond).address_of();
386 
387     isl::ast_expr Result = MaxExpr.le(MinExpr);
388     if (!NonAliasGroup.is_null())
389       NonAliasGroup = isl::manage(
390           isl_ast_expr_or(NonAliasGroup.release(), Result.release()));
391     else
392       NonAliasGroup = Result;
393   }
394 
395   if (NonAliasGroup.is_null())
396     NonAliasGroup = True;
397 
398   return NonAliasGroup;
399 }
400 
401 __isl_give isl_ast_expr *
402 IslAst::buildRunCondition(Scop &S, __isl_keep isl_ast_build *Build) {
403   isl_ast_expr *RunCondition;
404 
405   // The conditions that need to be checked at run-time for this scop are
406   // available as an isl_set in the runtime check context from which we can
407   // directly derive a run-time condition.
408   auto *PosCond =
409       isl_ast_build_expr_from_set(Build, S.getAssumedContext().release());
410   if (S.hasTrivialInvalidContext()) {
411     RunCondition = PosCond;
412   } else {
413     auto *ZeroV = isl_val_zero(isl_ast_build_get_ctx(Build));
414     auto *NegCond =
415         isl_ast_build_expr_from_set(Build, S.getInvalidContext().release());
416     auto *NotNegCond = isl_ast_expr_eq(isl_ast_expr_from_val(ZeroV), NegCond);
417     RunCondition = isl_ast_expr_and(PosCond, NotNegCond);
418   }
419 
420   // Create the alias checks from the minimal/maximal accesses in each alias
421   // group which consists of read only and non read only (read write) accesses.
422   // This operation is by construction quadratic in the read-write pointers and
423   // linear in the read only pointers in each alias group.
424   for (const Scop::MinMaxVectorPairTy &MinMaxAccessPair : S.getAliasGroups()) {
425     auto &MinMaxReadWrite = MinMaxAccessPair.first;
426     auto &MinMaxReadOnly = MinMaxAccessPair.second;
427     auto RWAccEnd = MinMaxReadWrite.end();
428 
429     for (auto RWAccIt0 = MinMaxReadWrite.begin(); RWAccIt0 != RWAccEnd;
430          ++RWAccIt0) {
431       for (auto RWAccIt1 = RWAccIt0 + 1; RWAccIt1 != RWAccEnd; ++RWAccIt1)
432         RunCondition = isl_ast_expr_and(
433             RunCondition,
434             buildCondition(S, isl::manage_copy(Build), RWAccIt0, RWAccIt1)
435                 .release());
436       for (const Scop::MinMaxAccessTy &ROAccIt : MinMaxReadOnly)
437         RunCondition = isl_ast_expr_and(
438             RunCondition,
439             buildCondition(S, isl::manage_copy(Build), RWAccIt0, &ROAccIt)
440                 .release());
441     }
442   }
443 
444   return RunCondition;
445 }
446 
447 /// Simple cost analysis for a given SCoP.
448 ///
449 /// TODO: Improve this analysis and extract it to make it usable in other
450 ///       places too.
451 ///       In order to improve the cost model we could either keep track of
452 ///       performed optimizations (e.g., tiling) or compute properties on the
453 ///       original as well as optimized SCoP (e.g., #stride-one-accesses).
454 static bool benefitsFromPolly(Scop &Scop, bool PerformParallelTest) {
455   if (PollyProcessUnprofitable)
456     return true;
457 
458   // Check if nothing interesting happened.
459   if (!PerformParallelTest && !Scop.isOptimized() &&
460       Scop.getAliasGroups().empty())
461     return false;
462 
463   // The default assumption is that Polly improves the code.
464   return true;
465 }
466 
467 /// Collect statistics for the syntax tree rooted at @p Ast.
468 static void walkAstForStatistics(__isl_keep isl_ast_node *Ast) {
469   assert(Ast);
470   isl_ast_node_foreach_descendant_top_down(
471       Ast,
472       [](__isl_keep isl_ast_node *Node, void *User) -> isl_bool {
473         switch (isl_ast_node_get_type(Node)) {
474         case isl_ast_node_for:
475           NumForLoops++;
476           if (IslAstInfo::isParallel(isl::manage_copy(Node)))
477             NumParallel++;
478           if (IslAstInfo::isInnermostParallel(isl::manage_copy(Node)))
479             NumInnermostParallel++;
480           if (IslAstInfo::isOutermostParallel(isl::manage_copy(Node)))
481             NumOutermostParallel++;
482           if (IslAstInfo::isReductionParallel(isl::manage_copy(Node)))
483             NumReductionParallel++;
484           if (IslAstInfo::isExecutedInParallel(isl::manage_copy(Node)))
485             NumExecutedInParallel++;
486           break;
487 
488         case isl_ast_node_if:
489           NumIfConditions++;
490           break;
491 
492         default:
493           break;
494         }
495 
496         // Continue traversing subtrees.
497         return isl_bool_true;
498       },
499       nullptr);
500 }
501 
502 IslAst::IslAst(Scop &Scop) : S(Scop), Ctx(Scop.getSharedIslCtx()) {}
503 
504 IslAst::IslAst(IslAst &&O)
505     : S(O.S), Root(O.Root), RunCondition(O.RunCondition), Ctx(O.Ctx) {
506   O.Root = nullptr;
507   O.RunCondition = nullptr;
508 }
509 
510 IslAst::~IslAst() {
511   isl_ast_node_free(Root);
512   isl_ast_expr_free(RunCondition);
513 }
514 
515 void IslAst::init(const Dependences &D) {
516   bool PerformParallelTest = PollyParallel || DetectParallel ||
517                              PollyVectorizerChoice != VECTORIZER_NONE;
518   auto ScheduleTree = S.getScheduleTree();
519 
520   // Skip AST and code generation if there was no benefit achieved.
521   if (!benefitsFromPolly(S, PerformParallelTest))
522     return;
523 
524   auto ScopStats = S.getStatistics();
525   ScopsBeneficial++;
526   BeneficialAffineLoops += ScopStats.NumAffineLoops;
527   BeneficialBoxedLoops += ScopStats.NumBoxedLoops;
528 
529   auto Ctx = S.getIslCtx();
530   isl_options_set_ast_build_atomic_upper_bound(Ctx.get(), true);
531   isl_options_set_ast_build_detect_min_max(Ctx.get(), true);
532   isl_ast_build *Build;
533   AstBuildUserInfo BuildInfo;
534 
535   if (UseContext)
536     Build = isl_ast_build_from_context(S.getContext().release());
537   else
538     Build = isl_ast_build_from_context(
539         isl_set_universe(S.getParamSpace().release()));
540 
541   Build = isl_ast_build_set_at_each_domain(Build, AtEachDomain, nullptr);
542 
543   if (PerformParallelTest) {
544     BuildInfo.Deps = &D;
545     BuildInfo.InParallelFor = false;
546     BuildInfo.InSIMD = false;
547 
548     Build = isl_ast_build_set_before_each_for(Build, &astBuildBeforeFor,
549                                               &BuildInfo);
550     Build =
551         isl_ast_build_set_after_each_for(Build, &astBuildAfterFor, &BuildInfo);
552 
553     Build = isl_ast_build_set_before_each_mark(Build, &astBuildBeforeMark,
554                                                &BuildInfo);
555 
556     Build = isl_ast_build_set_after_each_mark(Build, &astBuildAfterMark,
557                                               &BuildInfo);
558   }
559 
560   RunCondition = buildRunCondition(S, Build);
561 
562   Root = isl_ast_build_node_from_schedule(Build, S.getScheduleTree().release());
563   walkAstForStatistics(Root);
564 
565   isl_ast_build_free(Build);
566 }
567 
568 IslAst IslAst::create(Scop &Scop, const Dependences &D) {
569   IslAst Ast{Scop};
570   Ast.init(D);
571   return Ast;
572 }
573 
574 __isl_give isl_ast_node *IslAst::getAst() { return isl_ast_node_copy(Root); }
575 __isl_give isl_ast_expr *IslAst::getRunCondition() {
576   return isl_ast_expr_copy(RunCondition);
577 }
578 
579 __isl_give isl_ast_node *IslAstInfo::getAst() { return Ast.getAst(); }
580 __isl_give isl_ast_expr *IslAstInfo::getRunCondition() {
581   return Ast.getRunCondition();
582 }
583 
584 IslAstUserPayload *IslAstInfo::getNodePayload(const isl::ast_node &Node) {
585   isl::id Id = Node.get_annotation();
586   if (!Id)
587     return nullptr;
588   IslAstUserPayload *Payload = (IslAstUserPayload *)Id.get_user();
589   return Payload;
590 }
591 
592 bool IslAstInfo::isInnermost(const isl::ast_node &Node) {
593   IslAstUserPayload *Payload = getNodePayload(Node);
594   return Payload && Payload->IsInnermost;
595 }
596 
597 bool IslAstInfo::isParallel(const isl::ast_node &Node) {
598   return IslAstInfo::isInnermostParallel(Node) ||
599          IslAstInfo::isOutermostParallel(Node);
600 }
601 
602 bool IslAstInfo::isInnermostParallel(const isl::ast_node &Node) {
603   IslAstUserPayload *Payload = getNodePayload(Node);
604   return Payload && Payload->IsInnermostParallel;
605 }
606 
607 bool IslAstInfo::isOutermostParallel(const isl::ast_node &Node) {
608   IslAstUserPayload *Payload = getNodePayload(Node);
609   return Payload && Payload->IsOutermostParallel;
610 }
611 
612 bool IslAstInfo::isReductionParallel(const isl::ast_node &Node) {
613   IslAstUserPayload *Payload = getNodePayload(Node);
614   return Payload && Payload->IsReductionParallel;
615 }
616 
617 bool IslAstInfo::isExecutedInParallel(const isl::ast_node &Node) {
618   if (!PollyParallel)
619     return false;
620 
621   // Do not parallelize innermost loops.
622   //
623   // Parallelizing innermost loops is often not profitable, especially if
624   // they have a low number of iterations.
625   //
626   // TODO: Decide this based on the number of loop iterations that will be
627   //       executed. This can possibly require run-time checks, which again
628   //       raises the question of both run-time check overhead and code size
629   //       costs.
630   if (!PollyParallelForce && isInnermost(Node))
631     return false;
632 
633   return isOutermostParallel(Node) && !isReductionParallel(Node);
634 }
635 
636 isl::union_map IslAstInfo::getSchedule(const isl::ast_node &Node) {
637   IslAstUserPayload *Payload = getNodePayload(Node);
638   if (!Payload)
639     return nullptr;
640 
641   isl::ast_build Build = isl::manage_copy(Payload->Build);
642   return Build.get_schedule();
643 }
644 
645 isl::pw_aff
646 IslAstInfo::getMinimalDependenceDistance(const isl::ast_node &Node) {
647   IslAstUserPayload *Payload = getNodePayload(Node);
648   return Payload ? Payload->MinimalDependenceDistance : nullptr;
649 }
650 
651 IslAstInfo::MemoryAccessSet *
652 IslAstInfo::getBrokenReductions(const isl::ast_node &Node) {
653   IslAstUserPayload *Payload = getNodePayload(Node);
654   return Payload ? &Payload->BrokenReductions : nullptr;
655 }
656 
657 isl_ast_build *IslAstInfo::getBuild(__isl_keep isl_ast_node *Node) {
658   IslAstUserPayload *Payload = getNodePayload(isl::manage_copy(Node));
659   return Payload ? Payload->Build : nullptr;
660 }
661 
662 static std::unique_ptr<IslAstInfo> runIslAst(
663     Scop &Scop,
664     function_ref<const Dependences &(Dependences::AnalysisLevel)> GetDeps) {
665   // Skip SCoPs in case they're already handled by PPCGCodeGeneration.
666   if (Scop.isToBeSkipped())
667     return {};
668 
669   ScopsProcessed++;
670 
671   const Dependences &D = GetDeps(Dependences::AL_Statement);
672 
673   if (D.getSharedIslCtx() != Scop.getSharedIslCtx()) {
674     LLVM_DEBUG(
675         dbgs() << "Got dependence analysis for different SCoP/isl_ctx\n");
676     return {};
677   }
678 
679   std::unique_ptr<IslAstInfo> Ast = std::make_unique<IslAstInfo>(Scop, D);
680 
681   LLVM_DEBUG({
682     if (Ast)
683       Ast->print(dbgs());
684   });
685 
686   return Ast;
687 }
688 
689 IslAstInfo IslAstAnalysis::run(Scop &S, ScopAnalysisManager &SAM,
690                                ScopStandardAnalysisResults &SAR) {
691   auto GetDeps = [&](Dependences::AnalysisLevel Lvl) -> const Dependences & {
692     return SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(Lvl);
693   };
694 
695   return std::move(*runIslAst(S, GetDeps).release());
696 }
697 
698 static __isl_give isl_printer *cbPrintUser(__isl_take isl_printer *P,
699                                            __isl_take isl_ast_print_options *O,
700                                            __isl_keep isl_ast_node *Node,
701                                            void *User) {
702   isl::ast_node AstNode = isl::manage_copy(Node);
703   isl::ast_expr NodeExpr = AstNode.user_get_expr();
704   isl::ast_expr CallExpr = NodeExpr.get_op_arg(0);
705   isl::id CallExprId = CallExpr.get_id();
706   ScopStmt *AccessStmt = (ScopStmt *)CallExprId.get_user();
707 
708   P = isl_printer_start_line(P);
709   P = isl_printer_print_str(P, AccessStmt->getBaseName());
710   P = isl_printer_print_str(P, "(");
711   P = isl_printer_end_line(P);
712   P = isl_printer_indent(P, 2);
713 
714   for (MemoryAccess *MemAcc : *AccessStmt) {
715     P = isl_printer_start_line(P);
716 
717     if (MemAcc->isRead())
718       P = isl_printer_print_str(P, "/* read  */ &");
719     else
720       P = isl_printer_print_str(P, "/* write */  ");
721 
722     isl::ast_build Build = isl::manage_copy(IslAstInfo::getBuild(Node));
723     if (MemAcc->isAffine()) {
724       isl_pw_multi_aff *PwmaPtr =
725           MemAcc->applyScheduleToAccessRelation(Build.get_schedule()).release();
726       isl::pw_multi_aff Pwma = isl::manage(PwmaPtr);
727       isl::ast_expr AccessExpr = Build.access_from(Pwma);
728       P = isl_printer_print_ast_expr(P, AccessExpr.get());
729     } else {
730       P = isl_printer_print_str(
731           P, MemAcc->getLatestScopArrayInfo()->getName().c_str());
732       P = isl_printer_print_str(P, "[*]");
733     }
734     P = isl_printer_end_line(P);
735   }
736 
737   P = isl_printer_indent(P, -2);
738   P = isl_printer_start_line(P);
739   P = isl_printer_print_str(P, ");");
740   P = isl_printer_end_line(P);
741 
742   isl_ast_print_options_free(O);
743   return P;
744 }
745 
746 void IslAstInfo::print(raw_ostream &OS) {
747   isl_ast_print_options *Options;
748   isl_ast_node *RootNode = Ast.getAst();
749   Function &F = S.getFunction();
750 
751   OS << ":: isl ast :: " << F.getName() << " :: " << S.getNameStr() << "\n";
752 
753   if (!RootNode) {
754     OS << ":: isl ast generation and code generation was skipped!\n\n";
755     OS << ":: This is either because no useful optimizations could be applied "
756           "(use -polly-process-unprofitable to enforce code generation) or "
757           "because earlier passes such as dependence analysis timed out (use "
758           "-polly-dependences-computeout=0 to set dependence analysis timeout "
759           "to infinity)\n\n";
760     return;
761   }
762 
763   isl_ast_expr *RunCondition = Ast.getRunCondition();
764   char *RtCStr, *AstStr;
765 
766   Options = isl_ast_print_options_alloc(S.getIslCtx().get());
767 
768   if (PrintAccesses)
769     Options =
770         isl_ast_print_options_set_print_user(Options, cbPrintUser, nullptr);
771   Options = isl_ast_print_options_set_print_for(Options, cbPrintFor, nullptr);
772 
773   isl_printer *P = isl_printer_to_str(S.getIslCtx().get());
774   P = isl_printer_set_output_format(P, ISL_FORMAT_C);
775   P = isl_printer_print_ast_expr(P, RunCondition);
776   RtCStr = isl_printer_get_str(P);
777   P = isl_printer_flush(P);
778   P = isl_printer_indent(P, 4);
779   P = isl_ast_node_print(RootNode, P, Options);
780   AstStr = isl_printer_get_str(P);
781 
782   auto *Schedule = S.getScheduleTree().release();
783 
784   LLVM_DEBUG({
785     dbgs() << S.getContextStr() << "\n";
786     dbgs() << stringFromIslObj(Schedule);
787   });
788   OS << "\nif (" << RtCStr << ")\n\n";
789   OS << AstStr << "\n";
790   OS << "else\n";
791   OS << "    {  /* original code */ }\n\n";
792 
793   free(RtCStr);
794   free(AstStr);
795 
796   isl_ast_expr_free(RunCondition);
797   isl_schedule_free(Schedule);
798   isl_ast_node_free(RootNode);
799   isl_printer_free(P);
800 }
801 
802 AnalysisKey IslAstAnalysis::Key;
803 PreservedAnalyses IslAstPrinterPass::run(Scop &S, ScopAnalysisManager &SAM,
804                                          ScopStandardAnalysisResults &SAR,
805                                          SPMUpdater &U) {
806   auto &Ast = SAM.getResult<IslAstAnalysis>(S, SAR);
807   Ast.print(OS);
808   return PreservedAnalyses::all();
809 }
810 
811 void IslAstInfoWrapperPass::releaseMemory() { Ast.reset(); }
812 
813 bool IslAstInfoWrapperPass::runOnScop(Scop &Scop) {
814   auto GetDeps = [this](Dependences::AnalysisLevel Lvl) -> const Dependences & {
815     return getAnalysis<DependenceInfo>().getDependences(Lvl);
816   };
817 
818   Ast = runIslAst(Scop, GetDeps);
819 
820   return false;
821 }
822 
823 void IslAstInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
824   // Get the Common analysis usage of ScopPasses.
825   ScopPass::getAnalysisUsage(AU);
826   AU.addRequiredTransitive<ScopInfoRegionPass>();
827   AU.addRequired<DependenceInfo>();
828 
829   AU.addPreserved<DependenceInfo>();
830 }
831 
832 void IslAstInfoWrapperPass::printScop(raw_ostream &OS, Scop &S) const {
833   OS << "Printing analysis 'Polly - Generate an AST of the SCoP (isl)'"
834      << S.getName() << "' in function '" << S.getFunction().getName() << "':\n";
835   if (Ast)
836     Ast->print(OS);
837 }
838 
839 char IslAstInfoWrapperPass::ID = 0;
840 
841 Pass *polly::createIslAstInfoWrapperPassPass() {
842   return new IslAstInfoWrapperPass();
843 }
844 
845 INITIALIZE_PASS_BEGIN(IslAstInfoWrapperPass, "polly-ast",
846                       "Polly - Generate an AST of the SCoP (isl)", false,
847                       false);
848 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
849 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
850 INITIALIZE_PASS_END(IslAstInfoWrapperPass, "polly-ast",
851                     "Polly - Generate an AST from the SCoP (isl)", false, false)
852