Skip to content

Commit 7985fcc

Browse files
committed
emitc: Add fmtArgs to verbatim
Allows to print code snippets that refer to arguments or local variables. E.g. `emitc.verbatim "#pragma abc var={}" args %arg0 : !emitc.ptr<i32>` is printed as `#pragma abc var=v1` when the translater had decided to print `%arg0` as `v1`. As a follow-up PR, we will use the same infra to extend opaque type, which provides a way to generate template types depending on the spelling of other types.
1 parent e899930 commit 7985fcc

File tree

7 files changed

+239
-5
lines changed

7 files changed

+239
-5
lines changed

mlir/include/mlir/Dialect/EmitC/IR/EmitC.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
#include "mlir/Dialect/EmitC/IR/EmitCDialect.h.inc"
2828
#include "mlir/Dialect/EmitC/IR/EmitCEnums.h.inc"
2929

30+
#include <variant>
31+
3032
namespace mlir {
3133
namespace emitc {
3234
void buildTerminatedBody(OpBuilder &builder, Location loc);
@@ -47,6 +49,10 @@ bool isSupportedFloatType(mlir::Type type);
4749
/// Determines whether \p type is a emitc.size_t/ssize_t type.
4850
bool isPointerWideType(mlir::Type type);
4951

52+
// Either a literal string, or an placeholder for the fmtArgs.
53+
struct Placeholder {};
54+
using ReplacementItem = std::variant<StringRef, Placeholder>;
55+
5056
} // namespace emitc
5157
} // namespace mlir
5258

mlir/include/mlir/Dialect/EmitC/IR/EmitC.td

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,10 +1198,29 @@ def EmitC_VerbatimOp : EmitC_Op<"verbatim"> {
11981198
}
11991199
#endif
12001200
```
1201+
1202+
If the `emitc.verbatim` op has operands, then the `value` is interpreted as
1203+
format string, where `{}` is a placeholder for an operand in their order.
1204+
For example, `emitc.verbatim "#pragma my src={} dst={}" %src, %dest : i32, i32`
1205+
would be emitted as `#pragma my src=a dst=b` if `%src` became `a` and
1206+
`%dest` became `b` in the C code.
1207+
`{{` in the format string is interpreted as a single `{` and doesn't introduce
1208+
a placeholder.
12011209
}];
12021210

1203-
let arguments = (ins StrAttr:$value);
1204-
let assemblyFormat = "$value attr-dict";
1211+
let extraClassDeclaration = [{
1212+
FailureOr<SmallVector<::mlir::emitc::ReplacementItem>> parseFormatString();
1213+
}];
1214+
1215+
let arguments = (ins StrAttr:$value, Variadic<EmitCType>:$fmtArgs);
1216+
1217+
let builders = [OpBuilder<(ins "::mlir::StringAttr":$value),
1218+
[{ build($_builder, $_state, value, {}); }]>];
1219+
let builders = [OpBuilder<(ins "::llvm::StringRef":$value),
1220+
[{ build($_builder, $_state, value, {}); }]>];
1221+
let hasVerifier = 1;
1222+
let assemblyFormat =
1223+
"$value (`args` $fmtArgs^ `:` type($fmtArgs))? attr-dict";
12051224
}
12061225

