| 1 | //===- Rewrite.cpp - C API for Rewrite Patterns ---------------------------===// |
| 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 | #include "mlir-c/Rewrite.h" |
| 10 | |
| 11 | #include "mlir-c/Support.h" |
| 12 | #include "mlir-c/Transforms.h" |
| 13 | #include "mlir/CAPI/IR.h" |
| 14 | #include "mlir/CAPI/IRMapping.h" |
| 15 | #include "mlir/CAPI/Rewrite.h" |
| 16 | #include "mlir/CAPI/Support.h" |
| 17 | #include "mlir/CAPI/Wrap.h" |
| 18 | #include "mlir/IR/Attributes.h" |
| 19 | #include "mlir/IR/PDLPatternMatch.h.inc" |
| 20 | #include "mlir/IR/PatternMatch.h" |
| 21 | #include "mlir/Rewrite/FrozenRewritePatternSet.h" |
| 22 | #include "mlir/Transforms/DialectConversion.h" |
| 23 | #include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 24 | #include "mlir/Transforms/WalkPatternRewriteDriver.h" |
| 25 | |
| 26 | #include <cassert> |
| 27 | |
| 28 | using namespace mlir; |
| 29 | |
| 30 | //===----------------------------------------------------------------------===// |
| 31 | /// RewriterBase API inherited from OpBuilder |
| 32 | //===----------------------------------------------------------------------===// |
| 33 | |
| 34 | MlirContext mlirRewriterBaseGetContext(MlirRewriterBase rewriter) { |
| 35 | return wrap(cpp: unwrap(c: rewriter)->getContext()); |
| 36 | } |
| 37 | |
| 38 | //===----------------------------------------------------------------------===// |
| 39 | /// Insertion points methods |
| 40 | //===----------------------------------------------------------------------===// |
| 41 | |
| 42 | void mlirRewriterBaseClearInsertionPoint(MlirRewriterBase rewriter) { |
| 43 | unwrap(c: rewriter)->clearInsertionPoint(); |
| 44 | } |
| 45 | |
| 46 | void mlirRewriterBaseSetInsertionPointBefore(MlirRewriterBase rewriter, |
| 47 | MlirOperation op) { |
| 48 | unwrap(c: rewriter)->setInsertionPoint(unwrap(c: op)); |
| 49 | } |
| 50 | |
| 51 | void mlirRewriterBaseSetInsertionPointAfter(MlirRewriterBase rewriter, |
| 52 | MlirOperation op) { |
| 53 | unwrap(c: rewriter)->setInsertionPointAfter(unwrap(c: op)); |
| 54 | } |
| 55 | |
| 56 | void mlirRewriterBaseSetInsertionPointAfterValue(MlirRewriterBase rewriter, |
| 57 | MlirValue value) { |
| 58 | unwrap(c: rewriter)->setInsertionPointAfterValue(unwrap(c: value)); |
| 59 | } |
| 60 | |
| 61 | void mlirRewriterBaseSetInsertionPointToStart(MlirRewriterBase rewriter, |
| 62 | MlirBlock block) { |
| 63 | unwrap(c: rewriter)->setInsertionPointToStart(unwrap(c: block)); |
| 64 | } |
| 65 | |
| 66 | void mlirRewriterBaseSetInsertionPointToEnd(MlirRewriterBase rewriter, |
| 67 | MlirBlock block) { |
| 68 | unwrap(c: rewriter)->setInsertionPointToEnd(unwrap(c: block)); |
| 69 | } |
| 70 | |
| 71 | MlirBlock mlirRewriterBaseGetInsertionBlock(MlirRewriterBase rewriter) { |
| 72 | return wrap(cpp: unwrap(c: rewriter)->getInsertionBlock()); |
| 73 | } |
| 74 | |
| 75 | MlirBlock mlirRewriterBaseGetBlock(MlirRewriterBase rewriter) { |
| 76 | return wrap(cpp: unwrap(c: rewriter)->getBlock()); |
| 77 | } |
| 78 | |
| 79 | MlirOperation |
| 80 | mlirRewriterBaseGetOperationAfterInsertion(MlirRewriterBase rewriter) { |
| 81 | mlir::RewriterBase *base = unwrap(c: rewriter); |
| 82 | mlir::Block *block = base->getInsertionBlock(); |
| 83 | mlir::Block::iterator it = base->getInsertionPoint(); |
| 84 | if (it == block->end()) |
| 85 | return {.ptr: nullptr}; |
| 86 | |
| 87 | return wrap(cpp: std::addressof(r&: *it)); |
| 88 | } |
| 89 | |
| 90 | MlirRewriterBaseInsertPoint |
| 91 | mlirRewriterBaseSaveInsertionPoint(MlirRewriterBase rewriter) { |
| 92 | OpBuilder::InsertPoint ip = unwrap(c: rewriter)->saveInsertionPoint(); |
| 93 | if (!ip.isSet()) |
| 94 | return {.block: {.ptr: nullptr}, .operationAfter: {.ptr: nullptr}}; |
| 95 | Block *block = ip.getBlock(); |
| 96 | MlirOperation operationAfter = ip.getPoint() == block->end() |
| 97 | ? MlirOperation{.ptr: nullptr} |
| 98 | : wrap(cpp: &*ip.getPoint()); |
| 99 | return {.block: wrap(cpp: block), .operationAfter: operationAfter}; |
| 100 | } |
| 101 | |
| 102 | void mlirRewriterBaseRestoreInsertionPoint( |
| 103 | MlirRewriterBase rewriter, MlirRewriterBaseInsertPoint insertPoint) { |
| 104 | if (mlirBlockIsNull(block: insertPoint.block)) { |
| 105 | unwrap(c: rewriter)->clearInsertionPoint(); |
| 106 | return; |
| 107 | } |
| 108 | Block *block = unwrap(c: insertPoint.block); |
| 109 | if (mlirOperationIsNull(op: insertPoint.operationAfter)) |
| 110 | unwrap(c: rewriter)->setInsertionPointToEnd(block); |
| 111 | else |
| 112 | unwrap(c: rewriter)->setInsertionPoint( |
| 113 | block, insertPoint: Block::iterator(unwrap(c: insertPoint.operationAfter))); |
| 114 | } |
| 115 | |
| 116 | //===----------------------------------------------------------------------===// |
| 117 | /// Block and operation creation/insertion/cloning |
| 118 | //===----------------------------------------------------------------------===// |
| 119 | |
| 120 | MlirBlock mlirRewriterBaseCreateBlockBefore(MlirRewriterBase rewriter, |
| 121 | MlirBlock insertBefore, |
| 122 | intptr_t nArgTypes, |
| 123 | MlirType const *argTypes, |
| 124 | MlirLocation const *locations) { |
| 125 | SmallVector<Type, 4> args; |
| 126 | ArrayRef<Type> unwrappedArgs = unwrapList(size: nArgTypes, first: argTypes, storage&: args); |
| 127 | SmallVector<Location, 4> locs; |
| 128 | ArrayRef<Location> unwrappedLocs = unwrapList(size: nArgTypes, first: locations, storage&: locs); |
| 129 | return wrap(cpp: unwrap(c: rewriter)->createBlock(insertBefore: unwrap(c: insertBefore), argTypes: unwrappedArgs, |
| 130 | locs: unwrappedLocs)); |
| 131 | } |
| 132 | |
| 133 | MlirOperation mlirRewriterBaseInsert(MlirRewriterBase rewriter, |
| 134 | MlirOperation op) { |
| 135 | return wrap(cpp: unwrap(c: rewriter)->insert(op: unwrap(c: op))); |
| 136 | } |
| 137 | |
| 138 | // Other methods of OpBuilder |
| 139 | |
| 140 | MlirOperation mlirRewriterBaseClone(MlirRewriterBase rewriter, |
| 141 | MlirOperation op) { |
| 142 | return wrap(cpp: unwrap(c: rewriter)->clone(op&: *unwrap(c: op))); |
| 143 | } |
| 144 | |
| 145 | MlirOperation mlirRewriterBaseCloneWithoutRegions(MlirRewriterBase rewriter, |
| 146 | MlirOperation op) { |
| 147 | return wrap(cpp: unwrap(c: rewriter)->cloneWithoutRegions(op&: *unwrap(c: op))); |
| 148 | } |
| 149 | |
| 150 | MlirOperation mlirRewriterBaseCloneWithMapping(MlirRewriterBase rewriter, |
| 151 | MlirOperation op, |
| 152 | MlirIRMapping mapping) { |
| 153 | return wrap(cpp: unwrap(c: rewriter)->clone(op&: *unwrap(c: op), mapper&: *unwrap(c: mapping))); |
| 154 | } |
| 155 | |
| 156 | void mlirRewriterBaseCloneRegionBefore(MlirRewriterBase rewriter, |
| 157 | MlirRegion region, MlirBlock before) { |
| 158 | |
| 159 | unwrap(c: rewriter)->cloneRegionBefore(region&: *unwrap(c: region), before: unwrap(c: before)); |
| 160 | } |
| 161 | |
| 162 | //===----------------------------------------------------------------------===// |
| 163 | /// RewriterBase API |
| 164 | //===----------------------------------------------------------------------===// |
| 165 | |
| 166 | void mlirRewriterBaseInlineRegionBefore(MlirRewriterBase rewriter, |
| 167 | MlirRegion region, MlirBlock before) { |
| 168 | unwrap(c: rewriter)->inlineRegionBefore(region&: *unwrap(c: region), before: unwrap(c: before)); |
| 169 | } |
| 170 | |
| 171 | void mlirRewriterBaseReplaceOpWithValues(MlirRewriterBase rewriter, |
| 172 | MlirOperation op, intptr_t nValues, |
| 173 | MlirValue const *values) { |
| 174 | SmallVector<Value, 4> vals; |
| 175 | ArrayRef<Value> unwrappedVals = unwrapList(size: nValues, first: values, storage&: vals); |
| 176 | unwrap(c: rewriter)->replaceOp(op: unwrap(c: op), newValues: unwrappedVals); |
| 177 | } |
| 178 | |
| 179 | void mlirRewriterBaseReplaceOpWithOperation(MlirRewriterBase rewriter, |
| 180 | MlirOperation op, |
| 181 | MlirOperation newOp) { |
| 182 | unwrap(c: rewriter)->replaceOp(op: unwrap(c: op), newOp: unwrap(c: newOp)); |
| 183 | } |
| 184 | |
| 185 | void mlirRewriterBaseEraseOp(MlirRewriterBase rewriter, MlirOperation op) { |
| 186 | unwrap(c: rewriter)->eraseOp(op: unwrap(c: op)); |
| 187 | } |
| 188 | |
| 189 | void mlirRewriterBaseEraseBlock(MlirRewriterBase rewriter, MlirBlock block) { |
| 190 | unwrap(c: rewriter)->eraseBlock(block: unwrap(c: block)); |
| 191 | } |
| 192 | |
| 193 | void mlirRewriterBaseInlineBlockBefore(MlirRewriterBase rewriter, |
| 194 | MlirBlock source, MlirOperation op, |
| 195 | intptr_t nArgValues, |
| 196 | MlirValue const *argValues) { |
| 197 | SmallVector<Value, 4> vals; |
| 198 | ArrayRef<Value> unwrappedVals = unwrapList(size: nArgValues, first: argValues, storage&: vals); |
| 199 | |
| 200 | unwrap(c: rewriter)->inlineBlockBefore(source: unwrap(c: source), op: unwrap(c: op), |
| 201 | argValues: unwrappedVals); |
| 202 | } |
| 203 | |
| 204 | void mlirRewriterBaseMergeBlocks(MlirRewriterBase rewriter, MlirBlock source, |
| 205 | MlirBlock dest, intptr_t nArgValues, |
| 206 | MlirValue const *argValues) { |
| 207 | SmallVector<Value, 4> args; |
| 208 | ArrayRef<Value> unwrappedArgs = unwrapList(size: nArgValues, first: argValues, storage&: args); |
| 209 | unwrap(c: rewriter)->mergeBlocks(source: unwrap(c: source), dest: unwrap(c: dest), argValues: unwrappedArgs); |
| 210 | } |
| 211 | |
| 212 | void mlirRewriterBaseMoveOpBefore(MlirRewriterBase rewriter, MlirOperation op, |
| 213 | MlirOperation existingOp) { |
| 214 | unwrap(c: rewriter)->moveOpBefore(op: unwrap(c: op), existingOp: unwrap(c: existingOp)); |
| 215 | } |
| 216 | |
| 217 | void mlirRewriterBaseMoveOpAfter(MlirRewriterBase rewriter, MlirOperation op, |
| 218 | MlirOperation existingOp) { |
| 219 | unwrap(c: rewriter)->moveOpAfter(op: unwrap(c: op), existingOp: unwrap(c: existingOp)); |
| 220 | } |
| 221 | |
| 222 | void mlirRewriterBaseMoveBlockBefore(MlirRewriterBase rewriter, MlirBlock block, |
| 223 | MlirBlock existingBlock) { |
| 224 | unwrap(c: rewriter)->moveBlockBefore(block: unwrap(c: block), anotherBlock: unwrap(c: existingBlock)); |
| 225 | } |
| 226 | |
| 227 | void mlirRewriterBaseStartOpModification(MlirRewriterBase rewriter, |
| 228 | MlirOperation op) { |
| 229 | unwrap(c: rewriter)->startOpModification(op: unwrap(c: op)); |
| 230 | } |
| 231 | |
| 232 | void mlirRewriterBaseFinalizeOpModification(MlirRewriterBase rewriter, |
| 233 | MlirOperation op) { |
| 234 | unwrap(c: rewriter)->finalizeOpModification(op: unwrap(c: op)); |
| 235 | } |
| 236 | |
| 237 | void mlirRewriterBaseCancelOpModification(MlirRewriterBase rewriter, |
| 238 | MlirOperation op) { |
| 239 | unwrap(c: rewriter)->cancelOpModification(op: unwrap(c: op)); |
| 240 | } |
| 241 | |
| 242 | void mlirRewriterBaseReplaceAllUsesWith(MlirRewriterBase rewriter, |
| 243 | MlirValue from, MlirValue to) { |
| 244 | unwrap(c: rewriter)->replaceAllUsesWith(from: unwrap(c: from), to: unwrap(c: to)); |
| 245 | } |
| 246 | |
| 247 | void mlirRewriterBaseReplaceAllValueRangeUsesWith(MlirRewriterBase rewriter, |
| 248 | intptr_t nValues, |
| 249 | MlirValue const *from, |
| 250 | MlirValue const *to) { |
| 251 | SmallVector<Value, 4> fromVals; |
| 252 | ArrayRef<Value> unwrappedFromVals = unwrapList(size: nValues, first: from, storage&: fromVals); |
| 253 | SmallVector<Value, 4> toVals; |
| 254 | ArrayRef<Value> unwrappedToVals = unwrapList(size: nValues, first: to, storage&: toVals); |
| 255 | unwrap(c: rewriter)->replaceAllUsesWith(from: unwrappedFromVals, to: unwrappedToVals); |
| 256 | } |
| 257 | |
| 258 | void mlirRewriterBaseReplaceAllOpUsesWithValueRange(MlirRewriterBase rewriter, |
| 259 | MlirOperation from, |
| 260 | intptr_t nTo, |
| 261 | MlirValue const *to) { |
| 262 | SmallVector<Value, 4> toVals; |
| 263 | ArrayRef<Value> unwrappedToVals = unwrapList(size: nTo, first: to, storage&: toVals); |
| 264 | unwrap(c: rewriter)->replaceAllOpUsesWith(from: unwrap(c: from), to: unwrappedToVals); |
| 265 | } |
| 266 | |
| 267 | void mlirRewriterBaseReplaceAllOpUsesWithOperation(MlirRewriterBase rewriter, |
| 268 | MlirOperation from, |
| 269 | MlirOperation to) { |
| 270 | unwrap(c: rewriter)->replaceAllOpUsesWith(from: unwrap(c: from), to: unwrap(c: to)); |
| 271 | } |
| 272 | |
| 273 | void mlirRewriterBaseReplaceOpUsesWithinBlock(MlirRewriterBase rewriter, |
| 274 | MlirOperation op, |
| 275 | intptr_t nNewValues, |
| 276 | MlirValue const *newValues, |
| 277 | MlirBlock block) { |
| 278 | SmallVector<Value, 4> vals; |
| 279 | ArrayRef<Value> unwrappedVals = unwrapList(size: nNewValues, first: newValues, storage&: vals); |
| 280 | unwrap(c: rewriter)->replaceOpUsesWithinBlock(op: unwrap(c: op), newValues: unwrappedVals, |
| 281 | block: unwrap(c: block)); |
| 282 | } |
| 283 | |
| 284 | void mlirRewriterBaseReplaceAllUsesExcept(MlirRewriterBase rewriter, |
| 285 | MlirValue from, MlirValue to, |
| 286 | MlirOperation exceptedUser) { |
| 287 | unwrap(c: rewriter)->replaceAllUsesExcept(from: unwrap(c: from), to: unwrap(c: to), |
| 288 | exceptedUser: unwrap(c: exceptedUser)); |
| 289 | } |
| 290 | |
| 291 | //===----------------------------------------------------------------------===// |
| 292 | /// IRRewriter API |
| 293 | //===----------------------------------------------------------------------===// |
| 294 | |
| 295 | MlirRewriterBase mlirIRRewriterCreate(MlirContext context) { |
| 296 | return wrap(cpp: new IRRewriter(unwrap(c: context))); |
| 297 | } |
| 298 | |
| 299 | MlirRewriterBase mlirIRRewriterCreateFromOp(MlirOperation op) { |
| 300 | return wrap(cpp: new IRRewriter(unwrap(c: op))); |
| 301 | } |
| 302 | |
| 303 | void mlirIRRewriterDestroy(MlirRewriterBase rewriter) { |
| 304 | delete static_cast<IRRewriter *>(unwrap(c: rewriter)); |
| 305 | } |
| 306 | |
| 307 | //===----------------------------------------------------------------------===// |
| 308 | /// Dialect constant materialization API |
| 309 | //===----------------------------------------------------------------------===// |
| 310 | |
| 311 | MlirOperation mlirDialectMaterializeConstant(MlirDialect dialect, |
| 312 | MlirRewriterBase rewriter, |
| 313 | MlirAttribute value, MlirType type, |
| 314 | MlirLocation loc) { |
| 315 | return wrap(cpp: unwrap(c: dialect)->materializeConstant( |
| 316 | builder&: *unwrap(c: rewriter), value: unwrap(c: value), type: unwrap(c: type), loc: unwrap(c: loc))); |
| 317 | } |
| 318 | |
| 319 | //===----------------------------------------------------------------------===// |
| 320 | /// RewritePatternSet and FrozenRewritePatternSet API |
| 321 | //===----------------------------------------------------------------------===// |
| 322 | |
| 323 | MlirFrozenRewritePatternSet |
| 324 | mlirFreezeRewritePattern(MlirRewritePatternSet set) { |
| 325 | auto *m = new mlir::FrozenRewritePatternSet(std::move(*unwrap(c: set))); |
| 326 | set.ptr = nullptr; |
| 327 | return wrap(cpp: m); |
| 328 | } |
| 329 | |
| 330 | void mlirFrozenRewritePatternSetDestroy(MlirFrozenRewritePatternSet set) { |
| 331 | delete unwrap(c: set); |
| 332 | set.ptr = nullptr; |
| 333 | } |
| 334 | |
| 335 | //===----------------------------------------------------------------------===// |
| 336 | /// GreedyRewriteDriverConfig API |
| 337 | //===----------------------------------------------------------------------===// |
| 338 | |
| 339 | inline mlir::GreedyRewriteConfig *unwrap(MlirGreedyRewriteDriverConfig config) { |
| 340 | assert(config.ptr && "unexpected null config" ); |
| 341 | return static_cast<mlir::GreedyRewriteConfig *>(config.ptr); |
| 342 | } |
| 343 | |
| 344 | inline MlirGreedyRewriteDriverConfig wrap(mlir::GreedyRewriteConfig *config) { |
| 345 | return {.ptr: config}; |
| 346 | } |
| 347 | |
| 348 | MlirGreedyRewriteDriverConfig mlirGreedyRewriteDriverConfigCreate() { |
| 349 | return wrap(config: new mlir::GreedyRewriteConfig()); |
| 350 | } |
| 351 | |
| 352 | void mlirGreedyRewriteDriverConfigDestroy( |
| 353 | MlirGreedyRewriteDriverConfig config) { |
| 354 | delete unwrap(config); |
| 355 | } |
| 356 | |
| 357 | void mlirGreedyRewriteDriverConfigSetMaxIterations( |
| 358 | MlirGreedyRewriteDriverConfig config, int64_t maxIterations) { |
| 359 | unwrap(config)->setMaxIterations(maxIterations); |
| 360 | } |
| 361 | |
| 362 | void mlirGreedyRewriteDriverConfigSetMaxNumRewrites( |
| 363 | MlirGreedyRewriteDriverConfig config, int64_t maxNumRewrites) { |
| 364 | unwrap(config)->setMaxNumRewrites(maxNumRewrites); |
| 365 | } |
| 366 | |
| 367 | void mlirGreedyRewriteDriverConfigSetUseTopDownTraversal( |
| 368 | MlirGreedyRewriteDriverConfig config, bool useTopDownTraversal) { |
| 369 | unwrap(config)->setUseTopDownTraversal(useTopDownTraversal); |
| 370 | } |
| 371 | |
| 372 | void mlirGreedyRewriteDriverConfigEnableFolding( |
| 373 | MlirGreedyRewriteDriverConfig config, bool enable) { |
| 374 | unwrap(config)->enableFolding(enable); |
| 375 | } |
| 376 | |
| 377 | void mlirGreedyRewriteDriverConfigSetStrictness( |
| 378 | MlirGreedyRewriteDriverConfig config, |
| 379 | MlirGreedyRewriteStrictness strictness) { |
| 380 | mlir::GreedyRewriteStrictness cppStrictness; |
| 381 | switch (strictness) { |
| 382 | case MLIR_GREEDY_REWRITE_STRICTNESS_ANY_OP: |
| 383 | cppStrictness = mlir::GreedyRewriteStrictness::AnyOp; |
| 384 | break; |
| 385 | case MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_AND_NEW_OPS: |
| 386 | cppStrictness = mlir::GreedyRewriteStrictness::ExistingAndNewOps; |
| 387 | break; |
| 388 | case MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_OPS: |
| 389 | cppStrictness = mlir::GreedyRewriteStrictness::ExistingOps; |
| 390 | break; |
| 391 | } |
| 392 | unwrap(config)->setStrictness(cppStrictness); |
| 393 | } |
| 394 | |
| 395 | void mlirGreedyRewriteDriverConfigSetRegionSimplificationLevel( |
| 396 | MlirGreedyRewriteDriverConfig config, MlirGreedySimplifyRegionLevel level) { |
| 397 | mlir::GreedySimplifyRegionLevel cppLevel; |
| 398 | switch (level) { |
| 399 | case MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_DISABLED: |
| 400 | cppLevel = mlir::GreedySimplifyRegionLevel::Disabled; |
| 401 | break; |
| 402 | case MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_NORMAL: |
| 403 | cppLevel = mlir::GreedySimplifyRegionLevel::Normal; |
| 404 | break; |
| 405 | case MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_AGGRESSIVE: |
| 406 | cppLevel = mlir::GreedySimplifyRegionLevel::Aggressive; |
| 407 | break; |
| 408 | } |
| 409 | unwrap(config)->setRegionSimplificationLevel(cppLevel); |
| 410 | } |
| 411 | |
| 412 | void mlirGreedyRewriteDriverConfigEnableConstantCSE( |
| 413 | MlirGreedyRewriteDriverConfig config, bool enable) { |
| 414 | unwrap(config)->enableConstantCSE(enable); |
| 415 | } |
| 416 | |
| 417 | int64_t mlirGreedyRewriteDriverConfigGetMaxIterations( |
| 418 | MlirGreedyRewriteDriverConfig config) { |
| 419 | return unwrap(config)->getMaxIterations(); |
| 420 | } |
| 421 | |
| 422 | int64_t mlirGreedyRewriteDriverConfigGetMaxNumRewrites( |
| 423 | MlirGreedyRewriteDriverConfig config) { |
| 424 | return unwrap(config)->getMaxNumRewrites(); |
| 425 | } |
| 426 | |
| 427 | bool mlirGreedyRewriteDriverConfigGetUseTopDownTraversal( |
| 428 | MlirGreedyRewriteDriverConfig config) { |
| 429 | return unwrap(config)->getUseTopDownTraversal(); |
| 430 | } |
| 431 | |
| 432 | bool mlirGreedyRewriteDriverConfigIsFoldingEnabled( |
| 433 | MlirGreedyRewriteDriverConfig config) { |
| 434 | return unwrap(config)->isFoldingEnabled(); |
| 435 | } |
| 436 | |
| 437 | MlirGreedyRewriteStrictness mlirGreedyRewriteDriverConfigGetStrictness( |
| 438 | MlirGreedyRewriteDriverConfig config) { |
| 439 | mlir::GreedyRewriteStrictness cppStrictness = unwrap(config)->getStrictness(); |
| 440 | switch (cppStrictness) { |
| 441 | case mlir::GreedyRewriteStrictness::AnyOp: |
| 442 | return MLIR_GREEDY_REWRITE_STRICTNESS_ANY_OP; |
| 443 | case mlir::GreedyRewriteStrictness::ExistingAndNewOps: |
| 444 | return MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_AND_NEW_OPS; |
| 445 | case mlir::GreedyRewriteStrictness::ExistingOps: |
| 446 | return MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_OPS; |
| 447 | } |
| 448 | llvm_unreachable("Unknown GreedyRewriteStrictness" ); |
| 449 | } |
| 450 | |
| 451 | MlirGreedySimplifyRegionLevel |
| 452 | mlirGreedyRewriteDriverConfigGetRegionSimplificationLevel( |
| 453 | MlirGreedyRewriteDriverConfig config) { |
| 454 | mlir::GreedySimplifyRegionLevel cppLevel = |
| 455 | unwrap(config)->getRegionSimplificationLevel(); |
| 456 | switch (cppLevel) { |
| 457 | case mlir::GreedySimplifyRegionLevel::Disabled: |
| 458 | return MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_DISABLED; |
| 459 | case mlir::GreedySimplifyRegionLevel::Normal: |
| 460 | return MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_NORMAL; |
| 461 | case mlir::GreedySimplifyRegionLevel::Aggressive: |
| 462 | return MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_AGGRESSIVE; |
| 463 | } |
| 464 | llvm_unreachable("Unknown GreedySimplifyRegionLevel" ); |
| 465 | } |
| 466 | |
| 467 | bool mlirGreedyRewriteDriverConfigIsConstantCSEEnabled( |
| 468 | MlirGreedyRewriteDriverConfig config) { |
| 469 | return unwrap(config)->isConstantCSEEnabled(); |
| 470 | } |
| 471 | |
| 472 | MlirLogicalResult |
| 473 | mlirApplyPatternsAndFoldGreedily(MlirModule op, |
| 474 | MlirFrozenRewritePatternSet patterns, |
| 475 | MlirGreedyRewriteDriverConfig config) { |
| 476 | return wrap(res: mlir::applyPatternsGreedily(op: unwrap(c: op), patterns: *unwrap(c: patterns), |
| 477 | config: *unwrap(config))); |
| 478 | } |
| 479 | |
| 480 | MlirLogicalResult |
| 481 | mlirApplyPatternsAndFoldGreedilyWithOp(MlirOperation op, |
| 482 | MlirFrozenRewritePatternSet patterns, |
| 483 | MlirGreedyRewriteDriverConfig config) { |
| 484 | return wrap(res: mlir::applyPatternsGreedily(op: unwrap(c: op), patterns: *unwrap(c: patterns), |
| 485 | config: *unwrap(config))); |
| 486 | } |
| 487 | |
| 488 | void mlirWalkAndApplyPatterns(MlirOperation op, |
| 489 | MlirFrozenRewritePatternSet patterns) { |
| 490 | mlir::walkAndApplyPatterns(op: unwrap(c: op), patterns: *unwrap(c: patterns)); |
| 491 | } |
| 492 | |
| 493 | MlirLogicalResult |
| 494 | mlirApplyPartialConversion(MlirOperation op, MlirConversionTarget target, |
| 495 | MlirFrozenRewritePatternSet patterns, |
| 496 | MlirConversionConfig config) { |
| 497 | return wrap(res: mlir::applyPartialConversion(op: unwrap(c: op), target: *unwrap(c: target), |
| 498 | patterns: *unwrap(c: patterns), config: *unwrap(c: config))); |
| 499 | } |
| 500 | |
| 501 | MlirLogicalResult mlirApplyFullConversion(MlirOperation op, |
| 502 | MlirConversionTarget target, |
| 503 | MlirFrozenRewritePatternSet patterns, |
| 504 | MlirConversionConfig config) { |
| 505 | return wrap(res: mlir::applyFullConversion(op: unwrap(c: op), target: *unwrap(c: target), |
| 506 | patterns: *unwrap(c: patterns), config: *unwrap(c: config))); |
| 507 | } |
| 508 | |
| 509 | //===----------------------------------------------------------------------===// |
| 510 | /// ConversionConfig API |
| 511 | //===----------------------------------------------------------------------===// |
| 512 | |
| 513 | MlirConversionConfig mlirConversionConfigCreate(void) { |
| 514 | return wrap(cpp: new mlir::ConversionConfig()); |
| 515 | } |
| 516 | |
| 517 | void mlirConversionConfigDestroy(MlirConversionConfig config) { |
| 518 | delete unwrap(c: config); |
| 519 | } |
| 520 | |
| 521 | void mlirConversionConfigSetFoldingMode(MlirConversionConfig config, |
| 522 | MlirDialectConversionFoldingMode mode) { |
| 523 | mlir::DialectConversionFoldingMode cppMode; |
| 524 | switch (mode) { |
| 525 | case MLIR_DIALECT_CONVERSION_FOLDING_MODE_NEVER: |
| 526 | cppMode = mlir::DialectConversionFoldingMode::Never; |
| 527 | break; |
| 528 | case MLIR_DIALECT_CONVERSION_FOLDING_MODE_BEFORE_PATTERNS: |
| 529 | cppMode = mlir::DialectConversionFoldingMode::BeforePatterns; |
| 530 | break; |
| 531 | case MLIR_DIALECT_CONVERSION_FOLDING_MODE_AFTER_PATTERNS: |
| 532 | cppMode = mlir::DialectConversionFoldingMode::AfterPatterns; |
| 533 | break; |
| 534 | } |
| 535 | unwrap(c: config)->foldingMode = cppMode; |
| 536 | } |
| 537 | |
| 538 | MlirDialectConversionFoldingMode |
| 539 | mlirConversionConfigGetFoldingMode(MlirConversionConfig config) { |
| 540 | switch (unwrap(c: config)->foldingMode) { |
| 541 | case mlir::DialectConversionFoldingMode::Never: |
| 542 | return MLIR_DIALECT_CONVERSION_FOLDING_MODE_NEVER; |
| 543 | case mlir::DialectConversionFoldingMode::BeforePatterns: |
| 544 | return MLIR_DIALECT_CONVERSION_FOLDING_MODE_BEFORE_PATTERNS; |
| 545 | case mlir::DialectConversionFoldingMode::AfterPatterns: |
| 546 | return MLIR_DIALECT_CONVERSION_FOLDING_MODE_AFTER_PATTERNS; |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | void mlirConversionConfigEnableBuildMaterializations( |
| 551 | MlirConversionConfig config, bool enable) { |
| 552 | unwrap(c: config)->buildMaterializations = enable; |
| 553 | } |
| 554 | |
| 555 | bool mlirConversionConfigIsBuildMaterializationsEnabled( |
| 556 | MlirConversionConfig config) { |
| 557 | return unwrap(c: config)->buildMaterializations; |
| 558 | } |
| 559 | |
| 560 | //===----------------------------------------------------------------------===// |
| 561 | /// PatternRewriter API |
| 562 | //===----------------------------------------------------------------------===// |
| 563 | |
| 564 | MlirRewriterBase mlirPatternRewriterAsBase(MlirPatternRewriter rewriter) { |
| 565 | return wrap(cpp: static_cast<mlir::RewriterBase *>(unwrap(c: rewriter))); |
| 566 | } |
| 567 | |
| 568 | //===----------------------------------------------------------------------===// |
| 569 | /// ConversionPatternRewriter API |
| 570 | //===----------------------------------------------------------------------===// |
| 571 | |
| 572 | MlirPatternRewriter mlirConversionPatternRewriterAsPatternRewriter( |
| 573 | MlirConversionPatternRewriter rewriter) { |
| 574 | return wrap(cpp: static_cast<mlir::PatternRewriter *>(unwrap(c: rewriter))); |
| 575 | } |
| 576 | |
| 577 | MlirLogicalResult mlirConversionPatternRewriterConvertRegionTypes( |
| 578 | MlirConversionPatternRewriter rewriter, MlirRegion region, |
| 579 | MlirTypeConverter typeConverter) { |
| 580 | return wrap(res: unwrap(c: rewriter)->convertRegionTypes(region: unwrap(c: region), |
| 581 | converter: *unwrap(c: typeConverter))); |
| 582 | } |
| 583 | |
| 584 | void mlirConversionPatternRewriterReplaceOpWithMultiple( |
| 585 | MlirConversionPatternRewriter rewriter, MlirOperation op, intptr_t nRanges, |
| 586 | intptr_t *rangeSizes, MlirValue *values) { |
| 587 | SmallVector<SmallVector<Value>> ranges; |
| 588 | ranges.reserve(N: nRanges); |
| 589 | MlirValue *cur = values; |
| 590 | for (intptr_t i = 0; i < nRanges; ++i) { |
| 591 | intptr_t rangeSize = rangeSizes[i]; |
| 592 | SmallVector<Value> range; |
| 593 | range.reserve(N: rangeSize); |
| 594 | for (intptr_t j = 0; j < rangeSize; ++j, ++cur) |
| 595 | range.push_back(Elt: unwrap(c: *cur)); |
| 596 | ranges.push_back(Elt: std::move(range)); |
| 597 | } |
| 598 | unwrap(c: rewriter)->replaceOpWithMultiple(op: unwrap(c: op), newValues: std::move(ranges)); |
| 599 | } |
| 600 | |
| 601 | //===----------------------------------------------------------------------===// |
| 602 | /// ConversionTarget API |
| 603 | //===----------------------------------------------------------------------===// |
| 604 | |
| 605 | MlirConversionTarget mlirConversionTargetCreate(MlirContext context) { |
| 606 | return wrap(cpp: new mlir::ConversionTarget(*unwrap(c: context))); |
| 607 | } |
| 608 | |
| 609 | void mlirConversionTargetDestroy(MlirConversionTarget target) { |
| 610 | delete unwrap(c: target); |
| 611 | } |
| 612 | |
| 613 | void mlirConversionTargetAddLegalOp(MlirConversionTarget target, |
| 614 | MlirStringRef opName) { |
| 615 | unwrap(c: target)->addLegalOp( |
| 616 | op: mlir::OperationName(unwrap(ref: opName), &unwrap(c: target)->getContext())); |
| 617 | } |
| 618 | |
| 619 | void mlirConversionTargetAddIllegalOp(MlirConversionTarget target, |
| 620 | MlirStringRef opName) { |
| 621 | unwrap(c: target)->addIllegalOp( |
| 622 | op: mlir::OperationName(unwrap(ref: opName), &unwrap(c: target)->getContext())); |
| 623 | } |
| 624 | |
| 625 | void mlirConversionTargetAddLegalDialect(MlirConversionTarget target, |
| 626 | MlirStringRef dialectName) { |
| 627 | unwrap(c: target)->addLegalDialect(name: unwrap(ref: dialectName)); |
| 628 | } |
| 629 | |
| 630 | void mlirConversionTargetAddIllegalDialect(MlirConversionTarget target, |
| 631 | MlirStringRef dialectName) { |
| 632 | unwrap(c: target)->addIllegalDialect(name: unwrap(ref: dialectName)); |
| 633 | } |
| 634 | |
| 635 | namespace { |
| 636 | /// Wraps a C dynamic-legality callback as a C++ DynamicLegalityCallbackFn, |
| 637 | /// translating the tri-state MlirConversionTargetLegality result into the |
| 638 | /// std::optional<bool> expected by ConversionTarget (NO_OPINION -> nullopt). |
| 639 | ConversionTarget::DynamicLegalityCallbackFn |
| 640 | wrapLegalityCallback(MlirConversionTargetDynamicLegalityCallback callback, |
| 641 | void *userData) { |
| 642 | return [callback, userData](Operation *op) -> std::optional<bool> { |
| 643 | switch (callback(wrap(cpp: op), userData)) { |
| 644 | case MLIR_CONVERSION_TARGET_LEGALITY_LEGAL: |
| 645 | return true; |
| 646 | case MLIR_CONVERSION_TARGET_LEGALITY_ILLEGAL: |
| 647 | return false; |
| 648 | case MLIR_CONVERSION_TARGET_LEGALITY_NO_OPINION: |
| 649 | return std::nullopt; |
| 650 | } |
| 651 | llvm_unreachable("unknown MlirConversionTargetLegality" ); |
| 652 | }; |
| 653 | } |
| 654 | } // namespace |
| 655 | |
| 656 | void mlirConversionTargetAddDynamicallyLegalOp( |
| 657 | MlirConversionTarget target, MlirStringRef opName, |
| 658 | MlirConversionTargetDynamicLegalityCallback callback, void *userData) { |
| 659 | assert(callback && "expected non-null legality callback" ); |
| 660 | MLIRContext *ctx = &unwrap(c: target)->getContext(); |
| 661 | OperationName name(unwrap(ref: opName), ctx); |
| 662 | unwrap(c: target)->addDynamicallyLegalOp( |
| 663 | op: name, callback: wrapLegalityCallback(callback, userData)); |
| 664 | } |
| 665 | |
| 666 | void mlirConversionTargetAddDynamicallyLegalDialect( |
| 667 | MlirConversionTarget target, MlirStringRef dialectName, |
| 668 | MlirConversionTargetDynamicLegalityCallback callback, void *userData) { |
| 669 | assert(callback && "expected non-null legality callback" ); |
| 670 | unwrap(c: target)->addDynamicallyLegalDialect( |
| 671 | callback: wrapLegalityCallback(callback, userData), name: unwrap(ref: dialectName)); |
| 672 | } |
| 673 | |
| 674 | void mlirConversionTargetMarkOpRecursivelyLegal( |
| 675 | MlirConversionTarget target, MlirStringRef opName, |
| 676 | MlirConversionTargetDynamicLegalityCallback callback, void *userData) { |
| 677 | MLIRContext *ctx = &unwrap(c: target)->getContext(); |
| 678 | OperationName name(unwrap(ref: opName), ctx); |
| 679 | ConversionTarget::DynamicLegalityCallbackFn fn; |
| 680 | if (callback) |
| 681 | fn = wrapLegalityCallback(callback, userData); |
| 682 | unwrap(c: target)->markOpRecursivelyLegal(name, callback: fn); |
| 683 | } |
| 684 | |
| 685 | void mlirConversionTargetMarkUnknownOpDynamicallyLegal( |
| 686 | MlirConversionTarget target, |
| 687 | MlirConversionTargetDynamicLegalityCallback callback, void *userData) { |
| 688 | assert(callback && "expected non-null legality callback" ); |
| 689 | unwrap(c: target)->markUnknownOpDynamicallyLegal( |
| 690 | fn: wrapLegalityCallback(callback, userData)); |
| 691 | } |
| 692 | |
| 693 | //===----------------------------------------------------------------------===// |
| 694 | /// TypeConverter API |
| 695 | //===----------------------------------------------------------------------===// |
| 696 | |
| 697 | MlirTypeConverter mlirTypeConverterCreate() { |
| 698 | return wrap(cpp: new mlir::TypeConverter()); |
| 699 | } |
| 700 | |
| 701 | void mlirTypeConverterDestroy(MlirTypeConverter typeConverter) { |
| 702 | delete unwrap(c: typeConverter); |
| 703 | } |
| 704 | |
| 705 | void mlirTypeConverterAddConversion( |
| 706 | MlirTypeConverter typeConverter, |
| 707 | MlirTypeConverterConversionCallback convertType, void *userData) { |
| 708 | unwrap(c: typeConverter) |
| 709 | ->addConversion( |
| 710 | callback: [convertType, userData](Type type, SmallVectorImpl<Type> &results) |
| 711 | -> std::optional<LogicalResult> { |
| 712 | MlirType converted{.ptr: nullptr}; |
| 713 | MlirTypeConverterConversionStatus status = |
| 714 | convertType(wrap(cpp: type), &converted, userData); |
| 715 | switch (status) { |
| 716 | case MlirTypeConverterConversionStatusSuccess: |
| 717 | results.push_back(Elt: unwrap(c: converted)); |
| 718 | return success(); |
| 719 | case MlirTypeConverterConversionStatusFailure: |
| 720 | // Failure: fail the conversion without trying another |
| 721 | // registered conversion function. |
| 722 | return failure(); |
| 723 | case MlirTypeConverterConversionStatusDeclined: |
| 724 | // Declined: allow the driver to try another conversion function. |
| 725 | return std::nullopt; |
| 726 | } |
| 727 | llvm_unreachable("unknown MlirTypeConverterConversionStatus" ); |
| 728 | }); |
| 729 | } |
| 730 | |
| 731 | void mlirTypeConverterConversionResultsAppend( |
| 732 | MlirTypeConverterConversionResults results, MlirType type) { |
| 733 | static_cast<SmallVectorImpl<Type> *>(results.ptr)->push_back(Elt: unwrap(c: type)); |
| 734 | } |
| 735 | |
| 736 | void mlirTypeConverterAdd1ToNConversion( |
| 737 | MlirTypeConverter typeConverter, |
| 738 | MlirTypeConverter1ToNConversionCallback convertType, void *userData) { |
| 739 | unwrap(c: typeConverter) |
| 740 | ->addConversion( |
| 741 | callback: [convertType, userData](Type type, SmallVectorImpl<Type> &results) |
| 742 | -> std::optional<LogicalResult> { |
| 743 | size_t numPriorResults = results.size(); |
| 744 | MlirTypeConverterConversionResults wrappedResults{.ptr: &results}; |
| 745 | MlirTypeConverterConversionStatus status = |
| 746 | convertType(wrap(cpp: type), wrappedResults, userData); |
| 747 | switch (status) { |
| 748 | case MlirTypeConverterConversionStatusSuccess: |
| 749 | return success(); |
| 750 | case MlirTypeConverterConversionStatusFailure: |
| 751 | // Failure. Restore any types the callback appended (a |
| 752 | // non-succeeding conversion function must not mutate `results`) |
| 753 | // and fail the conversion without trying another function. |
| 754 | results.truncate(N: numPriorResults); |
| 755 | return failure(); |
| 756 | case MlirTypeConverterConversionStatusDeclined: |
| 757 | // The callback declined. Restore any types it appended so the |
| 758 | // driver's "try the next conversion" invariant holds (a declining |
| 759 | // conversion function must not mutate `results`). |
| 760 | results.truncate(N: numPriorResults); |
| 761 | return std::nullopt; |
| 762 | } |
| 763 | llvm_unreachable("unknown MlirTypeConverterConversionStatus" ); |
| 764 | }); |
| 765 | } |
| 766 | |
| 767 | MlirType mlirTypeConverterConvertType(MlirTypeConverter typeConverter, |
| 768 | MlirType type) { |
| 769 | return wrap(cpp: unwrap(c: typeConverter)->convertType(t: unwrap(c: type))); |
| 770 | } |
| 771 | |
| 772 | namespace { |
| 773 | SmallVector<MlirValue> wrapInputs(ValueRange inputs) { |
| 774 | SmallVector<MlirValue> wrappedInputs; |
| 775 | wrappedInputs.reserve(N: inputs.size()); |
| 776 | for (Value v : inputs) |
| 777 | wrappedInputs.push_back(Elt: wrap(cpp: v)); |
| 778 | return wrappedInputs; |
| 779 | } |
| 780 | |
| 781 | std::function<Value(OpBuilder &, Type, ValueRange, Location)> |
| 782 | wrapSourceMaterializationCallback( |
| 783 | MlirTypeConverterSourceMaterializationCallback callback, void *userData) { |
| 784 | return [callback, userData](OpBuilder &builder, Type type, ValueRange inputs, |
| 785 | Location loc) -> Value { |
| 786 | SmallVector<MlirValue> wrappedInputs = wrapInputs(inputs); |
| 787 | MlirValue result = |
| 788 | callback(wrap(cpp: static_cast<RewriterBase *>(&builder)), wrap(cpp: type), |
| 789 | static_cast<intptr_t>(wrappedInputs.size()), |
| 790 | wrappedInputs.data(), wrap(cpp: loc), userData); |
| 791 | return mlirValueIsNull(value: result) ? Value() : unwrap(c: result); |
| 792 | }; |
| 793 | } |
| 794 | |
| 795 | std::function<Value(OpBuilder &, Type, ValueRange, Location, Type)> |
| 796 | wrapTargetMaterializationCallback( |
| 797 | MlirTypeConverterTargetMaterializationCallback callback, void *userData) { |
| 798 | return [callback, userData](OpBuilder &builder, Type type, ValueRange inputs, |
| 799 | Location loc, Type originalType) -> Value { |
| 800 | SmallVector<MlirValue> wrappedInputs = wrapInputs(inputs); |
| 801 | MlirValue result = |
| 802 | callback(wrap(cpp: static_cast<RewriterBase *>(&builder)), wrap(cpp: type), |
| 803 | static_cast<intptr_t>(wrappedInputs.size()), |
| 804 | wrappedInputs.data(), wrap(cpp: loc), wrap(cpp: originalType), userData); |
| 805 | return mlirValueIsNull(value: result) ? Value() : unwrap(c: result); |
| 806 | }; |
| 807 | } |
| 808 | |
| 809 | std::function<SmallVector<Value>(OpBuilder &, TypeRange, ValueRange, Location, |
| 810 | Type)> |
| 811 | wrap1ToNTargetMaterializationCallback( |
| 812 | MlirTypeConverter1ToNTargetMaterializationCallback callback, |
| 813 | void *userData) { |
| 814 | return [callback, userData](OpBuilder &builder, TypeRange outputTypes, |
| 815 | ValueRange inputs, Location loc, |
| 816 | Type originalType) -> SmallVector<Value> { |
| 817 | SmallVector<MlirType> wrappedOutputTypes; |
| 818 | wrappedOutputTypes.reserve(N: outputTypes.size()); |
| 819 | for (Type t : outputTypes) |
| 820 | wrappedOutputTypes.push_back(Elt: wrap(cpp: t)); |
| 821 | SmallVector<MlirValue> wrappedInputs = wrapInputs(inputs); |
| 822 | SmallVector<MlirValue> wrappedOutputs(outputTypes.size(), |
| 823 | MlirValue{.ptr: nullptr}); |
| 824 | MlirLogicalResult result = callback( |
| 825 | wrap(cpp: static_cast<RewriterBase *>(&builder)), |
| 826 | static_cast<intptr_t>(wrappedOutputTypes.size()), |
| 827 | wrappedOutputTypes.data(), static_cast<intptr_t>(wrappedInputs.size()), |
| 828 | wrappedInputs.data(), wrap(cpp: loc), wrap(cpp: originalType), |
| 829 | wrappedOutputs.data(), userData); |
| 830 | if (mlirLogicalResultIsFailure(res: result)) |
| 831 | return {}; // declined; another materialization may be attempted |
| 832 | SmallVector<Value> outputs; |
| 833 | outputs.reserve(N: wrappedOutputs.size()); |
| 834 | for (MlirValue v : wrappedOutputs) { |
| 835 | // On success the callback must fill every output; a null entry is a |
| 836 | // contract violation (to decline, the callback returns failure instead). |
| 837 | assert(!mlirValueIsNull(v) && |
| 838 | "1:N target materialization succeeded but left one of the outputs " |
| 839 | "null" ); |
| 840 | outputs.push_back(Elt: unwrap(c: v)); |
| 841 | } |
| 842 | return outputs; |
| 843 | }; |
| 844 | } |
| 845 | } // namespace |
| 846 | |
| 847 | void mlirTypeConverterAddSourceMaterialization( |
| 848 | MlirTypeConverter typeConverter, |
| 849 | MlirTypeConverterSourceMaterializationCallback callback, void *userData) { |
| 850 | assert(callback && "expected non-null materialization callback" ); |
| 851 | unwrap(c: typeConverter) |
| 852 | ->addSourceMaterialization( |
| 853 | callback: wrapSourceMaterializationCallback(callback, userData)); |
| 854 | } |
| 855 | |
| 856 | void mlirTypeConverterAddTargetMaterialization( |
| 857 | MlirTypeConverter typeConverter, |
| 858 | MlirTypeConverterTargetMaterializationCallback callback, void *userData) { |
| 859 | assert(callback && "expected non-null materialization callback" ); |
| 860 | unwrap(c: typeConverter) |
| 861 | ->addTargetMaterialization( |
| 862 | callback: wrapTargetMaterializationCallback(callback, userData)); |
| 863 | } |
| 864 | |
| 865 | void mlirTypeConverterAdd1ToNTargetMaterialization( |
| 866 | MlirTypeConverter typeConverter, |
| 867 | MlirTypeConverter1ToNTargetMaterializationCallback callback, |
| 868 | void *userData) { |
| 869 | assert(callback && "expected non-null materialization callback" ); |
| 870 | unwrap(c: typeConverter) |
| 871 | ->addTargetMaterialization( |
| 872 | callback: wrap1ToNTargetMaterializationCallback(callback, userData)); |
| 873 | } |
| 874 | |
| 875 | //===----------------------------------------------------------------------===// |
| 876 | /// ConversionPattern API |
| 877 | //===----------------------------------------------------------------------===// |
| 878 | |
| 879 | namespace mlir { |
| 880 | |
| 881 | class ExternalConversionPattern : public mlir::ConversionPattern { |
| 882 | public: |
| 883 | ExternalConversionPattern(MlirConversionPatternCallbacks callbacks, |
| 884 | void *userData, StringRef rootName, |
| 885 | PatternBenefit benefit, MLIRContext *context, |
| 886 | TypeConverter *typeConverter, |
| 887 | ArrayRef<StringRef> generatedNames) |
| 888 | : ConversionPattern(*typeConverter, rootName, benefit, context, |
| 889 | generatedNames), |
| 890 | callbacks(callbacks), userData(userData) { |
| 891 | if (callbacks.construct) |
| 892 | callbacks.construct(userData); |
| 893 | } |
| 894 | |
| 895 | ~ExternalConversionPattern() { |
| 896 | if (callbacks.destruct) |
| 897 | callbacks.destruct(userData); |
| 898 | } |
| 899 | |
| 900 | LogicalResult |
| 901 | matchAndRewrite(Operation *op, ArrayRef<Value> operands, |
| 902 | ConversionPatternRewriter &rewriter) const override { |
| 903 | std::vector<MlirValue> wrappedOperands; |
| 904 | for (Value val : operands) |
| 905 | wrappedOperands.push_back(x: wrap(cpp: val)); |
| 906 | return unwrap(res: callbacks.matchAndRewrite( |
| 907 | wrap(cpp: static_cast<const mlir::ConversionPattern *>(this)), wrap(cpp: op), |
| 908 | wrappedOperands.size(), wrappedOperands.data(), wrap(cpp: &rewriter), |
| 909 | userData)); |
| 910 | } |
| 911 | |
| 912 | LogicalResult |
| 913 | matchAndRewrite(Operation *op, ArrayRef<ValueRange> operands, |
| 914 | ConversionPatternRewriter &rewriter) const override { |
| 915 | // Without a 1:N callback, defer to the default behavior, which dispatches |
| 916 | // to the 1:1 matchAndRewrite above or fails to match on a 1:N mapping. |
| 917 | if (!callbacks.matchAndRewrite1ToN) |
| 918 | return dispatchTo1To1(self: *this, op, operands, rewriter); |
| 919 | SmallVector<intptr_t> rangeSizes; |
| 920 | rangeSizes.reserve(N: operands.size()); |
| 921 | std::vector<MlirValue> wrappedOperands; |
| 922 | for (ValueRange range : operands) { |
| 923 | rangeSizes.push_back(Elt: static_cast<intptr_t>(range.size())); |
| 924 | for (Value val : range) |
| 925 | wrappedOperands.push_back(x: wrap(cpp: val)); |
| 926 | } |
| 927 | return unwrap(res: callbacks.matchAndRewrite1ToN( |
| 928 | wrap(cpp: static_cast<const mlir::ConversionPattern *>(this)), wrap(cpp: op), |
| 929 | static_cast<intptr_t>(rangeSizes.size()), rangeSizes.data(), |
| 930 | static_cast<intptr_t>(wrappedOperands.size()), wrappedOperands.data(), |
| 931 | wrap(cpp: &rewriter), userData)); |
| 932 | } |
| 933 | |
| 934 | private: |
| 935 | MlirConversionPatternCallbacks callbacks; |
| 936 | void *userData; |
| 937 | }; |
| 938 | |
| 939 | } // namespace mlir |
| 940 | |
| 941 | MlirConversionPattern mlirOpConversionPatternCreate( |
| 942 | MlirStringRef rootName, unsigned benefit, MlirContext context, |
| 943 | MlirTypeConverter typeConverter, MlirConversionPatternCallbacks callbacks, |
| 944 | void *userData, size_t nGeneratedNames, MlirStringRef *generatedNames) { |
| 945 | std::vector<mlir::StringRef> generatedNamesVec; |
| 946 | generatedNamesVec.reserve(n: nGeneratedNames); |
| 947 | for (size_t i = 0; i < nGeneratedNames; ++i) |
| 948 | generatedNamesVec.push_back(x: unwrap(ref: generatedNames[i])); |
| 949 | return wrap(cpp: new mlir::ExternalConversionPattern( |
| 950 | callbacks, userData, unwrap(ref: rootName), PatternBenefit(benefit), |
| 951 | unwrap(c: context), unwrap(c: typeConverter), generatedNamesVec)); |
| 952 | } |
| 953 | |
| 954 | MlirTypeConverter |
| 955 | mlirConversionPatternGetTypeConverter(MlirConversionPattern pattern) { |
| 956 | return wrap(cpp: const_cast<TypeConverter *>(unwrap(c: pattern)->getTypeConverter())); |
| 957 | } |
| 958 | |
| 959 | MlirRewritePattern |
| 960 | mlirConversionPatternAsRewritePattern(MlirConversionPattern pattern) { |
| 961 | return wrap(cpp: static_cast<const RewritePattern *>(unwrap(c: pattern))); |
| 962 | } |
| 963 | |
| 964 | //===----------------------------------------------------------------------===// |
| 965 | /// RewritePattern API |
| 966 | //===----------------------------------------------------------------------===// |
| 967 | |
| 968 | namespace mlir { |
| 969 | |
| 970 | class ExternalRewritePattern : public mlir::RewritePattern { |
| 971 | public: |
| 972 | ExternalRewritePattern(MlirRewritePatternCallbacks callbacks, void *userData, |
| 973 | StringRef rootName, PatternBenefit benefit, |
| 974 | MLIRContext *context, |
| 975 | ArrayRef<StringRef> generatedNames) |
| 976 | : RewritePattern(rootName, benefit, context, generatedNames), |
| 977 | callbacks(callbacks), userData(userData) { |
| 978 | if (callbacks.construct) |
| 979 | callbacks.construct(userData); |
| 980 | } |
| 981 | |
| 982 | ~ExternalRewritePattern() { |
| 983 | if (callbacks.destruct) |
| 984 | callbacks.destruct(userData); |
| 985 | } |
| 986 | |
| 987 | LogicalResult matchAndRewrite(Operation *op, |
| 988 | PatternRewriter &rewriter) const override { |
| 989 | return unwrap(res: callbacks.matchAndRewrite( |
| 990 | wrap(cpp: static_cast<const mlir::RewritePattern *>(this)), wrap(cpp: op), |
| 991 | wrap(cpp: &rewriter), userData)); |
| 992 | } |
| 993 | |
| 994 | private: |
| 995 | MlirRewritePatternCallbacks callbacks; |
| 996 | void *userData; |
| 997 | }; |
| 998 | |
| 999 | } // namespace mlir |
| 1000 | |
| 1001 | MlirRewritePattern mlirOpRewritePatternCreate( |
| 1002 | MlirStringRef rootName, unsigned benefit, MlirContext context, |
| 1003 | MlirRewritePatternCallbacks callbacks, void *userData, |
| 1004 | size_t nGeneratedNames, MlirStringRef *generatedNames) { |
| 1005 | std::vector<mlir::StringRef> generatedNamesVec; |
| 1006 | generatedNamesVec.reserve(n: nGeneratedNames); |
| 1007 | for (size_t i = 0; i < nGeneratedNames; ++i) { |
| 1008 | generatedNamesVec.push_back(x: unwrap(ref: generatedNames[i])); |
| 1009 | } |
| 1010 | return wrap(cpp: new mlir::ExternalRewritePattern( |
| 1011 | callbacks, userData, unwrap(ref: rootName), PatternBenefit(benefit), |
| 1012 | unwrap(c: context), generatedNamesVec)); |
| 1013 | } |
| 1014 | |
| 1015 | //===----------------------------------------------------------------------===// |
| 1016 | /// RewritePatternSet API |
| 1017 | //===----------------------------------------------------------------------===// |
| 1018 | |
| 1019 | MlirRewritePatternSet mlirRewritePatternSetCreate(MlirContext context) { |
| 1020 | return wrap(cpp: new mlir::RewritePatternSet(unwrap(c: context))); |
| 1021 | } |
| 1022 | |
| 1023 | MlirContext mlirRewritePatternSetGetContext(MlirRewritePatternSet set) { |
| 1024 | return wrap(cpp: unwrap(c: set)->getContext()); |
| 1025 | } |
| 1026 | |
| 1027 | void mlirRewritePatternSetDestroy(MlirRewritePatternSet set) { |
| 1028 | delete unwrap(c: set); |
| 1029 | } |
| 1030 | |
| 1031 | void mlirRewritePatternSetAdd(MlirRewritePatternSet set, |
| 1032 | MlirRewritePattern pattern) { |
| 1033 | std::unique_ptr<mlir::RewritePattern> patternPtr( |
| 1034 | const_cast<mlir::RewritePattern *>(unwrap(c: pattern))); |
| 1035 | pattern.ptr = nullptr; |
| 1036 | unwrap(c: set)->add(pattern: std::move(patternPtr)); |
| 1037 | } |
| 1038 | |
| 1039 | //===----------------------------------------------------------------------===// |
| 1040 | /// PDLPatternModule API |
| 1041 | //===----------------------------------------------------------------------===// |
| 1042 | |
| 1043 | #if MLIR_ENABLE_PDL_IN_PATTERNMATCH |
| 1044 | MlirPDLPatternModule mlirPDLPatternModuleFromModule(MlirModule op) { |
| 1045 | return wrap(new mlir::PDLPatternModule( |
| 1046 | mlir::OwningOpRef<mlir::ModuleOp>(unwrap(op)))); |
| 1047 | } |
| 1048 | |
| 1049 | void mlirPDLPatternModuleDestroy(MlirPDLPatternModule op) { |
| 1050 | delete unwrap(op); |
| 1051 | op.ptr = nullptr; |
| 1052 | } |
| 1053 | |
| 1054 | MlirRewritePatternSet |
| 1055 | mlirRewritePatternSetFromPDLPatternModule(MlirPDLPatternModule op) { |
| 1056 | auto *m = new mlir::RewritePatternSet(std::move(*unwrap(op))); |
| 1057 | op.ptr = nullptr; |
| 1058 | return wrap(m); |
| 1059 | } |
| 1060 | |
| 1061 | MlirValue mlirPDLValueAsValue(MlirPDLValue value) { |
| 1062 | return wrap(llvm::dyn_cast_if_present<mlir::Value>(*unwrap(value))); |
| 1063 | } |
| 1064 | |
| 1065 | MlirType mlirPDLValueAsType(MlirPDLValue value) { |
| 1066 | return wrap(llvm::dyn_cast_if_present<mlir::Type>(*unwrap(value))); |
| 1067 | } |
| 1068 | |
| 1069 | MlirOperation mlirPDLValueAsOperation(MlirPDLValue value) { |
| 1070 | return wrap(llvm::dyn_cast_if_present<mlir::Operation *>(*unwrap(value))); |
| 1071 | } |
| 1072 | |
| 1073 | MlirAttribute mlirPDLValueAsAttribute(MlirPDLValue value) { |
| 1074 | return wrap(llvm::dyn_cast_if_present<mlir::Attribute>(*unwrap(value))); |
| 1075 | } |
| 1076 | |
| 1077 | void mlirPDLResultListPushBackValue(MlirPDLResultList results, |
| 1078 | MlirValue value) { |
| 1079 | unwrap(results)->push_back(unwrap(value)); |
| 1080 | } |
| 1081 | |
| 1082 | void mlirPDLResultListPushBackType(MlirPDLResultList results, MlirType value) { |
| 1083 | unwrap(results)->push_back(unwrap(value)); |
| 1084 | } |
| 1085 | |
| 1086 | void mlirPDLResultListPushBackOperation(MlirPDLResultList results, |
| 1087 | MlirOperation value) { |
| 1088 | unwrap(results)->push_back(unwrap(value)); |
| 1089 | } |
| 1090 | |
| 1091 | void mlirPDLResultListPushBackAttribute(MlirPDLResultList results, |
| 1092 | MlirAttribute value) { |
| 1093 | unwrap(results)->push_back(unwrap(value)); |
| 1094 | } |
| 1095 | |
| 1096 | inline std::vector<MlirPDLValue> wrap(ArrayRef<PDLValue> values) { |
| 1097 | std::vector<MlirPDLValue> mlirValues; |
| 1098 | mlirValues.reserve(values.size()); |
| 1099 | for (auto &value : values) { |
| 1100 | mlirValues.push_back(wrap(&value)); |
| 1101 | } |
| 1102 | return mlirValues; |
| 1103 | } |
| 1104 | |
| 1105 | void mlirPDLPatternModuleRegisterRewriteFunction( |
| 1106 | MlirPDLPatternModule pdlModule, MlirStringRef name, |
| 1107 | MlirPDLRewriteFunction rewriteFn, void *userData) { |
| 1108 | unwrap(pdlModule)->registerRewriteFunction( |
| 1109 | unwrap(name), |
| 1110 | [userData, rewriteFn](PatternRewriter &rewriter, PDLResultList &results, |
| 1111 | ArrayRef<PDLValue> values) -> LogicalResult { |
| 1112 | std::vector<MlirPDLValue> mlirValues = wrap(values); |
| 1113 | return unwrap(rewriteFn(wrap(&rewriter), wrap(&results), |
| 1114 | mlirValues.size(), mlirValues.data(), |
| 1115 | userData)); |
| 1116 | }); |
| 1117 | } |
| 1118 | |
| 1119 | void mlirPDLPatternModuleRegisterConstraintFunction( |
| 1120 | MlirPDLPatternModule pdlModule, MlirStringRef name, |
| 1121 | MlirPDLConstraintFunction constraintFn, void *userData) { |
| 1122 | unwrap(pdlModule)->registerConstraintFunction( |
| 1123 | unwrap(name), |
| 1124 | [userData, constraintFn](PatternRewriter &rewriter, |
| 1125 | PDLResultList &results, |
| 1126 | ArrayRef<PDLValue> values) -> LogicalResult { |
| 1127 | std::vector<MlirPDLValue> mlirValues = wrap(values); |
| 1128 | return unwrap(constraintFn(wrap(&rewriter), wrap(&results), |
| 1129 | mlirValues.size(), mlirValues.data(), |
| 1130 | userData)); |
| 1131 | }); |
| 1132 | } |
| 1133 | #endif // MLIR_ENABLE_PDL_IN_PATTERNMATCH |
| 1134 | |