Group constants

Hello,

I need to group all the constants declared in a source function at the beginning of the processed function (so pick them and move them).

Can I do that during lowering ?

Best regards,

Hugo

Hi Hugo,

MLIR is very extensible, for example, there are multiple ops that are function-like and users can define more. So we may need a more context to give you a proper answer. In particular, what do you want to lower and where?

In general, assuming your work with std.constant and std.func it should be possible to implement such transformation by splicing the operations in question to the first basic block. This would be quite awkward to write with the pattern-rewriting (or dialect conversion) infrastructure at the moment, and you should not be needing that infrastructure for this kind of transformation. Be aware that some MLIR operations with IsolatedFromAbove trait do not allow operations in the associated region to reference values defined outside that region. So moving constants out of those regions would be incorrect.

The -canonicalize pass already hoists all constant definitions to the top of the closest surrounding op that has the IsolatedFromAbove trait. (@qaco, this would be the beginning of a function in your case). Try the -canonicalize to see if it’s what you wanted. You could then just call it from anywhere by calling the greedy pattern rewrite driver (provide an empty pattern list if all you are interested in is hoisting constants).

@ftynse

I am trying to implement a dialect in which all the input program is filled in a big one ForLoop, and its constants become the iterArgs of the loop. That’s why I need to move and manipulate constants (std.constant), for the moment inside a single function (std.func), before rewriting anything else.
I am a newbie with MLIR, I think you have noticed that ^^ How can I rewrite a program (“splicing the operations in question to the first basic block”) without using the pattern-rewriting infrastructure ?

@bondhugula
That is great. Which part of MLIR makes this transformation ? I need to learn more about acting globally (vs operations one by one) on the input program, I should read this MLIR part.

I thank both of you very much.

mlir::applyPatternsAndFoldGreedily (it’s what -canonicalize uses). Within that, the hoisting happens as part of FoldUtils::tryToFold.

Then indeed the constant folding performed by the canonicalization pass should be sufficient for your use case. While you can look inside applyPatternsAndFoldGreedily to understand how it works, I don’t think you’ll find yourself interacting with that code directly at this point. I would suggest to read about the pattern rewriting infrastructure (quickstart) in general after following the tutorial. Canonicalization patterns are one example of patterns we use in MLIR.

Thank you very much for all this help.