12071226
def EmitC_AssignOp : EmitC_Op<"assign", []> {

mlir/lib/Dialect/EmitC/IR/EmitC.cpp

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include "llvm/ADT/StringExtras.h"
2020
#include "llvm/ADT/TypeSwitch.h"
2121
#include "llvm/Support/Casting.h"
22+
#include "llvm/Support/FormatVariadic.h"
2223

2324
using namespace mlir;
2425
using namespace mlir::emitc;
@@ -167,6 +168,64 @@ static LogicalResult verifyInitializationAttribute(Operation *op,
167168
return success();
168169
}
169170

171+
/// Parse a format string and return a list of its parts.
172+
/// A part is either a StringRef that has to be printed as-is, or
173+
/// a Placeholder which requires printing the next operand of the VerbatimOp.
174+
/// In the format string, all `{}` are replaced by Placeholders, except if the
175+
/// `{` is escaped by `{{` - then it doesn't start a placeholder.
176+
template <class ArgType>
177+
FailureOr<SmallVector<ReplacementItem>>
178+
parseFormatString(StringRef toParse, ArgType fmtArgs,
179+
std::optional<llvm::function_ref<mlir::InFlightDiagnostic()>>
180+
emitError = {}) {
181+
SmallVector<ReplacementItem> items;
182+
183+
// If there are not operands, the format string is not interpreted.
184+
if (fmtArgs.empty()) {
185+
items.push_back(toParse);
186+
return items;
187+
}
188+
189+
while (!toParse.empty()) {
190+
size_t idx = toParse.find('{');
191+
if (idx == StringRef::npos) {
192+
// No '{'
193+
items.push_back(toParse);
194+
break;
195+
}
196+
if (idx > 0) {
197+
// Take all chars excluding the '{'.
198+
items.push_back(toParse.take_front(idx));
199+
toParse = toParse.drop_front(idx);
200+
continue;
201+
}
202+
if (toParse.size() < 2) {
203+
// '{' is last character
204+
items.push_back(toParse);
205+
break;
206+
}
207+
// toParse contains at least two characters and starts with `{`.
208+
char nextChar = toParse[1];
209+
if (nextChar == '{') {
210+
// Double '{{' -> '{' (escaping).
211+
items.push_back(toParse.take_front(1));
212+
toParse = toParse.drop_front(2);
213+
continue;
214+
}
215+
if (nextChar == '}') {
216+
items.push_back(Placeholder{});
217+
toParse = toParse.drop_front(2);
218+
continue;
219+
}
220+
221+
if (emitError.has_value()) {
222+
return (*emitError)() << "expected '}' after unescaped '{'";
223+
}
224+
return failure();
225+
}
226+
return items;
227+
}
228+
170229
//===----------------------------------------------------------------------===//
171230
// AddOp
172231
//===----------------------------------------------------------------------===//
@@ -909,6 +968,55 @@ LogicalResult emitc::SubscriptOp::verify() {
909968
return success();
910969
}
911970

971+
//===----------------------------------------------------------------------===//
972+
// VerbatimOp
973+
//===----------------------------------------------------------------------===//
974+
975+
LogicalResult emitc::VerbatimOp::verify() {
976+
auto errorCallback = [&]() -> InFlightDiagnostic {
977+
return this->emitOpError();
978+
};
979+
FailureOr<SmallVector<ReplacementItem>> fmt =
980+
::parseFormatString(getValue(), getFmtArgs(), errorCallback);
981+
if (failed(fmt))
982+
return failure();
983+
984+
size_t numPlaceholders = llvm::count_if(*fmt, [](ReplacementItem &item) {
985+
return std::holds_alternative<Placeholder>(item);
986+
});
987+
988+
if (numPlaceholders != getFmtArgs().size()) {
989+
return emitOpError()
990+
<< "requires operands for each placeholder in the format string";
991+
}
992+
return success();
993+
}
994+
995+
static ParseResult parseVariadicTypeFmtArgs(AsmParser &p,
996+
SmallVector<Type> &params) {
997+
Type type;
998+
if (p.parseType(type))
999+
return failure();
1000+
1001+
params.push_back(type);
1002+
while (succeeded(p.parseOptionalComma())) {
1003+
if (p.parseType(type))
1004+
return failure();
1005+
params.push_back(type);
1006+
}
1007+
1008+
return success();
1009+
}
1010+
1011+
static void printVariadicTypeFmtArgs(AsmPrinter &p, ArrayRef<Type> params) {
1012+
llvm::interleaveComma(params, p, [&](Type type) { p.printType(type); });
1013+
}
1014+
1015+
FailureOr<SmallVector<ReplacementItem>> emitc::VerbatimOp::parseFormatString() {
1016+
// Error checking is done in verify.
1017+
return ::parseFormatString(getValue(), getFmtArgs());
1018+
}
1019+
9121020
//===----------------------------------------------------------------------===//
9131021
// EmitC Enums
9141022
//===----------------------------------------------------------------------===//

mlir/lib/Target/Cpp/TranslateToCpp.cpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,21 @@ static LogicalResult printOperation(CppEmitter &emitter,
556556
emitc::VerbatimOp verbatimOp) {
557557
raw_ostream &os = emitter.ostream();
558558

559-
os << verbatimOp.getValue();
559+
FailureOr<SmallVector<ReplacementItem>> items =
560+
verbatimOp.parseFormatString();
561+
if (failed(items))
562+
return failure();
563+
564+
auto fmtArg = verbatimOp.getFmtArgs().begin();
565+
566+
for (ReplacementItem &item : *items) {
567+
if (auto *str = std::get_if<StringRef>(&item)) {
568+
os << *str;
569+
} else {
570+
if (failed(emitter.emitOperand(*fmtArg++)))
571+
return failure();
572+
}
573+
}
560574

561575
return success();
562576
}

mlir/test/Dialect/EmitC/invalid_ops.mlir

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,3 +566,51 @@ func.func @emitc_switch() {
566566
}
567567
return
568568
}
569+
570+
// -----
571+
572+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
573+
// expected-error @+1 {{'emitc.verbatim' op requires operands for each placeholder in the format string}}
574+
emitc.verbatim "" args %arg0, %arg1 : !emitc.ptr<i32>, i32
575+
return
576+
}
577+
578+
// -----
579+
580+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
581+
// expected-error @+1 {{'emitc.verbatim' op requires operands for each placeholder in the format string}}
582+
emitc.verbatim "abc" args %arg0, %arg1 : !emitc.ptr<i32>, i32
583+
return
584+
}
585+
586+
// -----
587+
588+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
589+
// expected-error @+1 {{'emitc.verbatim' op requires operands for each placeholder in the format string}}
590+
emitc.verbatim "{}" args %arg0, %arg1 : !emitc.ptr<i32>, i32
591+
return
592+
}
593+
594+
// -----
595+
596+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
597+
// expected-error @+1 {{'emitc.verbatim' op requires operands for each placeholder in the format string}}
598+
emitc.verbatim "{} {} {}" args %arg0, %arg1 : !emitc.ptr<i32>, i32
599+
return
600+
}
601+
602+
// -----
603+
604+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
605+
// expected-error @+1 {{'emitc.verbatim' op expected '}' after unescaped '{'}}
606+
emitc.verbatim "{ " args %arg0, %arg1 : !emitc.ptr<i32>, i32
607+
return
608+
}
609+
610+
// -----
611+
612+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
613+
// expected-error @+1 {{'emitc.verbatim' op expected '}' after unescaped '{'}}
614+
emitc.verbatim "{a} " args %arg0, %arg1 : !emitc.ptr<i32>, i32
615+
return
616+
}

