1 //===- SparseBufferRewriting.cpp - Sparse buffer rewriting rules ----------===// 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 // This file implements rewriting rules that are specific to sparse tensor 10 // primitives with memref operands. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodegenUtils.h" 15 16 #include "mlir/Dialect/Arith/IR/Arith.h" 17 #include "mlir/Dialect/Func/IR/FuncOps.h" 18 #include "mlir/Dialect/Linalg/IR/Linalg.h" 19 #include "mlir/Dialect/Math/IR/Math.h" 20 #include "mlir/Dialect/MemRef/IR/MemRef.h" 21 #include "mlir/Dialect/SCF/IR/SCF.h" 22 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" 23 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" 24 #include "mlir/Support/LLVM.h" 25 26 using namespace mlir; 27 using namespace mlir::sparse_tensor; 28 29 //===---------------------------------------------------------------------===// 30 // Helper methods for the actual rewriting rules. 31 //===---------------------------------------------------------------------===// 32 33 static constexpr uint64_t loIdx = 0; 34 static constexpr uint64_t hiIdx = 1; 35 static constexpr uint64_t xStartIdx = 2; 36 37 static constexpr const char kPartitionFuncNamePrefix[] = "_sparse_partition_"; 38 static constexpr const char kBinarySearchFuncNamePrefix[] = 39 "_sparse_binary_search_"; 40 static constexpr const char kHybridQuickSortFuncNamePrefix[] = 41 "_sparse_hybrid_qsort_"; 42 static constexpr const char kSortStableFuncNamePrefix[] = 43 "_sparse_sort_stable_"; 44 static constexpr const char kShiftDownFuncNamePrefix[] = "_sparse_shift_down_"; 45 static constexpr const char kHeapSortFuncNamePrefix[] = "_sparse_heap_sort_"; 46 static constexpr const char kQuickSortFuncNamePrefix[] = "_sparse_qsort_"; 47 48 using FuncGeneratorType = function_ref<void( 49 OpBuilder &, ModuleOp, func::FuncOp, uint64_t, uint64_t, bool, uint32_t)>; 50 51 /// Constructs a function name with this format to facilitate quick sort: 52 /// <namePrefix><nx>_<x type>_<y0 type>..._<yn type> for sort 53 /// <namePrefix><nx>_<x type>_coo_<ny>_<y0 type>..._<yn type> for sort_coo 54 static void getMangledSortHelperFuncName(llvm::raw_svector_ostream &nameOstream, 55 StringRef namePrefix, uint64_t nx, 56 uint64_t ny, bool isCoo, 57 ValueRange operands) { 58 nameOstream << namePrefix << nx << "_" 59 << getMemRefType(operands[xStartIdx]).getElementType(); 60 61 if (isCoo) 62 nameOstream << "_coo_" << ny; 63 64 uint64_t yBufferOffset = isCoo ? 1 : nx; 65 for (Value v : operands.drop_front(xStartIdx + yBufferOffset)) 66 nameOstream << "_" << getMemRefType(v).getElementType(); 67 } 68 69 /// Looks up a function that is appropriate for the given operands being 70 /// sorted, and creates such a function if it doesn't exist yet. The 71 /// parameters `nx` and `ny` tell the number of x and y values provided 72 /// by the buffer in xStartIdx, and `isCoo` indicates whether the instruction 73 /// being processed is a sparse_tensor.sort or sparse_tensor.sort_coo. 74 // 75 // All sorting function generators take (lo, hi, xs, ys) in `operands` as 76 // parameters for the sorting functions. Other parameters, such as the recursive 77 // call depth, are appended to the end of the parameter list as 78 // "trailing parameters". 79 static FlatSymbolRefAttr 80 getMangledSortHelperFunc(OpBuilder &builder, func::FuncOp insertPoint, 81 TypeRange resultTypes, StringRef namePrefix, 82 uint64_t nx, uint64_t ny, bool isCoo, 83 ValueRange operands, FuncGeneratorType createFunc, 84 uint32_t nTrailingP = 0) { 85 SmallString<32> nameBuffer; 86 llvm::raw_svector_ostream nameOstream(nameBuffer); 87 getMangledSortHelperFuncName(nameOstream, namePrefix, nx, ny, isCoo, 88 operands.drop_back(nTrailingP)); 89 90 ModuleOp module = insertPoint->getParentOfType<ModuleOp>(); 91 MLIRContext *context = module.getContext(); 92 auto result = SymbolRefAttr::get(context, nameOstream.str()); 93 auto func = module.lookupSymbol<func::FuncOp>(result.getAttr()); 94 95 if (!func) { 96 // Create the function. 97 OpBuilder::InsertionGuard insertionGuard(builder); 98 builder.setInsertionPoint(insertPoint); 99 Location loc = insertPoint.getLoc(); 100 func = builder.create<func::FuncOp>( 101 loc, nameOstream.str(), 102 FunctionType::get(context, operands.getTypes(), resultTypes)); 103 func.setPrivate(); 104 createFunc(builder, module, func, nx, ny, isCoo, nTrailingP); 105 } 106 107 return result; 108 } 109 110 /// Creates a code block to process each pair of (xs[i], xs[j]) for sorting. 111 /// The code to process the value pairs is generated by `bodyBuilder`. 112 static void forEachIJPairInXs( 113 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 114 bool isCoo, function_ref<void(uint64_t, Value, Value, Value)> bodyBuilder) { 115 Value iOffset, jOffset; 116 if (isCoo) { 117 Value cstep = constantIndex(builder, loc, nx + ny); 118 iOffset = builder.create<arith::MulIOp>(loc, args[0], cstep); 119 jOffset = builder.create<arith::MulIOp>(loc, args[1], cstep); 120 } 121 for (uint64_t k = 0; k < nx; k++) { 122 scf::IfOp ifOp; 123 Value i, j, buffer; 124 if (isCoo) { 125 Value ck = constantIndex(builder, loc, k); 126 i = builder.create<arith::AddIOp>(loc, ck, iOffset); 127 j = builder.create<arith::AddIOp>(loc, ck, jOffset); 128 buffer = args[xStartIdx]; 129 } else { 130 i = args[0]; 131 j = args[1]; 132 buffer = args[xStartIdx + k]; 133 } 134 bodyBuilder(k, i, j, buffer); 135 } 136 } 137 138 /// Creates a code block to process each pair of (xys[i], xys[j]) for sorting. 139 /// The code to process the value pairs is generated by `bodyBuilder`. 140 static void forEachIJPairInAllBuffers( 141 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 142 bool isCoo, function_ref<void(uint64_t, Value, Value, Value)> bodyBuilder) { 143 144 // Create code for the first (nx + ny) buffers. When isCoo==true, these 145 // logical buffers are all from the xy buffer of the sort_coo operator. 146 forEachIJPairInXs(builder, loc, args, nx + ny, 0, isCoo, bodyBuilder); 147 148 uint64_t numHandledBuffers = isCoo ? 1 : nx + ny; 149 150 // Create code for the remaining buffers. 151 Value i = args[0]; 152 Value j = args[1]; 153 for (const auto &arg : 154 llvm::enumerate(args.drop_front(xStartIdx + numHandledBuffers))) { 155 bodyBuilder(arg.index() + nx + ny, i, j, arg.value()); 156 } 157 } 158 159 /// Creates a code block for swapping the values in index i and j for all the 160 /// buffers. 161 // 162 // The generated IR corresponds to this C like algorithm: 163 // swap(x0[i], x0[j]); 164 // swap(x1[i], x1[j]); 165 // ... 166 // swap(xn[i], xn[j]); 167 // swap(y0[i], y0[j]); 168 // ... 169 // swap(yn[i], yn[j]); 170 static void createSwap(OpBuilder &builder, Location loc, ValueRange args, 171 uint64_t nx, uint64_t ny, bool isCoo) { 172 auto swapOnePair = [&](uint64_t unused, Value i, Value j, Value buffer) { 173 Value vi = builder.create<memref::LoadOp>(loc, buffer, i); 174 Value vj = builder.create<memref::LoadOp>(loc, buffer, j); 175 builder.create<memref::StoreOp>(loc, vj, buffer, i); 176 builder.create<memref::StoreOp>(loc, vi, buffer, j); 177 }; 178 179 forEachIJPairInAllBuffers(builder, loc, args, nx, ny, isCoo, swapOnePair); 180 } 181 182 /// Creates code to compare all the (xs[i], xs[j]) pairs. The method to compare 183 /// each pair is create via `compareBuilder`. 184 static Value createInlinedCompareImplementation( 185 OpBuilder &builder, Location loc, ValueRange args, uint64_t nx, uint64_t ny, 186 bool isCoo, 187 function_ref<Value(OpBuilder &, Location, Value, Value, Value, bool, bool)> 188 compareBuilder) { 189 Value result; 190 auto bodyBuilder = [&](uint64_t k, Value i, Value j, Value buffer) { 191 bool isFirstDim = (k == 0); 192 bool isLastDim = (k == nx - 1); 193 Value val = 194 compareBuilder(builder, loc, i, j, buffer, isFirstDim, isLastDim); 195 if (isFirstDim) { 196 result = val; 197 } else if (!isLastDim) { 198 OpBuilder::InsertionGuard insertionGuard(builder); 199 auto ifOp = cast<scf::IfOp>(val.getDefiningOp()); 200 builder.setInsertionPointAfter(ifOp); 201 builder.create<scf::YieldOp>(loc, ifOp.getResult(0)); 202 } 203 }; 204 205 forEachIJPairInXs(builder, loc, args, nx, ny, isCoo, bodyBuilder); 206 207 builder.setInsertionPointAfterValue(result); 208 return result; 209 } 210 211 /// Generates code to compare whether x[i] is equal to x[j] and returns the 212 /// result of the comparison. 213 static Value createEqCompare(OpBuilder &builder, Location loc, Value i, Value j, 214 Value x, bool isFirstDim, bool isLastDim) { 215 Value vi = builder.create<memref::LoadOp>(loc, x, i); 216 Value vj = builder.create<memref::LoadOp>(loc, x, j); 217 218 Value res; 219 if (isLastDim) { 220 res = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, vi, vj); 221 // For 1D, we create a compare without any control flow. Otherwise, we 222 // create YieldOp to return the result in the nested if-stmt. 223 if (!isFirstDim) 224 builder.create<scf::YieldOp>(loc, res); 225 } else { 226 Value ne = 227 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, vi, vj); 228 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, builder.getIntegerType(1), 229 ne, /*else=*/true); 230 // If (x[i] != x[j]). 231 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 232 Value f = constantI1(builder, loc, false); 233 builder.create<scf::YieldOp>(loc, f); 234 235 // If (x[i] == x[j]). Set up the insertion point for the nested if-stmt that 236 // checks the remaining dimensions. 237 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 238 res = ifOp.getResult(0); 239 } 240 241 return res; 242 } 243 244 /// Creates code to compare whether xs[i] is equal to xs[j]. 245 // 246 // The generate IR corresponds to this C like algorithm: 247 // if (x0[i] != x0[j]) 248 // return false; 249 // else 250 // if (x1[i] != x1[j]) 251 // return false; 252 // else if (x2[2] != x2[j])) 253 // and so on ... 254 static Value createInlinedEqCompare(OpBuilder &builder, Location loc, 255 ValueRange args, uint64_t nx, uint64_t ny, 256 bool isCoo, uint32_t nTrailingP = 0) { 257 // Compare functions don't use trailing parameters. 258 (void)nTrailingP; 259 assert(nTrailingP == 0); 260 return createInlinedCompareImplementation(builder, loc, args, nx, ny, isCoo, 261 createEqCompare); 262 } 263 264 /// Generates code to compare whether x[i] is less than x[j] and returns the 265 /// result of the comparison. 266 static Value createLessThanCompare(OpBuilder &builder, Location loc, Value i, 267 Value j, Value x, bool isFirstDim, 268 bool isLastDim) { 269 Value vi = builder.create<memref::LoadOp>(loc, x, i); 270 Value vj = builder.create<memref::LoadOp>(loc, x, j); 271 272 Value res; 273 if (isLastDim) { 274 res = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, vi, vj); 275 // For 1D, we create a compare without any control flow. Otherwise, we 276 // create YieldOp to return the result in the nested if-stmt. 277 if (!isFirstDim) 278 builder.create<scf::YieldOp>(loc, res); 279 } else { 280 Value ne = 281 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, vi, vj); 282 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, builder.getIntegerType(1), 283 ne, /*else=*/true); 284 // If (x[i] != x[j]). 285 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 286 Value lt = 287 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, vi, vj); 288 builder.create<scf::YieldOp>(loc, lt); 289 290 // If (x[i] == x[j]). Set up the insertion point for the nested if-stmt that 291 // checks the remaining dimensions. 292 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 293 res = ifOp.getResult(0); 294 } 295 296 return res; 297 } 298 299 /// Creates code to compare whether xs[i] is less than xs[j]. 300 // 301 // The generate IR corresponds to this C like algorithm: 302 // if (x0[i] != x0[j]) 303 // return x0[i] < x0[j]; 304 // else if (x1[j] != x1[i]) 305 // return x1[i] < x1[j]; 306 // else 307 // and so on ... 308 static Value createInlinedLessThan(OpBuilder &builder, Location loc, 309 ValueRange args, uint64_t nx, uint64_t ny, 310 bool isCoo, uint32_t nTrailingP = 0) { 311 // Compare functions don't use trailing parameters. 312 (void)nTrailingP; 313 assert(nTrailingP == 0); 314 return createInlinedCompareImplementation(builder, loc, args, nx, ny, isCoo, 315 createLessThanCompare); 316 } 317 318 /// Creates a function to use a binary search to find the insertion point for 319 /// inserting xs[hi] to the sorted values xs[lo..hi). 320 // 321 // The generate IR corresponds to this C like algorithm: 322 // p = hi 323 // while (lo < hi) 324 // mid = (lo + hi) >> 1 325 // if (xs[p] < xs[mid]) 326 // hi = mid 327 // else 328 // lo = mid - 1 329 // return lo; 330 // 331 static void createBinarySearchFunc(OpBuilder &builder, ModuleOp module, 332 func::FuncOp func, uint64_t nx, uint64_t ny, 333 bool isCoo, uint32_t nTrailingP = 0) { 334 // Binary search doesn't use trailing parameters. 335 (void)nTrailingP; 336 assert(nTrailingP == 0); 337 OpBuilder::InsertionGuard insertionGuard(builder); 338 Block *entryBlock = func.addEntryBlock(); 339 builder.setInsertionPointToStart(entryBlock); 340 341 Location loc = func.getLoc(); 342 ValueRange args = entryBlock->getArguments(); 343 Value p = args[hiIdx]; 344 SmallVector<Type, 2> types(2, p.getType()); // Only two types. 345 scf::WhileOp whileOp = builder.create<scf::WhileOp>( 346 loc, types, SmallVector<Value, 2>{args[loIdx], args[hiIdx]}); 347 348 // The before-region of the WhileOp. 349 Block *before = 350 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc}); 351 builder.setInsertionPointToEnd(before); 352 Value cond1 = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 353 before->getArgument(0), 354 before->getArgument(1)); 355 builder.create<scf::ConditionOp>(loc, cond1, before->getArguments()); 356 357 // The after-region of the WhileOp. 358 Block *after = 359 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc}); 360 builder.setInsertionPointToEnd(after); 361 Value lo = after->getArgument(0); 362 Value hi = after->getArgument(1); 363 // Compute mid = (lo + hi) >> 1. 364 Value c1 = constantIndex(builder, loc, 1); 365 Value mid = builder.create<arith::ShRUIOp>( 366 loc, builder.create<arith::AddIOp>(loc, lo, hi), c1); 367 Value midp1 = builder.create<arith::AddIOp>(loc, mid, c1); 368 369 // Compare xs[p] < xs[mid]. 370 SmallVector<Value> compareOperands{p, mid}; 371 uint64_t numXBuffers = isCoo ? 1 : nx; 372 compareOperands.append(args.begin() + xStartIdx, 373 args.begin() + xStartIdx + numXBuffers); 374 Value cond2 = 375 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 376 // Update lo and hi for the WhileOp as follows: 377 // if (xs[p] < xs[mid])) 378 // hi = mid; 379 // else 380 // lo = mid + 1; 381 Value newLo = builder.create<arith::SelectOp>(loc, cond2, lo, midp1); 382 Value newHi = builder.create<arith::SelectOp>(loc, cond2, mid, hi); 383 builder.create<scf::YieldOp>(loc, ValueRange{newLo, newHi}); 384 385 builder.setInsertionPointAfter(whileOp); 386 builder.create<func::ReturnOp>(loc, whileOp.getResult(0)); 387 } 388 389 /// Creates code to advance i in a loop based on xs[p] as follows: 390 /// while (xs[i] < xs[p]) i += step (step > 0) 391 /// or 392 /// while (xs[i] > xs[p]) i += step (step < 0) 393 /// The routine returns i as well as a boolean value to indicate whether 394 /// xs[i] == xs[p]. 395 static std::pair<Value, Value> 396 createScanLoop(OpBuilder &builder, ModuleOp module, func::FuncOp func, 397 ValueRange xs, Value i, Value p, uint64_t nx, uint64_t ny, 398 bool isCoo, int step) { 399 Location loc = func.getLoc(); 400 scf::WhileOp whileOp = 401 builder.create<scf::WhileOp>(loc, TypeRange{i.getType()}, ValueRange{i}); 402 403 Block *before = 404 builder.createBlock(&whileOp.getBefore(), {}, {i.getType()}, {loc}); 405 builder.setInsertionPointToEnd(before); 406 SmallVector<Value> compareOperands; 407 if (step > 0) { 408 compareOperands.push_back(before->getArgument(0)); 409 compareOperands.push_back(p); 410 } else { 411 assert(step < 0); 412 compareOperands.push_back(p); 413 compareOperands.push_back(before->getArgument(0)); 414 } 415 compareOperands.append(xs.begin(), xs.end()); 416 Value cond = 417 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 418 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 419 420 Block *after = 421 builder.createBlock(&whileOp.getAfter(), {}, {i.getType()}, {loc}); 422 builder.setInsertionPointToEnd(after); 423 Value cs = constantIndex(builder, loc, step); 424 i = builder.create<arith::AddIOp>(loc, after->getArgument(0), cs); 425 builder.create<scf::YieldOp>(loc, ValueRange{i}); 426 i = whileOp.getResult(0); 427 428 builder.setInsertionPointAfter(whileOp); 429 compareOperands[0] = i; 430 compareOperands[1] = p; 431 Value compareEq = 432 createInlinedEqCompare(builder, loc, compareOperands, nx, ny, isCoo); 433 434 return std::make_pair(whileOp.getResult(0), compareEq); 435 } 436 437 /// Creates a code block to swap the values so that data[mi] is the median among 438 /// data[lo], data[hi], and data[mi]. 439 // The generated code corresponds to this C-like algorithm: 440 // median = mi 441 // if (data[mi] < data[lo]). (if1) 442 // if (data[hi] < data[lo]) (if2) 443 // median = data[hi] < data[mi] ? mi : hi 444 // else 445 // median = lo 446 // else 447 // if data[hi] < data[mi] (if3) 448 // median = data[hi] < data[lo] ? lo : hi 449 // if median != mi swap data[median] with data[mi] 450 static void createChoosePivot(OpBuilder &builder, ModuleOp module, 451 func::FuncOp func, uint64_t nx, uint64_t ny, 452 bool isCoo, Value lo, Value hi, Value mi, 453 ValueRange args) { 454 SmallVector<Value> compareOperands{mi, lo}; 455 uint64_t numXBuffers = isCoo ? 1 : nx; 456 compareOperands.append(args.begin() + xStartIdx, 457 args.begin() + xStartIdx + numXBuffers); 458 Type i1Type = IntegerType::get(module.getContext(), 1, IntegerType::Signless); 459 SmallVector<Type, 1> cmpTypes{i1Type}; 460 Location loc = func.getLoc(); 461 // Compare data[mi] < data[lo]. 462 Value cond1 = 463 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 464 SmallVector<Type, 1> ifTypes{lo.getType()}; 465 scf::IfOp ifOp1 = 466 builder.create<scf::IfOp>(loc, ifTypes, cond1, /*else=*/true); 467 468 // Generate an if-stmt to find the median value, assuming we already know that 469 // data[b] < data[a] and we haven't compare data[c] yet. 470 auto createFindMedian = [&](Value a, Value b, Value c) -> scf::IfOp { 471 compareOperands[0] = c; 472 compareOperands[1] = a; 473 // Compare data[c] < data[b]. 474 Value cond2 = 475 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 476 scf::IfOp ifOp2 = 477 builder.create<scf::IfOp>(loc, ifTypes, cond2, /*else=*/true); 478 builder.setInsertionPointToStart(&ifOp2.getThenRegion().front()); 479 compareOperands[0] = c; 480 compareOperands[1] = b; 481 // Compare data[c] < data[b]. 482 Value cond3 = 483 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 484 builder.create<scf::YieldOp>( 485 loc, ValueRange{builder.create<arith::SelectOp>(loc, cond3, b, c)}); 486 builder.setInsertionPointToStart(&ifOp2.getElseRegion().front()); 487 builder.create<scf::YieldOp>(loc, ValueRange{a}); 488 return ifOp2; 489 }; 490 491 builder.setInsertionPointToStart(&ifOp1.getThenRegion().front()); 492 scf::IfOp ifOp2 = createFindMedian(lo, mi, hi); 493 builder.setInsertionPointAfter(ifOp2); 494 builder.create<scf::YieldOp>(loc, ValueRange{ifOp2.getResult(0)}); 495 496 builder.setInsertionPointToStart(&ifOp1.getElseRegion().front()); 497 scf::IfOp ifOp3 = createFindMedian(mi, lo, hi); 498 499 builder.setInsertionPointAfter(ifOp3); 500 builder.create<scf::YieldOp>(loc, ValueRange{ifOp3.getResult(0)}); 501 502 builder.setInsertionPointAfter(ifOp1); 503 Value median = ifOp1.getResult(0); 504 Value cond = 505 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, mi, median); 506 scf::IfOp ifOp = 507 builder.create<scf::IfOp>(loc, TypeRange(), cond, /*else=*/false); 508 509 SmallVector<Value> swapOperands{median, mi}; 510 swapOperands.append(args.begin() + xStartIdx, args.end()); 511 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 512 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 513 builder.setInsertionPointAfter(ifOp); 514 } 515 516 /// Creates a function to perform quick sort partition on the values in the 517 /// range of index [lo, hi), assuming lo < hi. 518 // 519 // The generated IR corresponds to this C like algorithm: 520 // int partition(lo, hi, xs) { 521 // p = (lo+hi)/2 // pivot index 522 // i = lo 523 // j = hi-1 524 // while (i < j) do { 525 // while (xs[i] < xs[p]) i ++; 526 // i_eq = (xs[i] == xs[p]); 527 // while (xs[j] > xs[p]) j --; 528 // j_eq = (xs[j] == xs[p]); 529 // if (i < j) { 530 // swap(xs[i], xs[j]) 531 // if (i == p) { 532 // p = j; 533 // } else if (j == p) { 534 // p = i; 535 // } 536 // if (i_eq && j_eq) { 537 // ++i; 538 // --j; 539 // } 540 // } 541 // } 542 // return p 543 // } 544 static void createPartitionFunc(OpBuilder &builder, ModuleOp module, 545 func::FuncOp func, uint64_t nx, uint64_t ny, 546 bool isCoo, uint32_t nTrailingP = 0) { 547 // Quick sort partition doesn't use trailing parameters. 548 (void)nTrailingP; 549 assert(nTrailingP == 0); 550 OpBuilder::InsertionGuard insertionGuard(builder); 551 552 Block *entryBlock = func.addEntryBlock(); 553 builder.setInsertionPointToStart(entryBlock); 554 555 Location loc = func.getLoc(); 556 ValueRange args = entryBlock->getArguments(); 557 Value lo = args[loIdx]; 558 Value hi = args[hiIdx]; 559 Value sum = builder.create<arith::AddIOp>(loc, lo, hi); 560 Value c1 = constantIndex(builder, loc, 1); 561 Value p = builder.create<arith::ShRUIOp>(loc, sum, c1); 562 563 Value i = lo; 564 Value j = builder.create<arith::SubIOp>(loc, hi, c1); 565 createChoosePivot(builder, module, func, nx, ny, isCoo, i, j, p, args); 566 SmallVector<Value, 3> operands{i, j, p}; // Exactly three values. 567 SmallVector<Type, 3> types{i.getType(), j.getType(), p.getType()}; 568 scf::WhileOp whileOp = builder.create<scf::WhileOp>(loc, types, operands); 569 570 // The before-region of the WhileOp. 571 Block *before = 572 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc, loc}); 573 builder.setInsertionPointToEnd(before); 574 Value cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 575 before->getArgument(0), 576 before->getArgument(1)); 577 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 578 579 // The after-region of the WhileOp. 580 Block *after = 581 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc, loc}); 582 builder.setInsertionPointToEnd(after); 583 i = after->getArgument(0); 584 j = after->getArgument(1); 585 p = after->getArgument(2); 586 587 uint64_t numXBuffers = isCoo ? 1 : nx; 588 auto [iresult, iCompareEq] = 589 createScanLoop(builder, module, func, args.slice(xStartIdx, numXBuffers), 590 i, p, nx, ny, isCoo, 1); 591 i = iresult; 592 auto [jresult, jCompareEq] = 593 createScanLoop(builder, module, func, args.slice(xStartIdx, numXBuffers), 594 j, p, nx, ny, isCoo, -1); 595 j = jresult; 596 597 // If i < j: 598 cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, i, j); 599 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, types, cond, /*else=*/true); 600 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 601 SmallVector<Value> swapOperands{i, j}; 602 swapOperands.append(args.begin() + xStartIdx, args.end()); 603 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 604 // If the pivot is moved, update p with the new pivot. 605 Value icond = 606 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, i, p); 607 scf::IfOp ifOpI = builder.create<scf::IfOp>(loc, TypeRange{p.getType()}, 608 icond, /*else=*/true); 609 builder.setInsertionPointToStart(&ifOpI.getThenRegion().front()); 610 builder.create<scf::YieldOp>(loc, ValueRange{j}); 611 builder.setInsertionPointToStart(&ifOpI.getElseRegion().front()); 612 Value jcond = 613 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, j, p); 614 scf::IfOp ifOpJ = builder.create<scf::IfOp>(loc, TypeRange{p.getType()}, 615 jcond, /*else=*/true); 616 builder.setInsertionPointToStart(&ifOpJ.getThenRegion().front()); 617 builder.create<scf::YieldOp>(loc, ValueRange{i}); 618 builder.setInsertionPointToStart(&ifOpJ.getElseRegion().front()); 619 builder.create<scf::YieldOp>(loc, ValueRange{p}); 620 builder.setInsertionPointAfter(ifOpJ); 621 builder.create<scf::YieldOp>(loc, ifOpJ.getResults()); 622 builder.setInsertionPointAfter(ifOpI); 623 Value compareEqIJ = 624 builder.create<arith::AndIOp>(loc, iCompareEq, jCompareEq); 625 scf::IfOp ifOp2 = builder.create<scf::IfOp>( 626 loc, TypeRange{i.getType(), j.getType()}, compareEqIJ, /*else=*/true); 627 builder.setInsertionPointToStart(&ifOp2.getThenRegion().front()); 628 Value i2 = builder.create<arith::AddIOp>(loc, i, c1); 629 Value j2 = builder.create<arith::SubIOp>(loc, j, c1); 630 builder.create<scf::YieldOp>(loc, ValueRange{i2, j2}); 631 builder.setInsertionPointToStart(&ifOp2.getElseRegion().front()); 632 builder.create<scf::YieldOp>(loc, ValueRange{i, j}); 633 builder.setInsertionPointAfter(ifOp2); 634 builder.create<scf::YieldOp>( 635 loc, 636 ValueRange{ifOp2.getResult(0), ifOp2.getResult(1), ifOpI.getResult(0)}); 637 638 // False branch for if i < j: 639 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 640 builder.create<scf::YieldOp>(loc, ValueRange{i, j, p}); 641 642 // Return for the whileOp. 643 builder.setInsertionPointAfter(ifOp); 644 builder.create<scf::YieldOp>(loc, ifOp.getResults()); 645 646 // Return for the function. 647 builder.setInsertionPointAfter(whileOp); 648 builder.create<func::ReturnOp>(loc, whileOp.getResult(2)); 649 } 650 651 /// Computes (n-2)/n, assuming n has index type. 652 static Value createSubTwoDividedByTwo(OpBuilder &builder, Location loc, 653 Value n) { 654 Value i2 = constantIndex(builder, loc, 2); 655 Value res = builder.create<arith::SubIOp>(loc, n, i2); 656 Value i1 = constantIndex(builder, loc, 1); 657 return builder.create<arith::ShRUIOp>(loc, res, i1); 658 } 659 660 /// Creates a function to heapify the subtree with root `start` within the full 661 /// binary tree in the range of index [first, first + n). 662 // 663 // The generated IR corresponds to this C like algorithm: 664 // void shiftDown(first, start, n, data) { 665 // if (n >= 2) { 666 // child = start - first 667 // if ((n-2)/2 >= child) { 668 // // Left child exists. 669 // child = child * 2 + 1 // Initialize the bigger child to left child. 670 // childIndex = child + first 671 // if (child+1 < n && data[childIndex] < data[childIndex+1]) 672 // // Right child exits and is bigger. 673 // childIndex++; child++; 674 // // Shift data[start] down to where it belongs in the subtree. 675 // while (data[start] < data[childIndex) { 676 // swap(data[start], data[childIndex]) 677 // start = childIndex 678 // if ((n - 2)/2 >= child) { 679 // // Left child exists. 680 // child = 2*child + 1 681 // childIndex = child + 1 682 // if (child + 1) < n && data[childIndex] < data[childIndex+1] 683 // childIndex++; child++; 684 // } 685 // } 686 // } 687 // } 688 // } 689 // 690 static void createShiftDownFunc(OpBuilder &builder, ModuleOp module, 691 func::FuncOp func, uint64_t nx, uint64_t ny, 692 bool isCoo, uint32_t nTrailingP) { 693 // The value n is passed in as a trailing parameter. 694 assert(nTrailingP == 1); 695 OpBuilder::InsertionGuard insertionGuard(builder); 696 Block *entryBlock = func.addEntryBlock(); 697 builder.setInsertionPointToStart(entryBlock); 698 699 Location loc = func.getLoc(); 700 Value n = entryBlock->getArguments().back(); 701 ValueRange args = entryBlock->getArguments().drop_back(); 702 Value first = args[loIdx]; 703 Value start = args[hiIdx]; 704 705 // If (n >= 2). 706 Value c2 = constantIndex(builder, loc, 2); 707 Value condN = 708 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, n, c2); 709 scf::IfOp ifN = builder.create<scf::IfOp>(loc, condN, /*else=*/false); 710 builder.setInsertionPointToStart(&ifN.getThenRegion().front()); 711 Value child = builder.create<arith::SubIOp>(loc, start, first); 712 713 // If ((n-2)/2 >= child). 714 Value t = createSubTwoDividedByTwo(builder, loc, n); 715 Value condNc = 716 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, t, child); 717 scf::IfOp ifNc = builder.create<scf::IfOp>(loc, condNc, /*else=*/false); 718 719 builder.setInsertionPointToStart(&ifNc.getThenRegion().front()); 720 Value c1 = constantIndex(builder, loc, 1); 721 SmallVector<Value> compareOperands{start, start}; 722 uint64_t numXBuffers = isCoo ? 1 : nx; 723 compareOperands.append(args.begin() + xStartIdx, 724 args.begin() + xStartIdx + numXBuffers); 725 726 // Generate code to inspect the children of 'r' and return the larger child 727 // as follows: 728 // child = r * 2 + 1 // Left child. 729 // childIndex = child + first 730 // if (child+1 < n && data[childIndex] < data[childIndex+1]) 731 // childIndex ++; child ++ // Right child is bigger. 732 auto getLargerChild = [&](Value r) -> std::pair<Value, Value> { 733 Value lChild = builder.create<arith::ShLIOp>(loc, r, c1); 734 lChild = builder.create<arith::AddIOp>(loc, lChild, c1); 735 Value lChildIdx = builder.create<arith::AddIOp>(loc, lChild, first); 736 Value rChild = builder.create<arith::AddIOp>(loc, lChild, c1); 737 Value cond1 = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 738 rChild, n); 739 SmallVector<Type, 2> ifTypes(2, r.getType()); 740 scf::IfOp if1 = 741 builder.create<scf::IfOp>(loc, ifTypes, cond1, /*else=*/true); 742 builder.setInsertionPointToStart(&if1.getThenRegion().front()); 743 Value rChildIdx = builder.create<arith::AddIOp>(loc, rChild, first); 744 // Compare data[left] < data[right]. 745 compareOperands[0] = lChildIdx; 746 compareOperands[1] = rChildIdx; 747 Value cond2 = 748 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 749 scf::IfOp if2 = 750 builder.create<scf::IfOp>(loc, ifTypes, cond2, /*else=*/true); 751 builder.setInsertionPointToStart(&if2.getThenRegion().front()); 752 builder.create<scf::YieldOp>(loc, ValueRange{rChild, rChildIdx}); 753 builder.setInsertionPointToStart(&if2.getElseRegion().front()); 754 builder.create<scf::YieldOp>(loc, ValueRange{lChild, lChildIdx}); 755 builder.setInsertionPointAfter(if2); 756 builder.create<scf::YieldOp>(loc, if2.getResults()); 757 builder.setInsertionPointToStart(&if1.getElseRegion().front()); 758 builder.create<scf::YieldOp>(loc, ValueRange{lChild, lChildIdx}); 759 builder.setInsertionPointAfter(if1); 760 return std::make_pair(if1.getResult(0), if1.getResult(1)); 761 }; 762 763 Value childIdx; 764 std::tie(child, childIdx) = getLargerChild(child); 765 766 // While (data[start] < data[childIndex]). 767 SmallVector<Type, 3> types(3, child.getType()); 768 scf::WhileOp whileOp = builder.create<scf::WhileOp>( 769 loc, types, SmallVector<Value, 2>{start, child, childIdx}); 770 771 // The before-region of the WhileOp. 772 SmallVector<Location, 3> locs(3, loc); 773 Block *before = builder.createBlock(&whileOp.getBefore(), {}, types, locs); 774 builder.setInsertionPointToEnd(before); 775 start = before->getArgument(0); 776 childIdx = before->getArgument(2); 777 compareOperands[0] = start; 778 compareOperands[1] = childIdx; 779 Value cond = 780 createInlinedLessThan(builder, loc, compareOperands, nx, ny, isCoo); 781 builder.create<scf::ConditionOp>(loc, cond, before->getArguments()); 782 783 // The after-region of the WhileOp. 784 Block *after = builder.createBlock(&whileOp.getAfter(), {}, types, locs); 785 start = after->getArgument(0); 786 child = after->getArgument(1); 787 childIdx = after->getArgument(2); 788 SmallVector<Value> swapOperands{start, childIdx}; 789 swapOperands.append(args.begin() + xStartIdx, args.end()); 790 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 791 start = childIdx; 792 Value cond2 = 793 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::uge, t, child); 794 scf::IfOp if2 = builder.create<scf::IfOp>( 795 loc, TypeRange{child.getType(), child.getType()}, cond2, /*else=*/true); 796 builder.setInsertionPointToStart(&if2.getThenRegion().front()); 797 auto [newChild, newChildIdx] = getLargerChild(child); 798 builder.create<scf::YieldOp>(loc, ValueRange{newChild, newChildIdx}); 799 builder.setInsertionPointToStart(&if2.getElseRegion().front()); 800 builder.create<scf::YieldOp>(loc, ValueRange{child, childIdx}); 801 builder.setInsertionPointAfter(if2); 802 builder.create<scf::YieldOp>( 803 loc, ValueRange{start, if2.getResult(0), if2.getResult(1)}); 804 805 builder.setInsertionPointAfter(ifN); 806 builder.create<func::ReturnOp>(loc); 807 } 808 809 /// Creates a function to perform heap sort on the values in the range of index 810 /// [lo, hi) with the assumption hi - lo >= 2. 811 // 812 // The generate IR corresponds to this C like algorithm: 813 // void heapSort(lo, hi, data) { 814 // n = hi - lo 815 // for i = (n-2)/2 downto 0 816 // shiftDown(lo, lo+i, n) 817 // 818 // for l = n downto 2 819 // swap(lo, lo+l-1) 820 // shiftdown(lo, lo, l-1) 821 // } 822 static void createHeapSortFunc(OpBuilder &builder, ModuleOp module, 823 func::FuncOp func, uint64_t nx, uint64_t ny, 824 bool isCoo, uint32_t nTrailingP) { 825 // Heap sort function doesn't have trailing parameters. 826 (void)nTrailingP; 827 assert(nTrailingP == 0); 828 OpBuilder::InsertionGuard insertionGuard(builder); 829 Block *entryBlock = func.addEntryBlock(); 830 builder.setInsertionPointToStart(entryBlock); 831 832 Location loc = func.getLoc(); 833 ValueRange args = entryBlock->getArguments(); 834 Value lo = args[loIdx]; 835 Value hi = args[hiIdx]; 836 Value n = builder.create<arith::SubIOp>(loc, hi, lo); 837 838 // For i = (n-2)/2 downto 0. 839 Value c0 = constantIndex(builder, loc, 0); 840 Value c1 = constantIndex(builder, loc, 1); 841 Value s = createSubTwoDividedByTwo(builder, loc, n); 842 Value up = builder.create<arith::AddIOp>(loc, s, c1); 843 scf::ForOp forI = builder.create<scf::ForOp>(loc, c0, up, c1); 844 builder.setInsertionPointToStart(forI.getBody()); 845 Value i = builder.create<arith::SubIOp>(loc, s, forI.getInductionVar()); 846 Value lopi = builder.create<arith::AddIOp>(loc, lo, i); 847 SmallVector<Value> shiftDownOperands = {lo, lopi}; 848 shiftDownOperands.append(args.begin() + xStartIdx, args.end()); 849 shiftDownOperands.push_back(n); 850 FlatSymbolRefAttr shiftDownFunc = getMangledSortHelperFunc( 851 builder, func, TypeRange(), kShiftDownFuncNamePrefix, nx, ny, isCoo, 852 shiftDownOperands, createShiftDownFunc, /*nTrailingP=*/1); 853 builder.create<func::CallOp>(loc, shiftDownFunc, TypeRange(), 854 shiftDownOperands); 855 856 builder.setInsertionPointAfter(forI); 857 // For l = n downto 2. 858 up = builder.create<arith::SubIOp>(loc, n, c1); 859 scf::ForOp forL = builder.create<scf::ForOp>(loc, c0, up, c1); 860 builder.setInsertionPointToStart(forL.getBody()); 861 Value l = builder.create<arith::SubIOp>(loc, n, forL.getInductionVar()); 862 Value loplm1 = builder.create<arith::AddIOp>(loc, lo, l); 863 loplm1 = builder.create<arith::SubIOp>(loc, loplm1, c1); 864 SmallVector<Value> swapOperands{lo, loplm1}; 865 swapOperands.append(args.begin() + xStartIdx, args.end()); 866 createSwap(builder, loc, swapOperands, nx, ny, isCoo); 867 shiftDownOperands[1] = lo; 868 shiftDownOperands[shiftDownOperands.size() - 1] = 869 builder.create<arith::SubIOp>(loc, l, c1); 870 builder.create<func::CallOp>(loc, shiftDownFunc, TypeRange(), 871 shiftDownOperands); 872 873 builder.setInsertionPointAfter(forL); 874 builder.create<func::ReturnOp>(loc); 875 } 876 877 /// A helper for generating code to perform quick sort. It partitions [lo, hi), 878 /// recursively calls quick sort to process the smaller partition and returns 879 /// the bigger partition to be processed by the enclosed while-loop. 880 static std::pair<Value, Value> 881 createQuickSort(OpBuilder &builder, ModuleOp module, func::FuncOp func, 882 ValueRange args, uint64_t nx, uint64_t ny, bool isCoo, 883 uint32_t nTrailingP) { 884 MLIRContext *context = module.getContext(); 885 Location loc = func.getLoc(); 886 Value lo = args[loIdx]; 887 Value hi = args[hiIdx]; 888 FlatSymbolRefAttr partitionFunc = getMangledSortHelperFunc( 889 builder, func, {IndexType::get(context)}, kPartitionFuncNamePrefix, nx, 890 ny, isCoo, args.drop_back(nTrailingP), createPartitionFunc); 891 Value p = builder 892 .create<func::CallOp>(loc, partitionFunc, 893 TypeRange{IndexType::get(context)}, 894 args.drop_back(nTrailingP)) 895 .getResult(0); 896 Value pP1 = 897 builder.create<arith::AddIOp>(loc, p, constantIndex(builder, loc, 1)); 898 Value lenLow = builder.create<arith::SubIOp>(loc, p, lo); 899 Value lenHigh = builder.create<arith::SubIOp>(loc, hi, p); 900 Value cond = builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule, 901 lenLow, lenHigh); 902 903 SmallVector<Type, 2> types(2, lo.getType()); // Only two types. 904 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, types, cond, /*else=*/true); 905 906 Value c0 = constantIndex(builder, loc, 0); 907 auto mayRecursion = [&](Value low, Value high, Value len) { 908 Value cond = 909 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, len, c0); 910 scf::IfOp ifOp = builder.create<scf::IfOp>(loc, cond, /*else=*/false); 911 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 912 SmallVector<Value> operands{low, high}; 913 operands.append(args.begin() + xStartIdx, args.end()); 914 builder.create<func::CallOp>(loc, func, operands); 915 builder.setInsertionPointAfter(ifOp); 916 }; 917 918 // Recursively call quickSort to process the smaller partition and return 919 // the bigger partition to be processed by the enclosed while-loop. 920 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 921 mayRecursion(lo, p, lenLow); 922 builder.create<scf::YieldOp>(loc, ValueRange{pP1, hi}); 923 924 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 925 mayRecursion(pP1, hi, lenHigh); 926 builder.create<scf::YieldOp>(loc, ValueRange{lo, p}); 927 928 builder.setInsertionPointAfter(ifOp); 929 return std::make_pair(ifOp.getResult(0), ifOp.getResult(1)); 930 } 931 932 /// Creates a function to perform insertion sort on the values in the range of 933 /// index [lo, hi). 934 // 935 // The generate IR corresponds to this C like algorithm: 936 // void insertionSort(lo, hi, data) { 937 // for (i = lo+1; i < hi; i++) { 938 // d = data[i]; 939 // p = binarySearch(lo, i-1, data) 940 // for (j = 0; j > i - p; j++) 941 // data[i-j] = data[i-j-1] 942 // data[p] = d 943 // } 944 // } 945 static void createSortStableFunc(OpBuilder &builder, ModuleOp module, 946 func::FuncOp func, uint64_t nx, uint64_t ny, 947 bool isCoo, uint32_t nTrailingP) { 948 // Stable sort function doesn't use trailing parameters. 949 (void)nTrailingP; 950 assert(nTrailingP == 0); 951 OpBuilder::InsertionGuard insertionGuard(builder); 952 Block *entryBlock = func.addEntryBlock(); 953 builder.setInsertionPointToStart(entryBlock); 954 955 MLIRContext *context = module.getContext(); 956 Location loc = func.getLoc(); 957 ValueRange args = entryBlock->getArguments(); 958 Value c1 = constantIndex(builder, loc, 1); 959 Value lo = args[loIdx]; 960 Value hi = args[hiIdx]; 961 Value lop1 = builder.create<arith::AddIOp>(loc, lo, c1); 962 963 // Start the outer for-stmt with induction variable i. 964 scf::ForOp forOpI = builder.create<scf::ForOp>(loc, lop1, hi, c1); 965 builder.setInsertionPointToStart(forOpI.getBody()); 966 Value i = forOpI.getInductionVar(); 967 968 // Binary search to find the insertion point p. 969 SmallVector<Value> operands{lo, i}; 970 operands.append(args.begin() + xStartIdx, args.end()); 971 FlatSymbolRefAttr searchFunc = getMangledSortHelperFunc( 972 builder, func, {IndexType::get(context)}, kBinarySearchFuncNamePrefix, nx, 973 ny, isCoo, operands, createBinarySearchFunc); 974 Value p = builder 975 .create<func::CallOp>(loc, searchFunc, TypeRange{c1.getType()}, 976 operands) 977 .getResult(0); 978 979 // Move the value at data[i] to a temporary location. 980 operands[0] = operands[1] = i; 981 SmallVector<Value> d; 982 forEachIJPairInAllBuffers( 983 builder, loc, operands, nx, ny, isCoo, 984 [&](uint64_t unused, Value i, Value unused2, Value buffer) { 985 d.push_back(builder.create<memref::LoadOp>(loc, buffer, i)); 986 }); 987 988 // Start the inner for-stmt with induction variable j, for moving data[p..i) 989 // to data[p+1..i+1). 990 Value imp = builder.create<arith::SubIOp>(loc, i, p); 991 Value c0 = constantIndex(builder, loc, 0); 992 scf::ForOp forOpJ = builder.create<scf::ForOp>(loc, c0, imp, c1); 993 builder.setInsertionPointToStart(forOpJ.getBody()); 994 Value j = forOpJ.getInductionVar(); 995 Value imj = builder.create<arith::SubIOp>(loc, i, j); 996 operands[1] = imj; 997 operands[0] = builder.create<arith::SubIOp>(loc, imj, c1); 998 forEachIJPairInAllBuffers( 999 builder, loc, operands, nx, ny, isCoo, 1000 [&](uint64_t unused, Value imjm1, Value imj, Value buffer) { 1001 Value t = builder.create<memref::LoadOp>(loc, buffer, imjm1); 1002 builder.create<memref::StoreOp>(loc, t, buffer, imj); 1003 }); 1004 1005 // Store the value at data[i] to data[p]. 1006 builder.setInsertionPointAfter(forOpJ); 1007 operands[0] = operands[1] = p; 1008 forEachIJPairInAllBuffers( 1009 builder, loc, operands, nx, ny, isCoo, 1010 [&](uint64_t k, Value p, Value usused, Value buffer) { 1011 builder.create<memref::StoreOp>(loc, d[k], buffer, p); 1012 }); 1013 1014 builder.setInsertionPointAfter(forOpI); 1015 builder.create<func::ReturnOp>(loc); 1016 } 1017 1018 /// Creates a function to perform quick sort or a hybrid quick sort on the 1019 /// values in the range of index [lo, hi). 1020 // 1021 // 1022 // When nTrailingP == 0, the generated IR corresponds to this C like algorithm: 1023 // void quickSort(lo, hi, data) { 1024 // while (lo + 1 < hi) { 1025 // p = partition(low, high, data); 1026 // if (len(lo, p) < len(p+1, hi)) { 1027 // quickSort(lo, p, data); 1028 // lo = p+1; 1029 // } else { 1030 // quickSort(p + 1, hi, data); 1031 // hi = p; 1032 // } 1033 // } 1034 // } 1035 // 1036 // When nTrailingP == 1, the generated IR corresponds to this C like algorithm: 1037 // void hybridQuickSort(lo, hi, data, depthLimit) { 1038 // while (lo + 1 < hi) { 1039 // len = hi - lo; 1040 // if (len <= limit) { 1041 // insertionSort(lo, hi, data); 1042 // } else { 1043 // depthLimit --; 1044 // if (depthLimit <= 0) { 1045 // heapSort(lo, hi, data); 1046 // } else { 1047 // p = partition(low, high, data); 1048 // if (len(lo, p) < len(p+1, hi)) { 1049 // quickSort(lo, p, data, depthLimit); 1050 // lo = p+1; 1051 // } else { 1052 // quickSort(p + 1, hi, data, depthLimit); 1053 // hi = p; 1054 // } 1055 // } 1056 // } 1057 // } 1058 // } 1059 // 1060 static void createQuickSortFunc(OpBuilder &builder, ModuleOp module, 1061 func::FuncOp func, uint64_t nx, uint64_t ny, 1062 bool isCoo, uint32_t nTrailingP) { 1063 assert(nTrailingP == 1 || nTrailingP == 0); 1064 bool isHybrid = (nTrailingP == 1); 1065 OpBuilder::InsertionGuard insertionGuard(builder); 1066 Block *entryBlock = func.addEntryBlock(); 1067 builder.setInsertionPointToStart(entryBlock); 1068 1069 Location loc = func.getLoc(); 1070 SmallVector<Value> args; 1071 args.append(entryBlock->getArguments().begin(), 1072 entryBlock->getArguments().end()); 1073 Value lo = args[loIdx]; 1074 Value hi = args[hiIdx]; 1075 SmallVector<Type, 2> types(2, lo.getType()); // Only two types. 1076 scf::WhileOp whileOp = 1077 builder.create<scf::WhileOp>(loc, types, SmallVector<Value, 2>{lo, hi}); 1078 1079 // The before-region of the WhileOp. 1080 Block *before = 1081 builder.createBlock(&whileOp.getBefore(), {}, types, {loc, loc}); 1082 builder.setInsertionPointToEnd(before); 1083 lo = before->getArgument(0); 1084 hi = before->getArgument(1); 1085 Value loP1 = 1086 builder.create<arith::AddIOp>(loc, lo, constantIndex(builder, loc, 1)); 1087 Value needSort = 1088 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, loP1, hi); 1089 builder.create<scf::ConditionOp>(loc, needSort, before->getArguments()); 1090 1091 // The after-region of the WhileOp. 1092 Block *after = 1093 builder.createBlock(&whileOp.getAfter(), {}, types, {loc, loc}); 1094 builder.setInsertionPointToEnd(after); 1095 lo = after->getArgument(0); 1096 hi = after->getArgument(1); 1097 args[0] = lo; 1098 args[1] = hi; 1099 1100 if (isHybrid) { 1101 Value len = builder.create<arith::SubIOp>(loc, hi, lo); 1102 Value lenLimit = constantIndex(builder, loc, 30); 1103 Value lenCond = builder.create<arith::CmpIOp>( 1104 loc, arith::CmpIPredicate::ule, len, lenLimit); 1105 scf::IfOp lenIf = 1106 builder.create<scf::IfOp>(loc, types, lenCond, /*else=*/true); 1107 1108 // When len <= limit. 1109 builder.setInsertionPointToStart(&lenIf.getThenRegion().front()); 1110 FlatSymbolRefAttr insertionSortFunc = getMangledSortHelperFunc( 1111 builder, func, TypeRange(), kSortStableFuncNamePrefix, nx, ny, isCoo, 1112 ValueRange(args).drop_back(nTrailingP), createSortStableFunc); 1113 builder.create<func::CallOp>(loc, insertionSortFunc, TypeRange(), 1114 ValueRange(args).drop_back(nTrailingP)); 1115 builder.create<scf::YieldOp>(loc, ValueRange{lo, lo}); 1116 1117 // When len > limit. 1118 builder.setInsertionPointToStart(&lenIf.getElseRegion().front()); 1119 Value depthLimit = args.back(); 1120 depthLimit = builder.create<arith::SubIOp>(loc, depthLimit, 1121 constantI64(builder, loc, 1)); 1122 Value depthCond = 1123 builder.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule, 1124 depthLimit, constantI64(builder, loc, 0)); 1125 scf::IfOp depthIf = 1126 builder.create<scf::IfOp>(loc, types, depthCond, /*else=*/true); 1127 1128 // When depth exceeds limit. 1129 builder.setInsertionPointToStart(&depthIf.getThenRegion().front()); 1130 FlatSymbolRefAttr heapSortFunc = getMangledSortHelperFunc( 1131 builder, func, TypeRange(), kHeapSortFuncNamePrefix, nx, ny, isCoo, 1132 ValueRange(args).drop_back(nTrailingP), createHeapSortFunc); 1133 builder.create<func::CallOp>(loc, heapSortFunc, TypeRange(), 1134 ValueRange(args).drop_back(nTrailingP)); 1135 builder.create<scf::YieldOp>(loc, ValueRange{lo, lo}); 1136 1137 // When depth doesn't exceed limit. 1138 builder.setInsertionPointToStart(&depthIf.getElseRegion().front()); 1139 args.back() = depthLimit; 1140 std::tie(lo, hi) = 1141 createQuickSort(builder, module, func, args, nx, ny, isCoo, nTrailingP); 1142 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1143 1144 builder.setInsertionPointAfter(depthIf); 1145 lo = depthIf.getResult(0); 1146 hi = depthIf.getResult(1); 1147 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1148 1149 builder.setInsertionPointAfter(lenIf); 1150 lo = lenIf.getResult(0); 1151 hi = lenIf.getResult(1); 1152 } else { 1153 std::tie(lo, hi) = 1154 createQuickSort(builder, module, func, args, nx, ny, isCoo, nTrailingP); 1155 } 1156 1157 // New [lo, hi) for the next while-loop iteration. 1158 builder.create<scf::YieldOp>(loc, ValueRange{lo, hi}); 1159 1160 // After the while-loop. 1161 builder.setInsertionPointAfter(whileOp); 1162 builder.create<func::ReturnOp>(loc); 1163 } 1164 1165 /// Implements the rewriting for operator sort and sort_coo. 1166 template <typename OpTy> 1167 LogicalResult matchAndRewriteSortOp(OpTy op, ValueRange xys, uint64_t nx, 1168 uint64_t ny, bool isCoo, 1169 PatternRewriter &rewriter) { 1170 Location loc = op.getLoc(); 1171 SmallVector<Value> operands{constantIndex(rewriter, loc, 0), op.getN()}; 1172 1173 // Convert `values` to have dynamic shape and append them to `operands`. 1174 for (Value v : xys) { 1175 auto mtp = getMemRefType(v); 1176 if (!mtp.isDynamicDim(0)) { 1177 auto newMtp = 1178 MemRefType::get({ShapedType::kDynamic}, mtp.getElementType()); 1179 v = rewriter.create<memref::CastOp>(loc, newMtp, v); 1180 } 1181 operands.push_back(v); 1182 } 1183 1184 auto insertPoint = op->template getParentOfType<func::FuncOp>(); 1185 if (!insertPoint) 1186 return failure(); 1187 1188 SmallString<32> funcName; 1189 FuncGeneratorType funcGenerator; 1190 uint32_t nTrailingP = 0; 1191 switch (op.getAlgorithm()) { 1192 case SparseTensorSortKind::HybridQuickSort: { 1193 funcName = kHybridQuickSortFuncNamePrefix; 1194 funcGenerator = createQuickSortFunc; 1195 nTrailingP = 1; 1196 // As a heuristics, set depthLimit = 2 * log2(n). 1197 Value lo = operands[loIdx]; 1198 Value hi = operands[hiIdx]; 1199 Value len = rewriter.create<arith::IndexCastOp>( 1200 loc, rewriter.getI64Type(), 1201 rewriter.create<arith::SubIOp>(loc, hi, lo)); 1202 Value depthLimit = rewriter.create<arith::SubIOp>( 1203 loc, constantI64(rewriter, loc, 64), 1204 rewriter.create<math::CountLeadingZerosOp>(loc, len)); 1205 operands.push_back(depthLimit); 1206 break; 1207 } 1208 case SparseTensorSortKind::QuickSort: 1209 funcName = kQuickSortFuncNamePrefix; 1210 funcGenerator = createQuickSortFunc; 1211 break; 1212 case SparseTensorSortKind::InsertionSortStable: 1213 funcName = kSortStableFuncNamePrefix; 1214 funcGenerator = createSortStableFunc; 1215 break; 1216 case SparseTensorSortKind::HeapSort: 1217 funcName = kHeapSortFuncNamePrefix; 1218 funcGenerator = createHeapSortFunc; 1219 break; 1220 } 1221 1222 FlatSymbolRefAttr func = 1223 getMangledSortHelperFunc(rewriter, insertPoint, TypeRange(), funcName, nx, 1224 ny, isCoo, operands, funcGenerator, nTrailingP); 1225 rewriter.replaceOpWithNewOp<func::CallOp>(op, func, TypeRange(), operands); 1226 return success(); 1227 } 1228 1229 //===---------------------------------------------------------------------===// 1230 // The actual sparse buffer rewriting rules. 1231 //===---------------------------------------------------------------------===// 1232 1233 namespace { 1234 1235 /// Sparse rewriting rule for the push_back operator. 1236 struct PushBackRewriter : OpRewritePattern<PushBackOp> { 1237 public: 1238 using OpRewritePattern<PushBackOp>::OpRewritePattern; 1239 PushBackRewriter(MLIRContext *context, bool enableInit) 1240 : OpRewritePattern(context), enableBufferInitialization(enableInit) {} 1241 LogicalResult matchAndRewrite(PushBackOp op, 1242 PatternRewriter &rewriter) const override { 1243 // Rewrite push_back(buffer, value, n) to: 1244 // new_size = size(buffer) + n 1245 // if (new_size > capacity(buffer)) 1246 // while new_size > new_capacity 1247 // new_capacity = new_capacity*2 1248 // new_buffer = realloc(buffer, new_capacity) 1249 // buffer = new_buffer 1250 // subBuffer = subviewof(buffer) 1251 // linalg.fill subBuffer value 1252 // 1253 // size(buffer) += n 1254 // 1255 // The capacity check is skipped when the attribute inbounds is presented. 1256 Location loc = op->getLoc(); 1257 Value c0 = constantIndex(rewriter, loc, 0); 1258 Value buffer = op.getInBuffer(); 1259 Value capacity = rewriter.create<memref::DimOp>(loc, buffer, c0); 1260 Value size = op.getCurSize(); 1261 Value value = op.getValue(); 1262 1263 Value n = op.getN() ? op.getN() : constantIndex(rewriter, loc, 1); 1264 Value newSize = rewriter.create<arith::AddIOp>(loc, size, n); 1265 auto nValue = dyn_cast_or_null<arith::ConstantIndexOp>(n.getDefiningOp()); 1266 bool nIsOne = (nValue && nValue.value() == 1); 1267 1268 if (!op.getInbounds()) { 1269 Value cond = rewriter.create<arith::CmpIOp>( 1270 loc, arith::CmpIPredicate::ugt, newSize, capacity); 1271 1272 Value c2 = constantIndex(rewriter, loc, 2); 1273 auto bufferType = 1274 MemRefType::get({ShapedType::kDynamic}, value.getType()); 1275 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, bufferType, cond, 1276 /*else=*/true); 1277 // True branch. 1278 rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front()); 1279 if (nIsOne) { 1280 capacity = rewriter.create<arith::MulIOp>(loc, capacity, c2); 1281 } else { 1282 // Use a do-while loop to calculate the new capacity as follows: 1283 // do { new_capacity *= 2 } while (size > new_capacity) 1284 scf::WhileOp whileOp = 1285 rewriter.create<scf::WhileOp>(loc, capacity.getType(), capacity); 1286 1287 // The before-region of the WhileOp. 1288 Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, 1289 {capacity.getType()}, {loc}); 1290 rewriter.setInsertionPointToEnd(before); 1291 1292 capacity = 1293 rewriter.create<arith::MulIOp>(loc, before->getArgument(0), c2); 1294 cond = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ugt, 1295 newSize, capacity); 1296 rewriter.create<scf::ConditionOp>(loc, cond, ValueRange{capacity}); 1297 // The after-region of the WhileOp. 1298 Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, 1299 {capacity.getType()}, {loc}); 1300 rewriter.setInsertionPointToEnd(after); 1301 rewriter.create<scf::YieldOp>(loc, after->getArguments()); 1302 1303 rewriter.setInsertionPointAfter(whileOp); 1304 capacity = whileOp.getResult(0); 1305 } 1306 1307 Value newBuffer = 1308 rewriter.create<memref::ReallocOp>(loc, bufferType, buffer, capacity); 1309 if (enableBufferInitialization) { 1310 Value fillSize = rewriter.create<arith::SubIOp>(loc, capacity, newSize); 1311 Value fillValue = constantZero(rewriter, loc, value.getType()); 1312 Value subBuffer = rewriter.create<memref::SubViewOp>( 1313 loc, newBuffer, /*offset=*/ValueRange{newSize}, 1314 /*size=*/ValueRange{fillSize}, 1315 /*step=*/ValueRange{constantIndex(rewriter, loc, 1)}); 1316 rewriter.create<linalg::FillOp>(loc, fillValue, subBuffer); 1317 } 1318 rewriter.create<scf::YieldOp>(loc, newBuffer); 1319 1320 // False branch. 1321 rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front()); 1322 rewriter.create<scf::YieldOp>(loc, buffer); 1323 1324 // Prepare for adding the value to the end of the buffer. 1325 rewriter.setInsertionPointAfter(ifOp); 1326 buffer = ifOp.getResult(0); 1327 } 1328 1329 // Add the value to the end of the buffer. 1330 if (nIsOne) { 1331 rewriter.create<memref::StoreOp>(loc, value, buffer, size); 1332 } else { 1333 Value subBuffer = rewriter.create<memref::SubViewOp>( 1334 loc, buffer, /*offset=*/ValueRange{size}, /*size=*/ValueRange{n}, 1335 /*step=*/ValueRange{constantIndex(rewriter, loc, 1)}); 1336 rewriter.create<linalg::FillOp>(loc, value, subBuffer); 1337 } 1338 1339 // Update the buffer size. 1340 rewriter.replaceOp(op, {buffer, newSize}); 1341 return success(); 1342 } 1343 1344 private: 1345 bool enableBufferInitialization; 1346 }; 1347 1348 /// Sparse rewriting rule for the sort operator. 1349 struct SortRewriter : public OpRewritePattern<SortOp> { 1350 public: 1351 using OpRewritePattern<SortOp>::OpRewritePattern; 1352 1353 LogicalResult matchAndRewrite(SortOp op, 1354 PatternRewriter &rewriter) const override { 1355 SmallVector<Value> xys(op.getXs()); 1356 xys.append(op.getYs().begin(), op.getYs().end()); 1357 return matchAndRewriteSortOp(op, xys, op.getXs().size(), /*ny=*/0, 1358 /*isCoo=*/false, rewriter); 1359 } 1360 }; 1361 1362 /// Sparse rewriting rule for the sort_coo operator. 1363 struct SortCooRewriter : public OpRewritePattern<SortCooOp> { 1364 public: 1365 using OpRewritePattern<SortCooOp>::OpRewritePattern; 1366 1367 LogicalResult matchAndRewrite(SortCooOp op, 1368 PatternRewriter &rewriter) const override { 1369 SmallVector<Value> xys; 1370 xys.push_back(op.getXy()); 1371 xys.append(op.getYs().begin(), op.getYs().end()); 1372 uint64_t nx = 1; 1373 if (auto nxAttr = op.getNxAttr()) 1374 nx = nxAttr.getInt(); 1375 1376 uint64_t ny = 0; 1377 if (auto nyAttr = op.getNyAttr()) 1378 ny = nyAttr.getInt(); 1379 1380 return matchAndRewriteSortOp(op, xys, nx, ny, 1381 /*isCoo=*/true, rewriter); 1382 } 1383 }; 1384 1385 } // namespace 1386 1387 //===---------------------------------------------------------------------===// 1388 // Methods that add patterns described in this file to a pattern list. 1389 //===---------------------------------------------------------------------===// 1390 1391 void mlir::populateSparseBufferRewriting(RewritePatternSet &patterns, 1392 bool enableBufferInitialization) { 1393 patterns.add<PushBackRewriter>(patterns.getContext(), 1394 enableBufferInitialization); 1395 patterns.add<SortRewriter, SortCooRewriter>(patterns.getContext()); 1396 } 1397