1//===-- mlir-c/Rewrite.h - Helpers for C API to Rewrites ----------*- C -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM
4// Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This header declares the registration and creation method for
11// rewrite patterns.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef MLIR_C_REWRITE_H
16#define MLIR_C_REWRITE_H
17
18#include "mlir-c/IR.h"
19#include "mlir-c/Support.h"
20#include "mlir/Config/mlir-config.h"
21
22#ifdef __cplusplus
23extern "C" {
24#endif
25
26//===----------------------------------------------------------------------===//
27/// Opaque type declarations (see mlir-c/IR.h for more details).
28//===----------------------------------------------------------------------===//
29
30#define DEFINE_C_API_STRUCT(name, storage) \
31 struct name { \
32 storage *ptr; \
33 }; \
34 typedef struct name name
35
36DEFINE_C_API_STRUCT(MlirRewriterBase, void);
37DEFINE_C_API_STRUCT(MlirFrozenRewritePatternSet, void);
38DEFINE_C_API_STRUCT(MlirGreedyRewriteDriverConfig, void);
39
40/// Greedy rewrite strictness levels.
41typedef enum {
42 /// No restrictions wrt. which ops are processed.
43 MLIR_GREEDY_REWRITE_STRICTNESS_ANY_OP,
44 /// Only pre-existing and newly created ops are processed.
45 MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_AND_NEW_OPS,
46 /// Only pre-existing ops are processed.
47 MLIR_GREEDY_REWRITE_STRICTNESS_EXISTING_OPS
48} MlirGreedyRewriteStrictness;
49
50/// Greedy simplify region levels.
51typedef enum {
52 /// Disable region control-flow simplification.
53 MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_DISABLED,
54 /// Run the normal simplification (e.g. dead args elimination).
55 MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_NORMAL,
56 /// Run extra simplifications (e.g. block merging).
57 MLIR_GREEDY_SIMPLIFY_REGION_LEVEL_AGGRESSIVE
58} MlirGreedySimplifyRegionLevel;
59DEFINE_C_API_STRUCT(MlirRewritePatternSet, void);
60DEFINE_C_API_STRUCT(MlirPatternRewriter, void);
61DEFINE_C_API_STRUCT(MlirRewritePattern, const void);
62DEFINE_C_API_STRUCT(MlirConversionTarget, void);
63DEFINE_C_API_STRUCT(MlirConversionPattern, const void);
64DEFINE_C_API_STRUCT(MlirTypeConverter, void);
65DEFINE_C_API_STRUCT(MlirConversionPatternRewriter, void);
66DEFINE_C_API_STRUCT(MlirConversionConfig, void);
67
68//===----------------------------------------------------------------------===//
69/// RewriterBase API inherited from OpBuilder
70//===----------------------------------------------------------------------===//
71
72/// Get the MLIR context referenced by the rewriter.
73MLIR_CAPI_EXPORTED MlirContext
74mlirRewriterBaseGetContext(MlirRewriterBase rewriter);
75
76//===----------------------------------------------------------------------===//
77/// Insertion points methods
78//===----------------------------------------------------------------------===//
79
80// These do not include functions using Block::iterator or Region::iterator, as
81// they are not exposed by the C API yet. `InsertPoint` is exposed as
82// `MlirRewriterBaseInsertPoint` below.
83
84/// Reset the insertion point to no location. Creating an operation without a
85/// set insertion point is an error, but this can still be useful when the
86/// current insertion point a builder refers to is being removed.
87MLIR_CAPI_EXPORTED void
88mlirRewriterBaseClearInsertionPoint(MlirRewriterBase rewriter);
89
90/// Sets the insertion point to the specified operation, which will cause
91/// subsequent insertions to go right before it.
92MLIR_CAPI_EXPORTED void
93mlirRewriterBaseSetInsertionPointBefore(MlirRewriterBase rewriter,
94 MlirOperation op);
95
96/// Sets the insertion point to the node after the specified operation, which
97/// will cause subsequent insertions to go right after it.
98MLIR_CAPI_EXPORTED void
99mlirRewriterBaseSetInsertionPointAfter(MlirRewriterBase rewriter,
100 MlirOperation op);
101
102/// Sets the insertion point to the node after the specified value. If value
103/// has a defining operation, sets the insertion point to the node after such
104/// defining operation. This will cause subsequent insertions to go right
105/// after it. Otherwise, value is a BlockArgument. Sets the insertion point to
106/// the start of its block.
107MLIR_CAPI_EXPORTED void
108mlirRewriterBaseSetInsertionPointAfterValue(MlirRewriterBase rewriter,
109 MlirValue value);
110
111/// Sets the insertion point to the start of the specified block.
112MLIR_CAPI_EXPORTED void
113mlirRewriterBaseSetInsertionPointToStart(MlirRewriterBase rewriter,
114 MlirBlock block);
115
116/// Sets the insertion point to the end of the specified block.
117MLIR_CAPI_EXPORTED void
118mlirRewriterBaseSetInsertionPointToEnd(MlirRewriterBase rewriter,
119 MlirBlock block);
120
121/// Return the block the current insertion point belongs to. Note that the
122/// insertion point is not necessarily the end of the block.
123MLIR_CAPI_EXPORTED MlirBlock
124mlirRewriterBaseGetInsertionBlock(MlirRewriterBase rewriter);
125
126/// Returns the current block of the rewriter.
127MLIR_CAPI_EXPORTED MlirBlock
128mlirRewriterBaseGetBlock(MlirRewriterBase rewriter);
129
130/// Returns the operation right after the current insertion point
131/// of the rewriter. A null MlirOperation will be returned
132// if the current insertion point is at the end of the block.
133MLIR_CAPI_EXPORTED MlirOperation
134mlirRewriterBaseGetOperationAfterInsertion(MlirRewriterBase rewriter);
135
136/// A saved insertion point: a (block, operationAfter) pair. `operationAfter` is
137/// the operation that subsequent insertions go before. If `operationAfter` is
138/// null, the insertion point is at the end of `block`. If `block` is null, the
139/// insertion point is not set (cleared).
140typedef struct MlirRewriterBaseInsertPoint {
141 MlirBlock block;
142 MlirOperation operationAfter;
143} MlirRewriterBaseInsertPoint;
144
145/// Returns the current insertion point of the rewriter so that it can be
146/// restored later with mlirRewriterBaseRestoreInsertionPoint.
147MLIR_CAPI_EXPORTED MlirRewriterBaseInsertPoint
148mlirRewriterBaseSaveInsertionPoint(MlirRewriterBase rewriter);
149
150/// Restores a previously saved insertion point.
151MLIR_CAPI_EXPORTED void
152mlirRewriterBaseRestoreInsertionPoint(MlirRewriterBase rewriter,
153 MlirRewriterBaseInsertPoint insertPoint);
154
155//===----------------------------------------------------------------------===//
156/// Block and operation creation/insertion/cloning
157//===----------------------------------------------------------------------===//
158
159// These functions do not include the IRMapper, as it is not yet exposed by the
160// C API.
161
162/// Add new block with 'argTypes' arguments and set the insertion point to the
163/// end of it. The block is placed before 'insertBefore'. `locs` contains the
164/// locations of the inserted arguments, and should match the size of
165/// `argTypes`.
166MLIR_CAPI_EXPORTED MlirBlock mlirRewriterBaseCreateBlockBefore(
167 MlirRewriterBase rewriter, MlirBlock insertBefore, intptr_t nArgTypes,
168 MlirType const *argTypes, MlirLocation const *locations);
169
170/// Insert the given operation at the current insertion point and return it.
171MLIR_CAPI_EXPORTED MlirOperation
172mlirRewriterBaseInsert(MlirRewriterBase rewriter, MlirOperation op);
173
174/// Creates a deep copy of the specified operation.
175MLIR_CAPI_EXPORTED MlirOperation
176mlirRewriterBaseClone(MlirRewriterBase rewriter, MlirOperation op);
177
178/// Creates a deep copy of this operation but keep the operation regions
179/// empty.
180MLIR_CAPI_EXPORTED MlirOperation mlirRewriterBaseCloneWithoutRegions(
181 MlirRewriterBase rewriter, MlirOperation op);
182
183/// Clones the given operation using the rewriter and the provided IRMapping.
184/// The mapping is updated with the results of the cloned operation.
185MLIR_CAPI_EXPORTED MlirOperation mlirRewriterBaseCloneWithMapping(
186 MlirRewriterBase rewriter, MlirOperation op, MlirIRMapping mapping);
187
188/// Clone the blocks that belong to "region" before the given position in
189/// another region "parent".
190MLIR_CAPI_EXPORTED void
191mlirRewriterBaseCloneRegionBefore(MlirRewriterBase rewriter, MlirRegion region,
192 MlirBlock before);
193
194//===----------------------------------------------------------------------===//
195/// RewriterBase API
196//===----------------------------------------------------------------------===//
197
198/// Move the blocks that belong to "region" before the given position in
199/// another region "parent". The two regions must be different. The caller
200/// is responsible for creating or updating the operation transferring flow
201/// of control to the region and passing it the correct block arguments.
202MLIR_CAPI_EXPORTED void
203mlirRewriterBaseInlineRegionBefore(MlirRewriterBase rewriter, MlirRegion region,
204 MlirBlock before);
205
206/// Replace the results of the given (original) operation with the specified
207/// list of values (replacements). The result types of the given op and the
208/// replacements must match. The original op is erased.
209MLIR_CAPI_EXPORTED void
210mlirRewriterBaseReplaceOpWithValues(MlirRewriterBase rewriter, MlirOperation op,
211 intptr_t nValues, MlirValue const *values);
212
213/// Replace the results of the given (original) operation with the specified
214/// new op (replacement). The result types of the two ops must match. The
215/// original op is erased.
216MLIR_CAPI_EXPORTED void
217mlirRewriterBaseReplaceOpWithOperation(MlirRewriterBase rewriter,
218 MlirOperation op, MlirOperation newOp);
219
220/// Erases an operation that is known to have no uses.
221MLIR_CAPI_EXPORTED void mlirRewriterBaseEraseOp(MlirRewriterBase rewriter,
222 MlirOperation op);
223
224/// Erases a block along with all operations inside it.
225MLIR_CAPI_EXPORTED void mlirRewriterBaseEraseBlock(MlirRewriterBase rewriter,
226 MlirBlock block);
227
228/// Inline the operations of block 'source' before the operation 'op'. The
229/// source block will be deleted and must have no uses. 'argValues' is used to
230/// replace the block arguments of 'source'
231///
232/// The source block must have no successors. Otherwise, the resulting IR
233/// would have unreachable operations.
234MLIR_CAPI_EXPORTED void
235mlirRewriterBaseInlineBlockBefore(MlirRewriterBase rewriter, MlirBlock source,
236 MlirOperation op, intptr_t nArgValues,
237 MlirValue const *argValues);
238
239/// Inline the operations of block 'source' into the end of block 'dest'. The
240/// source block will be deleted and must have no uses. 'argValues' is used to
241/// replace the block arguments of 'source'
242///
243/// The dest block must have no successors. Otherwise, the resulting IR would
244/// have unreachable operation.
245MLIR_CAPI_EXPORTED void mlirRewriterBaseMergeBlocks(MlirRewriterBase rewriter,
246 MlirBlock source,
247 MlirBlock dest,
248 intptr_t nArgValues,
249 MlirValue const *argValues);
250
251/// Unlink this operation from its current block and insert it right before
252/// `existingOp` which may be in the same or another block in the same
253/// function.
254MLIR_CAPI_EXPORTED void mlirRewriterBaseMoveOpBefore(MlirRewriterBase rewriter,
255 MlirOperation op,
256 MlirOperation existingOp);
257
258/// Unlink this operation from its current block and insert it right after
259/// `existingOp` which may be in the same or another block in the same
260/// function.
261MLIR_CAPI_EXPORTED void mlirRewriterBaseMoveOpAfter(MlirRewriterBase rewriter,
262 MlirOperation op,
263 MlirOperation existingOp);
264
265/// Unlink this block and insert it right before `existingBlock`.
266MLIR_CAPI_EXPORTED void
267mlirRewriterBaseMoveBlockBefore(MlirRewriterBase rewriter, MlirBlock block,
268 MlirBlock existingBlock);
269
270/// This method is used to notify the rewriter that an in-place operation
271/// modification is about to happen. A call to this function *must* be
272/// followed by a call to either `finalizeOpModification` or
273/// `cancelOpModification`. This is a minor efficiency win (it avoids creating
274/// a new operation and removing the old one) but also often allows simpler
275/// code in the client.
276MLIR_CAPI_EXPORTED void
277mlirRewriterBaseStartOpModification(MlirRewriterBase rewriter,
278 MlirOperation op);
279
280/// This method is used to signal the end of an in-place modification of the
281/// given operation. This can only be called on operations that were provided
282/// to a call to `startOpModification`.
283MLIR_CAPI_EXPORTED void
284mlirRewriterBaseFinalizeOpModification(MlirRewriterBase rewriter,
285 MlirOperation op);
286
287/// This method cancels a pending in-place modification. This can only be
288/// called on operations that were provided to a call to
289/// `startOpModification`.
290MLIR_CAPI_EXPORTED void
291mlirRewriterBaseCancelOpModification(MlirRewriterBase rewriter,
292 MlirOperation op);
293
294/// Find uses of `from` and replace them with `to`. Also notify the listener
295/// about every in-place op modification (for every use that was replaced).
296MLIR_CAPI_EXPORTED void
297mlirRewriterBaseReplaceAllUsesWith(MlirRewriterBase rewriter, MlirValue from,
298 MlirValue to);
299
300/// Find uses of `from` and replace them with `to`. Also notify the listener
301/// about every in-place op modification (for every use that was replaced).
302MLIR_CAPI_EXPORTED void mlirRewriterBaseReplaceAllValueRangeUsesWith(
303 MlirRewriterBase rewriter, intptr_t nValues, MlirValue const *from,
304 MlirValue const *to);
305
306/// Find uses of `from` and replace them with `to`. Also notify the listener
307/// about every in-place op modification (for every use that was replaced)
308/// and that the `from` operation is about to be replaced.
309MLIR_CAPI_EXPORTED void
310mlirRewriterBaseReplaceAllOpUsesWithValueRange(MlirRewriterBase rewriter,
311 MlirOperation from, intptr_t nTo,
312 MlirValue const *to);
313
314/// Find uses of `from` and replace them with `to`. Also notify the listener
315/// about every in-place op modification (for every use that was replaced)
316/// and that the `from` operation is about to be replaced.
317MLIR_CAPI_EXPORTED void mlirRewriterBaseReplaceAllOpUsesWithOperation(
318 MlirRewriterBase rewriter, MlirOperation from, MlirOperation to);
319
320/// Find uses of `from` within `block` and replace them with `to`. Also notify
321/// the listener about every in-place op modification (for every use that was
322/// replaced). The optional `allUsesReplaced` flag is set to "true" if all
323/// uses were replaced.
324MLIR_CAPI_EXPORTED void mlirRewriterBaseReplaceOpUsesWithinBlock(
325 MlirRewriterBase rewriter, MlirOperation op, intptr_t nNewValues,
326 MlirValue const *newValues, MlirBlock block);
327
328/// Find uses of `from` and replace them with `to` except if the user is
329/// `exceptedUser`. Also notify the listener about every in-place op
330/// modification (for every use that was replaced).
331MLIR_CAPI_EXPORTED void
332mlirRewriterBaseReplaceAllUsesExcept(MlirRewriterBase rewriter, MlirValue from,
333 MlirValue to, MlirOperation exceptedUser);
334
335//===----------------------------------------------------------------------===//
336/// IRRewriter API
337//===----------------------------------------------------------------------===//
338
339/// Create an IRRewriter and transfer ownership to the caller.
340MLIR_CAPI_EXPORTED MlirRewriterBase mlirIRRewriterCreate(MlirContext context);
341
342/// Create an IRRewriter and transfer ownership to the caller. Additionally
343/// set the insertion point before the operation.
344MLIR_CAPI_EXPORTED MlirRewriterBase
345mlirIRRewriterCreateFromOp(MlirOperation op);
346
347/// Takes an IRRewriter owned by the caller and destroys it. It is the
348/// responsibility of the user to only pass an IRRewriter class.
349MLIR_CAPI_EXPORTED void mlirIRRewriterDestroy(MlirRewriterBase rewriter);
350
351//===----------------------------------------------------------------------===//
352/// Dialect constant materialization API
353//===----------------------------------------------------------------------===//
354
355/// Materializes a constant for the given attribute `value` and `type` using the
356/// dialect's `materializeConstant` hook. The operation is created with the
357/// given rewriter (used as an OpBuilder) at its current insertion point,
358/// without changing that insertion point. Returns a null operation if the
359/// dialect does not support materializing the given constant.
360MLIR_CAPI_EXPORTED MlirOperation mlirDialectMaterializeConstant(
361 MlirDialect dialect, MlirRewriterBase rewriter, MlirAttribute value,
362 MlirType type, MlirLocation loc);
363
364//===----------------------------------------------------------------------===//
365/// FrozenRewritePatternSet API
366//===----------------------------------------------------------------------===//
367
368/// Freeze the given MlirRewritePatternSet to a MlirFrozenRewritePatternSet.
369/// Note that the ownership of the input set is transferred into the frozen set
370/// after this call.
371MLIR_CAPI_EXPORTED MlirFrozenRewritePatternSet
372mlirFreezeRewritePattern(MlirRewritePatternSet set);
373
374/// Destroy the given MlirFrozenRewritePatternSet.
375MLIR_CAPI_EXPORTED void
376mlirFrozenRewritePatternSetDestroy(MlirFrozenRewritePatternSet set);
377
378MLIR_CAPI_EXPORTED MlirLogicalResult mlirApplyPatternsAndFoldGreedilyWithOp(
379 MlirOperation op, MlirFrozenRewritePatternSet patterns,
380 MlirGreedyRewriteDriverConfig);
381
382MLIR_CAPI_EXPORTED MlirLogicalResult mlirApplyPatternsAndFoldGreedily(
383 MlirModule op, MlirFrozenRewritePatternSet patterns,
384 MlirGreedyRewriteDriverConfig config);
385
386//===----------------------------------------------------------------------===//
387/// GreedyRewriteDriverConfig API
388//===----------------------------------------------------------------------===//
389
390/// Creates a greedy rewrite driver configuration with default settings.
391MLIR_CAPI_EXPORTED MlirGreedyRewriteDriverConfig
392mlirGreedyRewriteDriverConfigCreate(void);
393
394/// Destroys a greedy rewrite driver configuration.
395MLIR_CAPI_EXPORTED void
396mlirGreedyRewriteDriverConfigDestroy(MlirGreedyRewriteDriverConfig config);
397
398/// Sets the maximum number of iterations for the greedy rewrite driver.
399/// Use -1 for no limit.
400MLIR_CAPI_EXPORTED void mlirGreedyRewriteDriverConfigSetMaxIterations(
401 MlirGreedyRewriteDriverConfig config, int64_t maxIterations);
402
403/// Sets the maximum number of rewrites within an iteration.
404/// Use -1 for no limit.
405MLIR_CAPI_EXPORTED void mlirGreedyRewriteDriverConfigSetMaxNumRewrites(
406 MlirGreedyRewriteDriverConfig config, int64_t maxNumRewrites);
407
408/// Sets whether to use top-down traversal for the initial population of the
409/// worklist.
410MLIR_CAPI_EXPORTED void mlirGreedyRewriteDriverConfigSetUseTopDownTraversal(
411 MlirGreedyRewriteDriverConfig config, bool useTopDownTraversal);
412
413/// Enables or disables folding during greedy rewriting.
414MLIR_CAPI_EXPORTED void
415mlirGreedyRewriteDriverConfigEnableFolding(MlirGreedyRewriteDriverConfig config,
416 bool enable);
417
418/// Sets the strictness level for the greedy rewrite driver.
419MLIR_CAPI_EXPORTED void mlirGreedyRewriteDriverConfigSetStrictness(
420 MlirGreedyRewriteDriverConfig config,
421 MlirGreedyRewriteStrictness strictness);
422
423/// Sets the region simplification level.
424MLIR_CAPI_EXPORTED void
425mlirGreedyRewriteDriverConfigSetRegionSimplificationLevel(
426 MlirGreedyRewriteDriverConfig config, MlirGreedySimplifyRegionLevel level);
427
428/// Enables or disables constant CSE.
429MLIR_CAPI_EXPORTED void mlirGreedyRewriteDriverConfigEnableConstantCSE(
430 MlirGreedyRewriteDriverConfig config, bool enable);
431
432/// Gets the maximum number of iterations for the greedy rewrite driver.
433MLIR_CAPI_EXPORTED int64_t mlirGreedyRewriteDriverConfigGetMaxIterations(
434 MlirGreedyRewriteDriverConfig config);
435
436/// Gets the maximum number of rewrites within an iteration.
437MLIR_CAPI_EXPORTED int64_t mlirGreedyRewriteDriverConfigGetMaxNumRewrites(
438 MlirGreedyRewriteDriverConfig config);
439
440/// Gets whether top-down traversal is used for initial worklist population.
441MLIR_CAPI_EXPORTED bool mlirGreedyRewriteDriverConfigGetUseTopDownTraversal(
442 MlirGreedyRewriteDriverConfig config);
443
444/// Gets whether folding is enabled during greedy rewriting.
445MLIR_CAPI_EXPORTED bool mlirGreedyRewriteDriverConfigIsFoldingEnabled(
446 MlirGreedyRewriteDriverConfig config);
447
448/// Gets the strictness level for the greedy rewrite driver.
449MLIR_CAPI_EXPORTED MlirGreedyRewriteStrictness
450mlirGreedyRewriteDriverConfigGetStrictness(
451 MlirGreedyRewriteDriverConfig config);
452
453/// Gets the region simplification level.
454MLIR_CAPI_EXPORTED MlirGreedySimplifyRegionLevel
455mlirGreedyRewriteDriverConfigGetRegionSimplificationLevel(
456 MlirGreedyRewriteDriverConfig config);
457
458/// Gets whether constant CSE is enabled.
459MLIR_CAPI_EXPORTED bool mlirGreedyRewriteDriverConfigIsConstantCSEEnabled(
460 MlirGreedyRewriteDriverConfig config);
461
462/// Applies the given patterns to the given op by a fast walk-based pattern
463/// rewrite driver.
464MLIR_CAPI_EXPORTED void
465mlirWalkAndApplyPatterns(MlirOperation op,
466 MlirFrozenRewritePatternSet patterns);
467
468/// Apply a partial conversion on the given operation.
469MLIR_CAPI_EXPORTED MlirLogicalResult mlirApplyPartialConversion(
470 MlirOperation op, MlirConversionTarget target,
471 MlirFrozenRewritePatternSet patterns, MlirConversionConfig config);
472
473/// Apply a full conversion on the given operation.
474MLIR_CAPI_EXPORTED MlirLogicalResult mlirApplyFullConversion(
475 MlirOperation op, MlirConversionTarget target,
476 MlirFrozenRewritePatternSet patterns, MlirConversionConfig config);
477
478//===----------------------------------------------------------------------===//
479/// ConversionConfig API
480//===----------------------------------------------------------------------===//
481
482/// Create a default ConversionConfig.
483MLIR_CAPI_EXPORTED MlirConversionConfig mlirConversionConfigCreate(void);
484
485/// Destroy the given ConversionConfig.
486MLIR_CAPI_EXPORTED void
487mlirConversionConfigDestroy(MlirConversionConfig config);
488
489typedef enum {
490 MLIR_DIALECT_CONVERSION_FOLDING_MODE_NEVER,
491 MLIR_DIALECT_CONVERSION_FOLDING_MODE_BEFORE_PATTERNS,
492 MLIR_DIALECT_CONVERSION_FOLDING_MODE_AFTER_PATTERNS,
493} MlirDialectConversionFoldingMode;
494
495/// Set the folding mode for the given ConversionConfig.
496MLIR_CAPI_EXPORTED void
497mlirConversionConfigSetFoldingMode(MlirConversionConfig config,
498 MlirDialectConversionFoldingMode mode);
499
500/// Get the folding mode for the given ConversionConfig.
501MLIR_CAPI_EXPORTED MlirDialectConversionFoldingMode
502mlirConversionConfigGetFoldingMode(MlirConversionConfig config);
503
504/// Enable or disable building materializations during conversion.
505MLIR_CAPI_EXPORTED void
506mlirConversionConfigEnableBuildMaterializations(MlirConversionConfig config,
507 bool enable);
508
509/// Check if building materializations during conversion is enabled.
510MLIR_CAPI_EXPORTED bool
511mlirConversionConfigIsBuildMaterializationsEnabled(MlirConversionConfig config);
512
513//===----------------------------------------------------------------------===//
514/// PatternRewriter API
515//===----------------------------------------------------------------------===//
516
517/// Cast the PatternRewriter to a RewriterBase
518MLIR_CAPI_EXPORTED MlirRewriterBase
519mlirPatternRewriterAsBase(MlirPatternRewriter rewriter);
520
521//===----------------------------------------------------------------------===//
522/// ConversionPatternRewriter API
523//===----------------------------------------------------------------------===//
524
525/// Cast the ConversionPatternRewriter to a PatternRewriter
526MLIR_CAPI_EXPORTED MlirPatternRewriter
527mlirConversionPatternRewriterAsPatternRewriter(
528 MlirConversionPatternRewriter rewriter);
529
530/// Apply a signature conversion to each block in the given region.
531MLIR_CAPI_EXPORTED MlirLogicalResult
532mlirConversionPatternRewriterConvertRegionTypes(
533 MlirConversionPatternRewriter rewriter, MlirRegion region,
534 MlirTypeConverter typeConverter);
535
536/// Replace the given operation with multiple value ranges -- one range per
537/// result of `op` -- and erase it. `nRanges` must equal the number of results
538/// of `op`. `rangeSizes[i]` is the number of values in the i-th range, and
539/// `values` is the flat concatenation of all ranges (its length is the sum of
540/// `rangeSizes[0..nRanges)`).
541MLIR_CAPI_EXPORTED void mlirConversionPatternRewriterReplaceOpWithMultiple(
542 MlirConversionPatternRewriter rewriter, MlirOperation op, intptr_t nRanges,
543 intptr_t *rangeSizes, MlirValue *values);
544
545//===----------------------------------------------------------------------===//
546/// ConversionTarget API
547//===----------------------------------------------------------------------===//
548
549/// Create an empty ConversionTarget.
550MLIR_CAPI_EXPORTED MlirConversionTarget
551mlirConversionTargetCreate(MlirContext context);
552
553/// Destroy the given ConversionTarget.
554MLIR_CAPI_EXPORTED void
555mlirConversionTargetDestroy(MlirConversionTarget target);
556
557/// Register the given operations as legal.
558MLIR_CAPI_EXPORTED void
559mlirConversionTargetAddLegalOp(MlirConversionTarget target,
560 MlirStringRef opName);
561
562/// Register the given operations as illegal.
563MLIR_CAPI_EXPORTED void
564mlirConversionTargetAddIllegalOp(MlirConversionTarget target,
565 MlirStringRef opName);
566
567/// Register the operations of the given dialect as legal.
568MLIR_CAPI_EXPORTED void
569mlirConversionTargetAddLegalDialect(MlirConversionTarget target,
570 MlirStringRef dialectName);
571
572/// Register the operations of the given dialect as illegal.
573MLIR_CAPI_EXPORTED void
574mlirConversionTargetAddIllegalDialect(MlirConversionTarget target,
575 MlirStringRef dialectName);
576
577/// Result of a dynamic legality callback.
578typedef enum {
579 /// The operation instance is legal.
580 MLIR_CONVERSION_TARGET_LEGALITY_LEGAL,
581 /// The operation instance is illegal.
582 MLIR_CONVERSION_TARGET_LEGALITY_ILLEGAL,
583 /// The callback has no opinion on this instance. The decision is deferred to
584 /// other registered callbacks (legality callbacks are composed) or, failing
585 /// that, to the operation's static legality action.
586 MLIR_CONVERSION_TARGET_LEGALITY_NO_OPINION
587} MlirConversionTargetLegality;
588
589/// Callback for dynamic legality checks. Returns the legality of the given
590/// operation instance (see MlirConversionTargetLegality).
591typedef MlirConversionTargetLegality (
592 *MlirConversionTargetDynamicLegalityCallback)(MlirOperation op,
593 void *userData);
594
595/// Register the given operation as dynamically legal, with a callback to
596/// determine per-instance legality. The callback must not be NULL.
597MLIR_CAPI_EXPORTED void mlirConversionTargetAddDynamicallyLegalOp(
598 MlirConversionTarget target, MlirStringRef opName,
599 MlirConversionTargetDynamicLegalityCallback callback, void *userData);
600
601/// Register the given dialect as dynamically legal, with a callback to
602/// determine per-instance legality for all operations in the dialect. The
603/// callback must not be NULL.
604MLIR_CAPI_EXPORTED void mlirConversionTargetAddDynamicallyLegalDialect(
605 MlirConversionTarget target, MlirStringRef dialectName,
606 MlirConversionTargetDynamicLegalityCallback callback, void *userData);
607
608/// Mark the given operation as recursively legal. The optional callback (may
609/// be NULL) determines whether a specific instance is recursively legal; a NULL
610/// callback marks the operation as unconditionally recursively legal.
611MLIR_CAPI_EXPORTED void mlirConversionTargetMarkOpRecursivelyLegal(
612 MlirConversionTarget target, MlirStringRef opName,
613 MlirConversionTargetDynamicLegalityCallback callback, void *userData);
614
615/// Mark unknown operations as dynamically legal, with a callback. The callback
616/// must not be NULL.
617MLIR_CAPI_EXPORTED void mlirConversionTargetMarkUnknownOpDynamicallyLegal(
618 MlirConversionTarget target,
619 MlirConversionTargetDynamicLegalityCallback callback, void *userData);
620
621//===----------------------------------------------------------------------===//
622/// TypeConverter API
623//===----------------------------------------------------------------------===//
624
625/// Create a TypeConverter.
626MLIR_CAPI_EXPORTED MlirTypeConverter mlirTypeConverterCreate(void);
627
628/// Destroy the given TypeConverter.
629MLIR_CAPI_EXPORTED void
630mlirTypeConverterDestroy(MlirTypeConverter typeConverter);
631
632/// Outcome of a type conversion callback. Mirrors the three states of the
633/// underlying C++ `std::optional<LogicalResult>` conversion result.
634typedef enum MlirTypeConverterConversionStatus {
635 /// The type was converted successfully.
636 MlirTypeConverterConversionStatusSuccess = 0,
637 /// The conversion failed; no further conversion function will be tried.
638 MlirTypeConverterConversionStatusFailure = 1,
639 /// The conversion was declined; another registered conversion function may be
640 /// tried.
641 MlirTypeConverterConversionStatusDeclined = 2,
642} MlirTypeConverterConversionStatus;
643
644/// Callback type for type conversion functions. On success the callback sets
645/// `*convertedType` to the converted type and returns
646/// MlirTypeConverterConversionStatusSuccess. Returning
647/// MlirTypeConverterConversionStatusDeclined leaves the type unconverted and
648/// allows another registered conversion function to be tried; returning
649/// MlirTypeConverterConversionStatusFailure fails the conversion without trying
650/// any further function.
651typedef MlirTypeConverterConversionStatus (
652 *MlirTypeConverterConversionCallback)(MlirType type,
653 MlirType *convertedType,
654 void *userData);
655
656/// Add a type conversion function to the given TypeConverter.
657MLIR_CAPI_EXPORTED void
658mlirTypeConverterAddConversion(MlirTypeConverter typeConverter,
659 MlirTypeConverterConversionCallback convertType,
660 void *userData);
661
662/// Opaque accumulator for the result types of a 1:N type conversion. It is
663/// passed to a MlirTypeConverter1ToNConversionCallback, which appends converted
664/// types to it via mlirTypeConverterConversionResultsAppend.
665typedef struct MlirTypeConverterConversionResults {
666 void *ptr;
667} MlirTypeConverterConversionResults;
668
669/// Append a converted result type to the given 1:N conversion result
670/// accumulator.
671MLIR_CAPI_EXPORTED void mlirTypeConverterConversionResultsAppend(
672 MlirTypeConverterConversionResults results, MlirType type);
673
674/// Callback type for 1:N type conversion functions. For the given `type`, the
675/// callback appends zero or more converted result types to `results` (via
676/// mlirTypeConverterConversionResultsAppend) and returns a status. On
677/// MlirTypeConverterConversionStatusSuccess the appended types make up the
678/// conversion: appending a single type is a 1:1 conversion, appending several
679/// is a 1:N conversion, and appending none erases the type. Returning
680/// MlirTypeConverterConversionStatusDeclined lets another conversion function
681/// be tried; MlirTypeConverterConversionStatusFailure fails the conversion
682/// without trying another. Any types appended before a non-success status are
683/// discarded.
684typedef MlirTypeConverterConversionStatus (
685 *MlirTypeConverter1ToNConversionCallback)(
686 MlirType type, MlirTypeConverterConversionResults results, void *userData);
687
688/// Add a 1:N type conversion function to the given TypeConverter.
689MLIR_CAPI_EXPORTED void mlirTypeConverterAdd1ToNConversion(
690 MlirTypeConverter typeConverter,
691 MlirTypeConverter1ToNConversionCallback convertType, void *userData);
692
693/// Convert the given type using the given TypeConverter. This is the 1:1
694/// convenience form: it returns the single converted type, or a null MlirType
695/// on failure or if the type converts to anything other than exactly one type
696/// (e.g. a 1:N conversion registered via mlirTypeConverterAdd1ToNConversion, or
697/// an erasure to zero types).
698MLIR_CAPI_EXPORTED MlirType
699mlirTypeConverterConvertType(MlirTypeConverter typeConverter, MlirType type);
700
701/// Callback type for source materializations. Given a builder (passed as a
702/// rewriter), the desired output type, the input values, and a location, the
703/// callback must build a cast-like operation that produces a single value of
704/// `outputType` and return it. Returning a null MlirValue indicates failure, in
705/// which case another registered materialization may be attempted.
706typedef MlirValue (*MlirTypeConverterSourceMaterializationCallback)(
707 MlirRewriterBase rewriter, MlirType outputType, intptr_t nInputs,
708 MlirValue *inputs, MlirLocation loc, void *userData);
709
710/// Callback type for 1:1 target materializations. Behaves like
711/// MlirTypeConverterSourceMaterializationCallback, but additionally receives
712/// `originalType`: the original type of the SSA value being materialized.
713///
714/// Note: This callback is single-output. For the 1:N (multiple-output) form,
715/// use MlirTypeConverter1ToNTargetMaterializationCallback.
716typedef MlirValue (*MlirTypeConverterTargetMaterializationCallback)(
717 MlirRewriterBase rewriter, MlirType outputType, intptr_t nInputs,
718 MlirValue *inputs, MlirLocation loc, MlirType originalType, void *userData);
719
720/// Register a source materialization with the given TypeConverter. This is
721/// invoked when a replacement value must be converted back to its original
722/// source type because some uses persist beyond the main conversion.
723MLIR_CAPI_EXPORTED void mlirTypeConverterAddSourceMaterialization(
724 MlirTypeConverter typeConverter,
725 MlirTypeConverterSourceMaterializationCallback callback, void *userData);
726
727/// Register a target materialization with the given TypeConverter. This is
728/// invoked when a value must be converted to a target type according to a
729/// pattern's type converter.
730MLIR_CAPI_EXPORTED void mlirTypeConverterAddTargetMaterialization(
731 MlirTypeConverter typeConverter,
732 MlirTypeConverterTargetMaterializationCallback callback, void *userData);
733
734/// Callback type for 1:N target materializations. Like
735/// MlirTypeConverterTargetMaterializationCallback, but produces a value for
736/// each of the `nOutputTypes` requested output types instead of a single value.
737/// On success the callback must fill `outputs` -- a caller-allocated array of
738/// length `nOutputTypes` -- with that many non-null values; succeeding while
739/// leaving any entry null asserts. Returning failure signals that this
740/// materialization declined (so another may be attempted); in that case
741/// `outputs` is ignored. `originalType` carries the original type of the value
742/// being materialized and may be a null MlirType.
743typedef MlirLogicalResult (*MlirTypeConverter1ToNTargetMaterializationCallback)(
744 MlirRewriterBase rewriter, intptr_t nOutputTypes, MlirType *outputTypes,
745 intptr_t nInputs, MlirValue *inputs, MlirLocation loc,
746 MlirType originalType, MlirValue *outputs, void *userData);
747
748/// Register a 1:N target materialization with the given TypeConverter.
749MLIR_CAPI_EXPORTED void mlirTypeConverterAdd1ToNTargetMaterialization(
750 MlirTypeConverter typeConverter,
751 MlirTypeConverter1ToNTargetMaterializationCallback callback,
752 void *userData);
753
754//===----------------------------------------------------------------------===//
755/// ConversionPattern API
756//===----------------------------------------------------------------------===//
757
758typedef struct {
759 /// Optional constructor for the user data.
760 /// Set to nullptr to disable it.
761 void (*construct)(void *userData);
762 /// Optional destructor for the user data.
763 /// Set to nullptr to disable it.
764 void (*destruct)(void *userData);
765 /// The callback function to match against code rooted at the specified
766 /// operation, and perform the conversion rewrite if the match is successful,
767 /// corresponding to ConversionPattern::matchAndRewrite.
768 MlirLogicalResult (*matchAndRewrite)(MlirConversionPattern pattern,
769 MlirOperation op, intptr_t nOperands,
770 MlirValue *operands,
771 MlirConversionPatternRewriter rewriter,
772 void *userData);
773 /// Optional callback corresponding to the 1:N
774 /// ConversionPattern::matchAndRewrite(Operation *, ArrayRef<ValueRange>, ...)
775 /// overload, used when one or more operands are remapped to several values
776 /// (e.g. under a 1:N type conversion). `operands` is the flat concatenation
777 /// of all operand ranges; there are `nRanges` ranges (one per original
778 /// operand) and `rangeSizes[i]` is the number of values in the i-th range.
779 /// When this is non-null it takes precedence; when null, the driver falls
780 /// back to the 1:1 `matchAndRewrite` above.
781 MlirLogicalResult (*matchAndRewrite1ToN)(
782 MlirConversionPattern pattern, MlirOperation op, intptr_t nRanges,
783 intptr_t *rangeSizes, intptr_t nOperands, MlirValue *operands,
784 MlirConversionPatternRewriter rewriter, void *userData);
785} MlirConversionPatternCallbacks;
786
787/// Create a conversion pattern that matches the operation with the given
788/// rootName, corresponding to mlir::OpConversionPattern.
789MLIR_CAPI_EXPORTED MlirConversionPattern mlirOpConversionPatternCreate(
790 MlirStringRef rootName, unsigned benefit, MlirContext context,
791 MlirTypeConverter typeConverter, MlirConversionPatternCallbacks callbacks,
792 void *userData, size_t nGeneratedNames, MlirStringRef *generatedNames);
793
794/// Get the type converter used by this conversion pattern.
795MLIR_CAPI_EXPORTED MlirTypeConverter
796mlirConversionPatternGetTypeConverter(MlirConversionPattern pattern);
797
798/// Cast the ConversionPattern to a RewritePattern.
799MLIR_CAPI_EXPORTED MlirRewritePattern
800mlirConversionPatternAsRewritePattern(MlirConversionPattern pattern);
801
802//===----------------------------------------------------------------------===//
803/// RewritePattern API
804//===----------------------------------------------------------------------===//
805
806/// Callbacks to construct a rewrite pattern.
807typedef struct {
808 /// Optional constructor for the user data.
809 /// Set to nullptr to disable it.
810 void (*construct)(void *userData);
811 /// Optional destructor for the user data.
812 /// Set to nullptr to disable it.
813 void (*destruct)(void *userData);
814 /// The callback function to match against code rooted at the specified
815 /// operation, and perform the rewrite if the match is successful,
816 /// corresponding to RewritePattern::matchAndRewrite.
817 MlirLogicalResult (*matchAndRewrite)(MlirRewritePattern pattern,
818 MlirOperation op,
819 MlirPatternRewriter rewriter,
820 void *userData);
821} MlirRewritePatternCallbacks;
822
823/// Create a rewrite pattern that matches the operation
824/// with the given rootName, corresponding to mlir::OpRewritePattern.
825MLIR_CAPI_EXPORTED MlirRewritePattern mlirOpRewritePatternCreate(
826 MlirStringRef rootName, unsigned benefit, MlirContext context,
827 MlirRewritePatternCallbacks callbacks, void *userData,
828 size_t nGeneratedNames, MlirStringRef *generatedNames);
829
830//===----------------------------------------------------------------------===//
831/// RewritePatternSet API
832//===----------------------------------------------------------------------===//
833
834/// Create an empty MlirRewritePatternSet.
835MLIR_CAPI_EXPORTED MlirRewritePatternSet
836mlirRewritePatternSetCreate(MlirContext context);
837
838/// Get the context associated with a MlirRewritePatternSet.
839MLIR_CAPI_EXPORTED MlirContext
840mlirRewritePatternSetGetContext(MlirRewritePatternSet set);
841
842/// Destruct the given MlirRewritePatternSet.
843MLIR_CAPI_EXPORTED void mlirRewritePatternSetDestroy(MlirRewritePatternSet set);
844
845/// Add the given MlirRewritePattern into a MlirRewritePatternSet.
846/// Note that the ownership of the pattern is transferred to the set after this
847/// call.
848MLIR_CAPI_EXPORTED void mlirRewritePatternSetAdd(MlirRewritePatternSet set,
849 MlirRewritePattern pattern);
850
851//===----------------------------------------------------------------------===//
852/// PDLPatternModule API
853//===----------------------------------------------------------------------===//
854
855#if MLIR_ENABLE_PDL_IN_PATTERNMATCH
856DEFINE_C_API_STRUCT(MlirPDLPatternModule, void);
857DEFINE_C_API_STRUCT(MlirPDLValue, const void);
858DEFINE_C_API_STRUCT(MlirPDLResultList, void);
859
860MLIR_CAPI_EXPORTED MlirPDLPatternModule
861mlirPDLPatternModuleFromModule(MlirModule op);
862
863MLIR_CAPI_EXPORTED void mlirPDLPatternModuleDestroy(MlirPDLPatternModule op);
864
865MLIR_CAPI_EXPORTED MlirRewritePatternSet
866mlirRewritePatternSetFromPDLPatternModule(MlirPDLPatternModule op);
867
868/// Cast the MlirPDLValue to an MlirValue.
869/// Return a null value if the cast fails, just like llvm::dyn_cast.
870MLIR_CAPI_EXPORTED MlirValue mlirPDLValueAsValue(MlirPDLValue value);
871
872/// Cast the MlirPDLValue to an MlirType.
873/// Return a null value if the cast fails, just like llvm::dyn_cast.
874MLIR_CAPI_EXPORTED MlirType mlirPDLValueAsType(MlirPDLValue value);
875
876/// Cast the MlirPDLValue to an MlirOperation.
877/// Return a null value if the cast fails, just like llvm::dyn_cast.
878MLIR_CAPI_EXPORTED MlirOperation mlirPDLValueAsOperation(MlirPDLValue value);
879
880/// Cast the MlirPDLValue to an MlirAttribute.
881/// Return a null value if the cast fails, just like llvm::dyn_cast.
882MLIR_CAPI_EXPORTED MlirAttribute mlirPDLValueAsAttribute(MlirPDLValue value);
883
884/// Push the MlirValue into the given MlirPDLResultList.
885MLIR_CAPI_EXPORTED void
886mlirPDLResultListPushBackValue(MlirPDLResultList results, MlirValue value);
887
888/// Push the MlirType into the given MlirPDLResultList.
889MLIR_CAPI_EXPORTED void mlirPDLResultListPushBackType(MlirPDLResultList results,
890 MlirType value);
891
892/// Push the MlirOperation into the given MlirPDLResultList.
893MLIR_CAPI_EXPORTED void
894mlirPDLResultListPushBackOperation(MlirPDLResultList results,
895 MlirOperation value);
896
897/// Push the MlirAttribute into the given MlirPDLResultList.
898MLIR_CAPI_EXPORTED void
899mlirPDLResultListPushBackAttribute(MlirPDLResultList results,
900 MlirAttribute value);
901
902/// This function type is used as callbacks for PDL native rewrite functions.
903/// Input values can be accessed by `values` with its size `nValues`;
904/// output values can be added into `results` by `mlirPDLResultListPushBack*`
905/// APIs. And the return value indicates whether the rewrite succeeds.
906typedef MlirLogicalResult (*MlirPDLRewriteFunction)(
907 MlirPatternRewriter rewriter, MlirPDLResultList results, size_t nValues,
908 MlirPDLValue *values, void *userData);
909
910/// Register a rewrite function into the given PDL pattern module.
911/// `userData` will be provided as an argument to the rewrite function.
912MLIR_CAPI_EXPORTED void mlirPDLPatternModuleRegisterRewriteFunction(
913 MlirPDLPatternModule pdlModule, MlirStringRef name,
914 MlirPDLRewriteFunction rewriteFn, void *userData);
915
916/// This function type is used as callbacks for PDL native constraint functions.
917/// Input values can be accessed by `values` with its size `nValues`;
918/// output values can be added into `results` by `mlirPDLResultListPushBack*`
919/// APIs. And the return value indicates whether the constraint holds.
920typedef MlirLogicalResult (*MlirPDLConstraintFunction)(
921 MlirPatternRewriter rewriter, MlirPDLResultList results, size_t nValues,
922 MlirPDLValue *values, void *userData);
923
924/// Register a constraint function into the given PDL pattern module.
925/// `userData` will be provided as an argument to the constraint function.
926MLIR_CAPI_EXPORTED void mlirPDLPatternModuleRegisterConstraintFunction(
927 MlirPDLPatternModule pdlModule, MlirStringRef name,
928 MlirPDLConstraintFunction constraintFn, void *userData);
929
930#endif // MLIR_ENABLE_PDL_IN_PATTERNMATCH
931
932#undef DEFINE_C_API_STRUCT
933
934#ifdef __cplusplus
935}
936#endif
937
938#endif // MLIR_C_REWRITE_H
939