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