Coverage Report

Created: 2018-04-24 22:41

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