1 //===- polly/ScheduleTreeTransform.cpp --------------------------*- C++ -*-===// 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 // Make changes to isl's schedule tree data structure. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "polly/ScheduleTreeTransform.h" 14 #include "polly/Support/ISLTools.h" 15 #include "polly/Support/ScopHelper.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/Sequence.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Metadata.h" 21 #include "llvm/Transforms/Utils/UnrollLoop.h" 22 23 using namespace polly; 24 using namespace llvm; 25 26 namespace { 27 /// Recursively visit all nodes of a schedule tree while allowing changes. 28 /// 29 /// The visit methods return an isl::schedule_node that is used to continue 30 /// visiting the tree. Structural changes such as returning a different node 31 /// will confuse the visitor. 32 template <typename Derived, typename... Args> 33 struct ScheduleNodeRewriter 34 : public RecursiveScheduleTreeVisitor<Derived, isl::schedule_node, 35 Args...> { 36 Derived &getDerived() { return *static_cast<Derived *>(this); } 37 const Derived &getDerived() const { 38 return *static_cast<const Derived *>(this); 39 } 40 41 isl::schedule_node visitNode(const isl::schedule_node &Node, Args... args) { 42 if (!Node.has_children()) 43 return Node; 44 45 isl::schedule_node It = Node.first_child(); 46 while (true) { 47 It = getDerived().visit(It, std::forward<Args>(args)...); 48 if (!It.has_next_sibling()) 49 break; 50 It = It.next_sibling(); 51 } 52 return It.parent(); 53 } 54 }; 55 56 /// Rewrite a schedule tree by reconstructing it bottom-up. 57 /// 58 /// By default, the original schedule tree is reconstructed. To build a 59 /// different tree, redefine visitor methods in a derived class (CRTP). 60 /// 61 /// Note that AST build options are not applied; Setting the isolate[] option 62 /// makes the schedule tree 'anchored' and cannot be modified afterwards. Hence, 63 /// AST build options must be set after the tree has been constructed. 64 template <typename Derived, typename... Args> 65 struct ScheduleTreeRewriter 66 : public RecursiveScheduleTreeVisitor<Derived, isl::schedule, Args...> { 67 Derived &getDerived() { return *static_cast<Derived *>(this); } 68 const Derived &getDerived() const { 69 return *static_cast<const Derived *>(this); 70 } 71 72 isl::schedule visitDomain(const isl::schedule_node &Node, Args... args) { 73 // Every schedule_tree already has a domain node, no need to add one. 74 return getDerived().visit(Node.first_child(), std::forward<Args>(args)...); 75 } 76 77 isl::schedule visitBand(const isl::schedule_node &Band, Args... args) { 78 isl::multi_union_pw_aff PartialSched = 79 isl::manage(isl_schedule_node_band_get_partial_schedule(Band.get())); 80 isl::schedule NewChild = 81 getDerived().visit(Band.child(0), std::forward<Args>(args)...); 82 isl::schedule_node NewNode = 83 NewChild.insert_partial_schedule(PartialSched).get_root().get_child(0); 84 85 // Reapply permutability and coincidence attributes. 86 NewNode = isl::manage(isl_schedule_node_band_set_permutable( 87 NewNode.release(), isl_schedule_node_band_get_permutable(Band.get()))); 88 unsigned BandDims = isl_schedule_node_band_n_member(Band.get()); 89 for (unsigned i = 0; i < BandDims; i += 1) 90 NewNode = isl::manage(isl_schedule_node_band_member_set_coincident( 91 NewNode.release(), i, 92 isl_schedule_node_band_member_get_coincident(Band.get(), i))); 93 94 return NewNode.get_schedule(); 95 } 96 97 isl::schedule visitSequence(const isl::schedule_node &Sequence, 98 Args... args) { 99 int NumChildren = isl_schedule_node_n_children(Sequence.get()); 100 isl::schedule Result = 101 getDerived().visit(Sequence.child(0), std::forward<Args>(args)...); 102 for (int i = 1; i < NumChildren; i += 1) 103 Result = Result.sequence( 104 getDerived().visit(Sequence.child(i), std::forward<Args>(args)...)); 105 return Result; 106 } 107 108 isl::schedule visitSet(const isl::schedule_node &Set, Args... args) { 109 int NumChildren = isl_schedule_node_n_children(Set.get()); 110 isl::schedule Result = 111 getDerived().visit(Set.child(0), std::forward<Args>(args)...); 112 for (int i = 1; i < NumChildren; i += 1) 113 Result = isl::manage( 114 isl_schedule_set(Result.release(), 115 getDerived() 116 .visit(Set.child(i), std::forward<Args>(args)...) 117 .release())); 118 return Result; 119 } 120 121 isl::schedule visitLeaf(const isl::schedule_node &Leaf, Args... args) { 122 return isl::schedule::from_domain(Leaf.get_domain()); 123 } 124 125 isl::schedule visitMark(const isl::schedule_node &Mark, Args... args) { 126 isl::id TheMark = Mark.mark_get_id(); 127 isl::schedule_node NewChild = 128 getDerived() 129 .visit(Mark.first_child(), std::forward<Args>(args)...) 130 .get_root() 131 .first_child(); 132 return NewChild.insert_mark(TheMark).get_schedule(); 133 } 134 135 isl::schedule visitExtension(const isl::schedule_node &Extension, 136 Args... args) { 137 isl::union_map TheExtension = Extension.extension_get_extension(); 138 isl::schedule_node NewChild = getDerived() 139 .visit(Extension.child(0), args...) 140 .get_root() 141 .first_child(); 142 isl::schedule_node NewExtension = 143 isl::schedule_node::from_extension(TheExtension); 144 return NewChild.graft_before(NewExtension).get_schedule(); 145 } 146 147 isl::schedule visitFilter(const isl::schedule_node &Filter, Args... args) { 148 isl::union_set FilterDomain = Filter.filter_get_filter(); 149 isl::schedule NewSchedule = 150 getDerived().visit(Filter.child(0), std::forward<Args>(args)...); 151 return NewSchedule.intersect_domain(FilterDomain); 152 } 153 154 isl::schedule visitNode(const isl::schedule_node &Node, Args... args) { 155 llvm_unreachable("Not implemented"); 156 } 157 }; 158 159 /// Rewrite a schedule tree to an equivalent one without extension nodes. 160 /// 161 /// Each visit method takes two additional arguments: 162 /// 163 /// * The new domain the node, which is the inherited domain plus any domains 164 /// added by extension nodes. 165 /// 166 /// * A map of extension domains of all children is returned; it is required by 167 /// band nodes to schedule the additional domains at the same position as the 168 /// extension node would. 169 /// 170 struct ExtensionNodeRewriter 171 : public ScheduleTreeRewriter<ExtensionNodeRewriter, const isl::union_set &, 172 isl::union_map &> { 173 using BaseTy = ScheduleTreeRewriter<ExtensionNodeRewriter, 174 const isl::union_set &, isl::union_map &>; 175 BaseTy &getBase() { return *this; } 176 const BaseTy &getBase() const { return *this; } 177 178 isl::schedule visitSchedule(const isl::schedule &Schedule) { 179 isl::union_map Extensions; 180 isl::schedule Result = 181 visit(Schedule.get_root(), Schedule.get_domain(), Extensions); 182 assert(!Extensions.is_null() && Extensions.is_empty()); 183 return Result; 184 } 185 186 isl::schedule visitSequence(const isl::schedule_node &Sequence, 187 const isl::union_set &Domain, 188 isl::union_map &Extensions) { 189 int NumChildren = isl_schedule_node_n_children(Sequence.get()); 190 isl::schedule NewNode = visit(Sequence.first_child(), Domain, Extensions); 191 for (int i = 1; i < NumChildren; i += 1) { 192 isl::schedule_node OldChild = Sequence.child(i); 193 isl::union_map NewChildExtensions; 194 isl::schedule NewChildNode = visit(OldChild, Domain, NewChildExtensions); 195 NewNode = NewNode.sequence(NewChildNode); 196 Extensions = Extensions.unite(NewChildExtensions); 197 } 198 return NewNode; 199 } 200 201 isl::schedule visitSet(const isl::schedule_node &Set, 202 const isl::union_set &Domain, 203 isl::union_map &Extensions) { 204 int NumChildren = isl_schedule_node_n_children(Set.get()); 205 isl::schedule NewNode = visit(Set.first_child(), Domain, Extensions); 206 for (int i = 1; i < NumChildren; i += 1) { 207 isl::schedule_node OldChild = Set.child(i); 208 isl::union_map NewChildExtensions; 209 isl::schedule NewChildNode = visit(OldChild, Domain, NewChildExtensions); 210 NewNode = isl::manage( 211 isl_schedule_set(NewNode.release(), NewChildNode.release())); 212 Extensions = Extensions.unite(NewChildExtensions); 213 } 214 return NewNode; 215 } 216 217 isl::schedule visitLeaf(const isl::schedule_node &Leaf, 218 const isl::union_set &Domain, 219 isl::union_map &Extensions) { 220 Extensions = isl::union_map::empty(Leaf.ctx()); 221 return isl::schedule::from_domain(Domain); 222 } 223 224 isl::schedule visitBand(const isl::schedule_node &OldNode, 225 const isl::union_set &Domain, 226 isl::union_map &OuterExtensions) { 227 isl::schedule_node OldChild = OldNode.first_child(); 228 isl::multi_union_pw_aff PartialSched = 229 isl::manage(isl_schedule_node_band_get_partial_schedule(OldNode.get())); 230 231 isl::union_map NewChildExtensions; 232 isl::schedule NewChild = visit(OldChild, Domain, NewChildExtensions); 233 234 // Add the extensions to the partial schedule. 235 OuterExtensions = isl::union_map::empty(NewChildExtensions.ctx()); 236 isl::union_map NewPartialSchedMap = isl::union_map::from(PartialSched); 237 unsigned BandDims = isl_schedule_node_band_n_member(OldNode.get()); 238 for (isl::map Ext : NewChildExtensions.get_map_list()) { 239 unsigned ExtDims = Ext.domain_tuple_dim(); 240 assert(ExtDims >= BandDims); 241 unsigned OuterDims = ExtDims - BandDims; 242 243 isl::map BandSched = 244 Ext.project_out(isl::dim::in, 0, OuterDims).reverse(); 245 NewPartialSchedMap = NewPartialSchedMap.unite(BandSched); 246 247 // There might be more outer bands that have to schedule the extensions. 248 if (OuterDims > 0) { 249 isl::map OuterSched = 250 Ext.project_out(isl::dim::in, OuterDims, BandDims); 251 OuterExtensions = OuterExtensions.unite(OuterSched); 252 } 253 } 254 isl::multi_union_pw_aff NewPartialSchedAsAsMultiUnionPwAff = 255 isl::multi_union_pw_aff::from_union_map(NewPartialSchedMap); 256 isl::schedule_node NewNode = 257 NewChild.insert_partial_schedule(NewPartialSchedAsAsMultiUnionPwAff) 258 .get_root() 259 .get_child(0); 260 261 // Reapply permutability and coincidence attributes. 262 NewNode = isl::manage(isl_schedule_node_band_set_permutable( 263 NewNode.release(), 264 isl_schedule_node_band_get_permutable(OldNode.get()))); 265 for (unsigned i = 0; i < BandDims; i += 1) { 266 NewNode = isl::manage(isl_schedule_node_band_member_set_coincident( 267 NewNode.release(), i, 268 isl_schedule_node_band_member_get_coincident(OldNode.get(), i))); 269 } 270 271 return NewNode.get_schedule(); 272 } 273 274 isl::schedule visitFilter(const isl::schedule_node &Filter, 275 const isl::union_set &Domain, 276 isl::union_map &Extensions) { 277 isl::union_set FilterDomain = Filter.filter_get_filter(); 278 isl::union_set NewDomain = Domain.intersect(FilterDomain); 279 280 // A filter is added implicitly if necessary when joining schedule trees. 281 return visit(Filter.first_child(), NewDomain, Extensions); 282 } 283 284 isl::schedule visitExtension(const isl::schedule_node &Extension, 285 const isl::union_set &Domain, 286 isl::union_map &Extensions) { 287 isl::union_map ExtDomain = Extension.extension_get_extension(); 288 isl::union_set NewDomain = Domain.unite(ExtDomain.range()); 289 isl::union_map ChildExtensions; 290 isl::schedule NewChild = 291 visit(Extension.first_child(), NewDomain, ChildExtensions); 292 Extensions = ChildExtensions.unite(ExtDomain); 293 return NewChild; 294 } 295 }; 296 297 /// Collect all AST build options in any schedule tree band. 298 /// 299 /// ScheduleTreeRewriter cannot apply the schedule tree options. This class 300 /// collects these options to apply them later. 301 struct CollectASTBuildOptions 302 : public RecursiveScheduleTreeVisitor<CollectASTBuildOptions> { 303 using BaseTy = RecursiveScheduleTreeVisitor<CollectASTBuildOptions>; 304 BaseTy &getBase() { return *this; } 305 const BaseTy &getBase() const { return *this; } 306 307 llvm::SmallVector<isl::union_set, 8> ASTBuildOptions; 308 309 void visitBand(const isl::schedule_node &Band) { 310 ASTBuildOptions.push_back( 311 isl::manage(isl_schedule_node_band_get_ast_build_options(Band.get()))); 312 return getBase().visitBand(Band); 313 } 314 }; 315 316 /// Apply AST build options to the bands in a schedule tree. 317 /// 318 /// This rewrites a schedule tree with the AST build options applied. We assume 319 /// that the band nodes are visited in the same order as they were when the 320 /// build options were collected, typically by CollectASTBuildOptions. 321 struct ApplyASTBuildOptions 322 : public ScheduleNodeRewriter<ApplyASTBuildOptions> { 323 using BaseTy = ScheduleNodeRewriter<ApplyASTBuildOptions>; 324 BaseTy &getBase() { return *this; } 325 const BaseTy &getBase() const { return *this; } 326 327 size_t Pos; 328 llvm::ArrayRef<isl::union_set> ASTBuildOptions; 329 330 ApplyASTBuildOptions(llvm::ArrayRef<isl::union_set> ASTBuildOptions) 331 : ASTBuildOptions(ASTBuildOptions) {} 332 333 isl::schedule visitSchedule(const isl::schedule &Schedule) { 334 Pos = 0; 335 isl::schedule Result = visit(Schedule).get_schedule(); 336 assert(Pos == ASTBuildOptions.size() && 337 "AST build options must match to band nodes"); 338 return Result; 339 } 340 341 isl::schedule_node visitBand(const isl::schedule_node &Band) { 342 isl::schedule_node Result = 343 Band.band_set_ast_build_options(ASTBuildOptions[Pos]); 344 Pos += 1; 345 return getBase().visitBand(Result); 346 } 347 }; 348 349 /// Return whether the schedule contains an extension node. 350 static bool containsExtensionNode(isl::schedule Schedule) { 351 assert(!Schedule.is_null()); 352 353 auto Callback = [](__isl_keep isl_schedule_node *Node, 354 void *User) -> isl_bool { 355 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension) { 356 // Stop walking the schedule tree. 357 return isl_bool_error; 358 } 359 360 // Continue searching the subtree. 361 return isl_bool_true; 362 }; 363 isl_stat RetVal = isl_schedule_foreach_schedule_node_top_down( 364 Schedule.get(), Callback, nullptr); 365 366 // We assume that the traversal itself does not fail, i.e. the only reason to 367 // return isl_stat_error is that an extension node was found. 368 return RetVal == isl_stat_error; 369 } 370 371 /// Find a named MDNode property in a LoopID. 372 static MDNode *findOptionalNodeOperand(MDNode *LoopMD, StringRef Name) { 373 return dyn_cast_or_null<MDNode>( 374 findMetadataOperand(LoopMD, Name).getValueOr(nullptr)); 375 } 376 377 /// Is this node of type mark? 378 static bool isMark(const isl::schedule_node &Node) { 379 return isl_schedule_node_get_type(Node.get()) == isl_schedule_node_mark; 380 } 381 382 #ifndef NDEBUG 383 /// Is this node of type band? 384 static bool isBand(const isl::schedule_node &Node) { 385 return isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band; 386 } 387 388 /// Is this node a band of a single dimension (i.e. could represent a loop)? 389 static bool isBandWithSingleLoop(const isl::schedule_node &Node) { 390 391 return isBand(Node) && isl_schedule_node_band_n_member(Node.get()) == 1; 392 } 393 #endif 394 395 /// Create an isl::id representing the output loop after a transformation. 396 static isl::id createGeneratedLoopAttr(isl::ctx Ctx, MDNode *FollowupLoopMD) { 397 // Don't need to id the followup. 398 // TODO: Append llvm.loop.disable_heustistics metadata unless overridden by 399 // user followup-MD 400 if (!FollowupLoopMD) 401 return {}; 402 403 BandAttr *Attr = new BandAttr(); 404 Attr->Metadata = FollowupLoopMD; 405 return getIslLoopAttr(Ctx, Attr); 406 } 407 408 /// A loop consists of a band and an optional marker that wraps it. Return the 409 /// outermost of the two. 410 411 /// That is, either the mark or, if there is not mark, the loop itself. Can 412 /// start with either the mark or the band. 413 static isl::schedule_node moveToBandMark(isl::schedule_node BandOrMark) { 414 if (isBandMark(BandOrMark)) { 415 assert(isBandWithSingleLoop(BandOrMark.get_child(0))); 416 return BandOrMark; 417 } 418 assert(isBandWithSingleLoop(BandOrMark)); 419 420 isl::schedule_node Mark = BandOrMark.parent(); 421 if (isBandMark(Mark)) 422 return Mark; 423 424 // Band has no loop marker. 425 return BandOrMark; 426 } 427 428 static isl::schedule_node removeMark(isl::schedule_node MarkOrBand, 429 BandAttr *&Attr) { 430 MarkOrBand = moveToBandMark(MarkOrBand); 431 432 isl::schedule_node Band; 433 if (isMark(MarkOrBand)) { 434 Attr = getLoopAttr(MarkOrBand.mark_get_id()); 435 Band = isl::manage(isl_schedule_node_delete(MarkOrBand.release())); 436 } else { 437 Attr = nullptr; 438 Band = MarkOrBand; 439 } 440 441 assert(isBandWithSingleLoop(Band)); 442 return Band; 443 } 444 445 /// Remove the mark that wraps a loop. Return the band representing the loop. 446 static isl::schedule_node removeMark(isl::schedule_node MarkOrBand) { 447 BandAttr *Attr; 448 return removeMark(MarkOrBand, Attr); 449 } 450 451 static isl::schedule_node insertMark(isl::schedule_node Band, isl::id Mark) { 452 assert(isBand(Band)); 453 assert(moveToBandMark(Band).is_equal(Band) && 454 "Don't add a two marks for a band"); 455 456 return Band.insert_mark(Mark).get_child(0); 457 } 458 459 /// Return the (one-dimensional) set of numbers that are divisible by @p Factor 460 /// with remainder @p Offset. 461 /// 462 /// isDivisibleBySet(Ctx, 4, 0) = { [i] : floord(i,4) = 0 } 463 /// isDivisibleBySet(Ctx, 4, 1) = { [i] : floord(i,4) = 1 } 464 /// 465 static isl::basic_set isDivisibleBySet(isl::ctx &Ctx, long Factor, 466 long Offset) { 467 isl::val ValFactor{Ctx, Factor}; 468 isl::val ValOffset{Ctx, Offset}; 469 470 isl::space Unispace{Ctx, 0, 1}; 471 isl::local_space LUnispace{Unispace}; 472 isl::aff AffFactor{LUnispace, ValFactor}; 473 isl::aff AffOffset{LUnispace, ValOffset}; 474 475 isl::aff Id = isl::aff::var_on_domain(LUnispace, isl::dim::out, 0); 476 isl::aff DivMul = Id.mod(ValFactor); 477 isl::basic_map Divisible = isl::basic_map::from_aff(DivMul); 478 isl::basic_map Modulo = Divisible.fix_val(isl::dim::out, 0, ValOffset); 479 return Modulo.domain(); 480 } 481 482 /// Make the last dimension of Set to take values from 0 to VectorWidth - 1. 483 /// 484 /// @param Set A set, which should be modified. 485 /// @param VectorWidth A parameter, which determines the constraint. 486 static isl::set addExtentConstraints(isl::set Set, int VectorWidth) { 487 unsigned Dims = Set.tuple_dim(); 488 isl::space Space = Set.get_space(); 489 isl::local_space LocalSpace = isl::local_space(Space); 490 isl::constraint ExtConstr = isl::constraint::alloc_inequality(LocalSpace); 491 ExtConstr = ExtConstr.set_constant_si(0); 492 ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, 1); 493 Set = Set.add_constraint(ExtConstr); 494 ExtConstr = isl::constraint::alloc_inequality(LocalSpace); 495 ExtConstr = ExtConstr.set_constant_si(VectorWidth - 1); 496 ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, -1); 497 return Set.add_constraint(ExtConstr); 498 } 499 } // namespace 500 501 bool polly::isBandMark(const isl::schedule_node &Node) { 502 return isMark(Node) && isLoopAttr(Node.mark_get_id()); 503 } 504 505 BandAttr *polly::getBandAttr(isl::schedule_node MarkOrBand) { 506 MarkOrBand = moveToBandMark(MarkOrBand); 507 if (!isMark(MarkOrBand)) 508 return nullptr; 509 510 return getLoopAttr(MarkOrBand.mark_get_id()); 511 } 512 513 isl::schedule polly::hoistExtensionNodes(isl::schedule Sched) { 514 // If there is no extension node in the first place, return the original 515 // schedule tree. 516 if (!containsExtensionNode(Sched)) 517 return Sched; 518 519 // Build options can anchor schedule nodes, such that the schedule tree cannot 520 // be modified anymore. Therefore, apply build options after the tree has been 521 // created. 522 CollectASTBuildOptions Collector; 523 Collector.visit(Sched); 524 525 // Rewrite the schedule tree without extension nodes. 526 ExtensionNodeRewriter Rewriter; 527 isl::schedule NewSched = Rewriter.visitSchedule(Sched); 528 529 // Reapply the AST build options. The rewriter must not change the iteration 530 // order of bands. Any other node type is ignored. 531 ApplyASTBuildOptions Applicator(Collector.ASTBuildOptions); 532 NewSched = Applicator.visitSchedule(NewSched); 533 534 return NewSched; 535 } 536 537 isl::schedule polly::applyFullUnroll(isl::schedule_node BandToUnroll) { 538 isl::ctx Ctx = BandToUnroll.ctx(); 539 540 // Remove the loop's mark, the loop will disappear anyway. 541 BandToUnroll = removeMark(BandToUnroll); 542 assert(isBandWithSingleLoop(BandToUnroll)); 543 544 isl::multi_union_pw_aff PartialSched = isl::manage( 545 isl_schedule_node_band_get_partial_schedule(BandToUnroll.get())); 546 assert(PartialSched.dim(isl::dim::out) == 1 && 547 "Can only unroll a single dimension"); 548 isl::union_pw_aff PartialSchedUAff = PartialSched.get_union_pw_aff(0); 549 550 isl::union_set Domain = BandToUnroll.get_domain(); 551 PartialSchedUAff = PartialSchedUAff.intersect_domain(Domain); 552 isl::union_map PartialSchedUMap = isl::union_map(PartialSchedUAff); 553 554 // Enumerator only the scatter elements. 555 isl::union_set ScatterList = PartialSchedUMap.range(); 556 557 // Enumerate all loop iterations. 558 // TODO: Diagnose if not enumerable or depends on a parameter. 559 SmallVector<isl::point, 16> Elts; 560 ScatterList.foreach_point([&Elts](isl::point P) -> isl::stat { 561 Elts.push_back(P); 562 return isl::stat::ok(); 563 }); 564 565 // Don't assume that foreach_point returns in execution order. 566 llvm::sort(Elts, [](isl::point P1, isl::point P2) -> bool { 567 isl::val C1 = P1.get_coordinate_val(isl::dim::set, 0); 568 isl::val C2 = P2.get_coordinate_val(isl::dim::set, 0); 569 return C1.lt(C2); 570 }); 571 572 // Convert the points to a sequence of filters. 573 isl::union_set_list List = isl::union_set_list::alloc(Ctx, Elts.size()); 574 for (isl::point P : Elts) { 575 // Determine the domains that map this scatter element. 576 isl::union_set DomainFilter = PartialSchedUMap.intersect_range(P).domain(); 577 578 List = List.add(DomainFilter); 579 } 580 581 // Replace original band with unrolled sequence. 582 isl::schedule_node Body = 583 isl::manage(isl_schedule_node_delete(BandToUnroll.release())); 584 Body = Body.insert_sequence(List); 585 return Body.get_schedule(); 586 } 587 588 isl::schedule polly::applyPartialUnroll(isl::schedule_node BandToUnroll, 589 int Factor) { 590 assert(Factor > 0 && "Positive unroll factor required"); 591 isl::ctx Ctx = BandToUnroll.ctx(); 592 593 // Remove the mark, save the attribute for later use. 594 BandAttr *Attr; 595 BandToUnroll = removeMark(BandToUnroll, Attr); 596 assert(isBandWithSingleLoop(BandToUnroll)); 597 598 isl::multi_union_pw_aff PartialSched = isl::manage( 599 isl_schedule_node_band_get_partial_schedule(BandToUnroll.get())); 600 601 // { Stmt[] -> [x] } 602 isl::union_pw_aff PartialSchedUAff = PartialSched.get_union_pw_aff(0); 603 604 // Here we assume the schedule stride is one and starts with 0, which is not 605 // necessarily the case. 606 isl::union_pw_aff StridedPartialSchedUAff = 607 isl::union_pw_aff::empty(PartialSchedUAff.get_space()); 608 isl::val ValFactor{Ctx, Factor}; 609 PartialSchedUAff.foreach_pw_aff([&StridedPartialSchedUAff, 610 &ValFactor](isl::pw_aff PwAff) -> isl::stat { 611 isl::space Space = PwAff.get_space(); 612 isl::set Universe = isl::set::universe(Space.domain()); 613 isl::pw_aff AffFactor{Universe, ValFactor}; 614 isl::pw_aff DivSchedAff = PwAff.div(AffFactor).floor().mul(AffFactor); 615 StridedPartialSchedUAff = StridedPartialSchedUAff.union_add(DivSchedAff); 616 return isl::stat::ok(); 617 }); 618 619 isl::union_set_list List = isl::union_set_list::alloc(Ctx, Factor); 620 for (auto i : seq<int>(0, Factor)) { 621 // { Stmt[] -> [x] } 622 isl::union_map UMap{PartialSchedUAff}; 623 624 // { [x] } 625 isl::basic_set Divisible = isDivisibleBySet(Ctx, Factor, i); 626 627 // { Stmt[] } 628 isl::union_set UnrolledDomain = UMap.intersect_range(Divisible).domain(); 629 630 List = List.add(UnrolledDomain); 631 } 632 633 isl::schedule_node Body = 634 isl::manage(isl_schedule_node_delete(BandToUnroll.copy())); 635 Body = Body.insert_sequence(List); 636 isl::schedule_node NewLoop = 637 Body.insert_partial_schedule(StridedPartialSchedUAff); 638 639 MDNode *FollowupMD = nullptr; 640 if (Attr && Attr->Metadata) 641 FollowupMD = 642 findOptionalNodeOperand(Attr->Metadata, LLVMLoopUnrollFollowupUnrolled); 643 644 isl::id NewBandId = createGeneratedLoopAttr(Ctx, FollowupMD); 645 if (!NewBandId.is_null()) 646 NewLoop = insertMark(NewLoop, NewBandId); 647 648 return NewLoop.get_schedule(); 649 } 650 651 isl::set polly::getPartialTilePrefixes(isl::set ScheduleRange, 652 int VectorWidth) { 653 isl_size Dims = ScheduleRange.tuple_dim(); 654 isl::set LoopPrefixes = 655 ScheduleRange.drop_constraints_involving_dims(isl::dim::set, Dims - 1, 1); 656 auto ExtentPrefixes = addExtentConstraints(LoopPrefixes, VectorWidth); 657 isl::set BadPrefixes = ExtentPrefixes.subtract(ScheduleRange); 658 BadPrefixes = BadPrefixes.project_out(isl::dim::set, Dims - 1, 1); 659 LoopPrefixes = LoopPrefixes.project_out(isl::dim::set, Dims - 1, 1); 660 return LoopPrefixes.subtract(BadPrefixes); 661 } 662 663 isl::union_set polly::getIsolateOptions(isl::set IsolateDomain, 664 isl_size OutDimsNum) { 665 isl_size Dims = IsolateDomain.tuple_dim(); 666 assert(OutDimsNum <= Dims && 667 "The isl::set IsolateDomain is used to describe the range of schedule " 668 "dimensions values, which should be isolated. Consequently, the " 669 "number of its dimensions should be greater than or equal to the " 670 "number of the schedule dimensions."); 671 isl::map IsolateRelation = isl::map::from_domain(IsolateDomain); 672 IsolateRelation = IsolateRelation.move_dims(isl::dim::out, 0, isl::dim::in, 673 Dims - OutDimsNum, OutDimsNum); 674 isl::set IsolateOption = IsolateRelation.wrap(); 675 isl::id Id = isl::id::alloc(IsolateOption.ctx(), "isolate", nullptr); 676 IsolateOption = IsolateOption.set_tuple_id(Id); 677 return isl::union_set(IsolateOption); 678 } 679 680 isl::union_set polly::getDimOptions(isl::ctx Ctx, const char *Option) { 681 isl::space Space(Ctx, 0, 1); 682 auto DimOption = isl::set::universe(Space); 683 auto Id = isl::id::alloc(Ctx, Option, nullptr); 684 DimOption = DimOption.set_tuple_id(Id); 685 return isl::union_set(DimOption); 686 } 687 688 isl::schedule_node polly::tileNode(isl::schedule_node Node, 689 const char *Identifier, 690 ArrayRef<int> TileSizes, 691 int DefaultTileSize) { 692 auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get())); 693 auto Dims = Space.dim(isl::dim::set); 694 auto Sizes = isl::multi_val::zero(Space); 695 std::string IdentifierString(Identifier); 696 for (auto i : seq<isl_size>(0, Dims)) { 697 auto tileSize = 698 i < (isl_size)TileSizes.size() ? TileSizes[i] : DefaultTileSize; 699 Sizes = Sizes.set_val(i, isl::val(Node.ctx(), tileSize)); 700 } 701 auto TileLoopMarkerStr = IdentifierString + " - Tiles"; 702 auto TileLoopMarker = isl::id::alloc(Node.ctx(), TileLoopMarkerStr, nullptr); 703 Node = Node.insert_mark(TileLoopMarker); 704 Node = Node.child(0); 705 Node = 706 isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release())); 707 Node = Node.child(0); 708 auto PointLoopMarkerStr = IdentifierString + " - Points"; 709 auto PointLoopMarker = 710 isl::id::alloc(Node.ctx(), PointLoopMarkerStr, nullptr); 711 Node = Node.insert_mark(PointLoopMarker); 712 return Node.child(0); 713 } 714 715 isl::schedule_node polly::applyRegisterTiling(isl::schedule_node Node, 716 ArrayRef<int> TileSizes, 717 int DefaultTileSize) { 718 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize); 719 auto Ctx = Node.ctx(); 720 return Node.band_set_ast_build_options(isl::union_set(Ctx, "{unroll[x]}")); 721 } 722