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