Push some operations dynamically in module

Hi,
We are generating an MLIR code for one of our requirements. However, we are currently writing a code that will resolve a single purpose. In our current code, we have a for loop and some conditions. the current code looks like -

func::FuncOp generateMLIR(mlir::MLIRContext &context, mlir::OwningOpRef<mlir::ModuleOp> &module, Location loc)
{
    OpBuilder builder(&context);
    auto funcType = builder.getFunctionType(std::nullopt, std::nullopt);
    auto funcn = builder.create<func::FuncOp>(loc, "main", funcType);
    Block *entryBlock = funcn.addEntryBlock();
    builder.setInsertionPointToEnd(entryBlock);
   ....
   builder.create<scf::ForOp>(loc, lb, ub, step, ValueRange{},
                               [&](OpBuilder &b, Location loc, Value iv, ValueRange args)
                               {
                                b.create<scf::IfOp>(
                                       loc, shipDateGreater,
                                       [&](OpBuilder &b, Location loc)
                                       {
                                           b.create<scf::IfOp>(
                                               loc, shipDateLess,
                                               [&](OpBuilder &b, Location loc)
                                               ...
                                               b.create<scf::YieldOp>(loc);
                                       });
                                   b.create<scf::YieldOp>(loc);
                               });
builder.create<func::ReturnOp>(loc);

    return funcn;
}

However, this code is very static. We want to insert a loop and condition dynamically inside the module. But we are not sure how to do it. Would you please help us with this?

Thanks,
Sudip

You could at least replace the loop body (IfOps) with an emitBody(b, loc) invocation. That should give you give flexibility.

You can see it as a compiler for e.g. C. You lex, parse, analyse the code and then you do codegen into MLIR. Depending on the input source, you will generate different MLIR code.

Thanks @tschuett for your response. We need that exactly. We want to generate the MLIR code based on different sources. Is there any code sample or syntax you can point to in the MLIR codebase?

The Toy tutorial should give you some ideas: