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