17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/raw_ostream.h"
28#define GEN_PASS_DEF_MLGOADDREFLECTIONMAPPASS
29#include "mlir/Dialect/EmitC/Transforms/Passes.h.inc"
32constexpr const char *mapLibraryHeader =
"map";
33constexpr const char *stringLibraryHeader =
"string";
36 bool patternApplied =
false;
38 void notifyOperationInserted(
Operation *op,
40 patternApplied =
true;
44IncludeOp addHeader(
OpBuilder &builder, ModuleOp module, StringRef headerName) {
46 return IncludeOp::create(builder, module.getLoc(), includeAttr,
50class MLGOAddReflectionMapPass
51 :
public impl::MLGOAddReflectionMapPassBase<MLGOAddReflectionMapPass> {
52 using MLGOAddReflectionMapPassBase::MLGOAddReflectionMapPassBase;
53 void runOnOperation()
override {
54 mlir::ModuleOp moduleOp = getOperation();
59 PatternMatchListener listener;
64 if (!listener.patternApplied)
68 bool hasMapHdr =
false;
69 bool hasStringHdr =
false;
70 for (
auto &op : *moduleOp.getBody()) {
71 IncludeOp includeOp = llvm::dyn_cast<IncludeOp>(op);
75 if (includeOp.getIsStandardInclude()) {
76 auto include = includeOp.getInclude();
78 hasMapHdr |= include == mapLibraryHeader;
79 hasStringHdr |= include == stringLibraryHeader;
82 if (hasMapHdr && hasStringHdr)
86 mlir::OpBuilder builder(moduleOp.getBody(), moduleOp.getBody()->begin());
88 addHeader(builder, moduleOp, mapLibraryHeader);
91 addHeader(builder, moduleOp, stringLibraryHeader);
144 emitc::OpaqueType entryType =
145 emitc::OpaqueType::get(context,
"std::pair<char*, size_t>");
146 emitc::OpaqueType mapType = emitc::OpaqueType::get(
148 llvm::formatv(
"const std::map<std::string, {0}>", entryType.getValue())
154 std::vector<std::pair<StringRef, StringRef>> fieldNames;
155 classOp.walk([&](FieldOp fieldOp) {
158 dyn_cast_if_present<ArrayAttr>(fieldOp->getDiscardableAttr(attr));
163 if (!arrayAttr.empty() && isa<StringAttr>(arrayAttr[0])) {
164 fieldNames.emplace_back(cast<StringAttr>(arrayAttr[0]).getValue(),
171 if (fieldNames.empty())
175 std::string reflectionMapContents;
176 llvm::raw_string_ostream os(reflectionMapContents);
178 llvm::interleaveComma(fieldNames, os, [&](
const auto &field) {
180 "{ \"{0}\", { reinterpret_cast<char*>(&{1}), sizeof({1}) } }",
181 field.first, field.second);
187 auto funcs = classOp.getBlock().getOps<FuncOp>();
188 auto it = funcs.begin();
189 if (it != funcs.end())
202 FieldOp reflectionMapField = FieldOp::create(
203 rewriter, classOp.getLoc(), rewriter.
getStringAttr(
"reflectionMap"),
204 nullptr, TypeAttr::get(mapType),
205 emitc::OpaqueAttr::get(context, reflectionMapContents));
208 emitc::OpaqueType nameType =
209 emitc::OpaqueType::get(rewriter.
getContext(),
"std::string");
210 emitc::OpaqueType charType =
211 emitc::OpaqueType::get(rewriter.
getContext(),
"char");
212 emitc::PointerType valType =
213 emitc::PointerType::get(rewriter.
getContext(), charType);
214 FuncOp getBufferForNameFunc = FuncOp::create(
215 rewriter, reflectionMapField->getLoc(),
"getBufferForName",
216 FunctionType::get(rewriter.
getContext(), {nameType}, {valType}));
219 rewriter.
createBlock(&getBufferForNameFunc.getBody(), {}, {nameType},
220 {reflectionMapField->getLoc()});
222 GetFieldOp mapField = GetFieldOp::create(
223 rewriter, reflectionMapField->getLoc(), mapType,
"reflectionMap");
225 MemberCallOpaqueOp lookupCall = MemberCallOpaqueOp::create(
226 rewriter, reflectionMapField->getLoc(), entryType, mapField.getResult(),
227 "at", ArrayAttr{}, ArrayAttr{},
ValueRange{nameArg});
229 MemberOp::create(rewriter, reflectionMapField->getLoc(), valType,
230 "first", lookupCall.getResult(0));
231 ReturnOp::create(rewriter, reflectionMapField->getLoc(),
232 bufferPtr.getResult());
Rewrites a emitc::ClassOp to generate a reflection map of member fields and a lookup method.
LogicalResult matchAndRewrite(ClassOp classOp, PatternRewriter &rewriter) const override
MLGOAddReflectionMapClass(MLIRContext *context, llvm::ArrayRef< std::string > includedFieldAttrs)
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
StringAttr getStringAttr(const Twine &bytes)
MLIRContext * getContext() const
MLIRContext is the top-level object for a collection of MLIR operations.
This class represents a saved insertion point.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Operation is the basic unit of execution within MLIR.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
::mlir::Pass::ListOption< std::string > includedFieldAttrs
void populateMLGOAddReflectionMapPatterns(RewritePatternSet &patterns, ArrayRef< std::string > includedFieldAttrs)
Include the generated interface declarations.
void walkAndApplyPatterns(Operation *op, const FrozenRewritePatternSet &patterns, RewriterBase::Listener *listener=nullptr)
A fast walk-based pattern rewrite driver.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})