Coverage Report

Created: 2018-10-23 03:11

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