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