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