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