mlir/test/Dialect/EmitC/ops.mlir

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,21 @@ emitc.verbatim "#endif // __cplusplus"
238238
emitc.verbatim "typedef int32_t i32;"
239239
emitc.verbatim "typedef float f32;"
240240

241+
// The value is not interpreted as format string if there are no operands.
242+
emitc.verbatim "{} { }"
243+
244+
func.func @test_verbatim(%arg0 : !emitc.ptr<i32>, %arg1 : i32) {
245+
emitc.verbatim "{} + {};" args %arg0, %arg1 : !emitc.ptr<i32>, i32
246+
247+
// Trailing '{' are ok and don't start a placeholder.
248+
emitc.verbatim "{} + {} {" args %arg0, %arg1 : !emitc.ptr<i32>, i32
249+
250+
// Check there is no ambiguity whether %a is the argument to the emitc.verbatim op.
251+
emitc.verbatim "a"
252+
%a = "emitc.constant"(){value = 42 : i32} : () -> i32
253+
254+
return
255+
}
241256

242257
emitc.global @uninit : i32
243258
emitc.global @myglobal_int : i32 = 4

mlir/test/Target/Cpp/verbatim.mlir

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s
2-
// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s
1+
// RUN: mlir-translate -mlir-to-cpp %s | FileCheck %s --match-full-lines
2+
// RUN: mlir-translate -mlir-to-cpp -declare-variables-at-top %s | FileCheck %s --match-full-lines
33

44

55
emitc.verbatim "#ifdef __cplusplus"
@@ -19,3 +19,27 @@ emitc.verbatim "typedef int32_t i32;"
1919
// CHECK-NEXT: typedef int32_t i32;
2020
emitc.verbatim "typedef float f32;"
2121
// CHECK-NEXT: typedef float f32;
22+
23+
emitc.func @func(%arg: f32) {
24+
// CHECK: void func(float [[V0:[^ ]*]]) {
25+
%a = "emitc.variable"(){value = #emitc.opaque<"">} : () -> !emitc.array<3x7xi32>
26+
// CHECK: int32_t [[A:[^ ]*]][3][7];
27+
28+
emitc.verbatim "{}" args %arg : f32
29+
// CHECK: [[V0]]
30+
31+
emitc.verbatim "{} {{a" args %arg : f32
32+
// CHECK-NEXT: [[V0]] {a
33+
34+
emitc.verbatim "#pragma my var={} property" args %arg : f32
35+
// CHECK-NEXT: #pragma my var=[[V0]] property
36+
37+
// Trailing '{' are printed as-is.
38+
emitc.verbatim "#pragma my var={} {" args %arg : f32
39+
// CHECK-NEXT: #pragma my var=[[V0]] {
40+
41+
emitc.verbatim "#pragma my2 var={} property" args %a : !emitc.array<3x7xi32>
42+
// CHECK-NEXT: #pragma my2 var=[[A]] property
43+
44+
emitc.return
45+
}

0 commit comments

Comments
 (0)