aboutsummaryrefslogtreecommitdiff
path: root/mlir/tools/tblgen-to-irdl/OpDefinitionsGen.cpp
blob: c2ad09ffaaed5b7d0c6bc3267c15bc14648bdc7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//===- OpDefinitionsGen.cpp - IRDL op definitions generator ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// OpDefinitionsGen uses the description of operations to generate IRDL
// definitions for ops.
//
//===----------------------------------------------------------------------===//

#include "mlir/Dialect/IRDL/IR/IRDL.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/TableGen/AttrOrTypeDef.h"
#include "mlir/TableGen/GenInfo.h"
#include "mlir/TableGen/GenNameParser.h"
#include "mlir/TableGen/Interfaces.h"
#include "mlir/TableGen/Operator.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Main.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"

using namespace llvm;
using namespace mlir;
using tblgen::NamedTypeConstraint;

static llvm::cl::OptionCategory dialectGenCat("Options for -gen-irdl-dialect");
static llvm::cl::opt<std::string>
    selectedDialect("dialect", llvm::cl::desc("The dialect to gen for"),
                    llvm::cl::cat(dialectGenCat), llvm::cl::Required);

Value createPredicate(OpBuilder &builder, tblgen::Pred pred) {
  MLIRContext *ctx = builder.getContext();

  if (pred.isCombined()) {
    auto combiner = pred.getDef().getValueAsDef("kind")->getName();
    if (combiner == "PredCombinerAnd" || combiner == "PredCombinerOr") {
      std::vector<Value> constraints;
      for (auto *child : pred.getDef().getValueAsListOfDefs("children")) {
        constraints.push_back(createPredicate(builder, tblgen::Pred(child)));
      }
      if (combiner == "PredCombinerAnd") {
        auto op =
            builder.create<irdl::AllOfOp>(UnknownLoc::get(ctx), constraints);
        return op.getOutput();
      }
      auto op =
          builder.create<irdl::AnyOfOp>(UnknownLoc::get(ctx), constraints);
      return op.getOutput();
    }
  }

  std::string condition = pred.getCondition();
  // Build a CPredOp to match the C constraint built.
  irdl::CPredOp op = builder.create<irdl::CPredOp>(
      UnknownLoc::get(ctx), StringAttr::get(ctx, condition));
  return op;
}

Value typeToConstraint(OpBuilder &builder, Type type) {
  MLIRContext *ctx = builder.getContext();
  auto op =
      builder.create<irdl::IsOp>(UnknownLoc::get(ctx), TypeAttr::get(type));
  return op.getOutput();
}

Value baseToConstraint(OpBuilder &builder, StringRef baseClass) {
  MLIRContext *ctx = builder.getContext();
  auto op = builder.create<irdl::BaseOp>(UnknownLoc::get(ctx),
                                         StringAttr::get(ctx, baseClass));
  return op.getOutput();
}

std::optional<Type> recordToType(MLIRContext *ctx, const Record &predRec) {
  if (predRec.isSubClassOf("I")) {
    auto width = predRec.getValueAsInt("bitwidth");
    return IntegerType::get(ctx, width, IntegerType::Signless);
  }

  if (predRec.isSubClassOf("SI")) {
    auto width = predRec.getValueAsInt("bitwidth");
    return IntegerType::get(ctx, width, IntegerType::Signed);
  }

  if (predRec.isSubClassOf("UI")) {
    auto width = predRec.getValueAsInt("bitwidth");
    return IntegerType::get(ctx, width, IntegerType::Unsigned);
  }

  // Index type
  if (predRec.getName() == "Index") {
    return IndexType::get(ctx);
  }

  // Float types
  if (predRec.isSubClassOf("F")) {
    auto width = predRec.getValueAsInt("bitwidth");
    switch (width) {
    case 16:
      return Float16Type::get(ctx);
    case 32:
      return Float32Type::get(ctx);
    case 64:
      return Float64Type::get(ctx);
    case 80:
      return Float80Type::get(ctx);
    case 128:
      return Float128Type::get(ctx);
    }
  }

  if (predRec.getName() == "NoneType") {
    return NoneType::get(ctx);
  }

  if (predRec.getName() == "BF16") {
    return BFloat16Type::get(ctx);
  }

  if (predRec.getName() == "TF32") {
    return FloatTF32Type::get(ctx);
  }

  if (predRec.getName() == "F8E4M3FN") {
    return Float8E4M3FNType::get(ctx);
  }

  if (predRec.getName() == "F8E5M2") {
    return Float8E5M2Type::get(ctx);
  }

  if (predRec.getName() == "F8E4M3") {
    return Float8E4M3Type::get(ctx);
  }

  if (predRec.getName() == "F8E4M3FNUZ") {
    return Float8E4M3FNUZType::get(ctx);
  }

  if (predRec.getName() == "F8E4M3B11FNUZ") {
    return Float8E4M3B11FNUZType::get(ctx);
  }

  if (predRec.getName() == "F8E5M2FNUZ") {
    return Float8E5M2FNUZType::get(ctx);
  }

  if (predRec.getName() == "F8E3M4") {
    return Float8E3M4Type::get(ctx);
  }

  if (predRec.isSubClassOf("Complex")) {
    const Record *elementRec = predRec.getValueAsDef("elementType");
    auto elementType = recordToType(ctx, *elementRec);
    if (elementType.has_value()) {
      return ComplexType::get(elementType.value());
    }
  }

  return std::nullopt;
}

Value createTypeConstraint(OpBuilder &builder, tblgen::Constraint constraint) {
  MLIRContext *ctx = builder.getContext();
  const Record &predRec = constraint.getDef();

  if (predRec.isSubClassOf("Variadic") || predRec.isSubClassOf("Optional"))
    return createTypeConstraint(builder, predRec.getValueAsDef("baseType"));

  if (predRec.getName() == "AnyType") {
    auto op = builder.create<irdl::AnyOp>(UnknownLoc::get(ctx));
    return op.getOutput();
  }

  if (predRec.isSubClassOf("TypeDef")) {
    auto dialect = predRec.getValueAsDef("dialect")->getValueAsString("name");
    if (dialect == selectedDialect) {
      std::string combined = ("!" + predRec.getValueAsString("mnemonic")).str();
      SmallVector<FlatSymbolRefAttr> nested = {
          SymbolRefAttr::get(ctx, combined)};
      auto typeSymbol = SymbolRefAttr::get(ctx, dialect, nested);
      auto op = builder.create<irdl::BaseOp>(UnknownLoc::get(ctx), typeSymbol);
      return op.getOutput();
    }
    std::string typeName = ("!" + predRec.getValueAsString("typeName")).str();
    auto op = builder.create<irdl::BaseOp>(UnknownLoc::get(ctx),
                                           StringAttr::get(ctx, typeName));
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AnyTypeOf")) {
    std::vector<Value> constraints;
    for (const Record *child : predRec.getValueAsListOfDefs("allowedTypes")) {
      constraints.push_back(
          createTypeConstraint(builder, tblgen::Constraint(child)));
    }
    auto op = builder.create<irdl::AnyOfOp>(UnknownLoc::get(ctx), constraints);
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AllOfType")) {
    std::vector<Value> constraints;
    for (const Record *child : predRec.getValueAsListOfDefs("allowedTypes")) {
      constraints.push_back(
          createTypeConstraint(builder, tblgen::Constraint(child)));
    }
    auto op = builder.create<irdl::AllOfOp>(UnknownLoc::get(ctx), constraints);
    return op.getOutput();
  }

  // Integer types
  if (predRec.getName() == "AnyInteger") {
    auto op = builder.create<irdl::BaseOp>(
        UnknownLoc::get(ctx), StringAttr::get(ctx, "!builtin.integer"));
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AnyI")) {
    auto width = predRec.getValueAsInt("bitwidth");
    std::vector<Value> types = {
        typeToConstraint(builder,
                         IntegerType::get(ctx, width, IntegerType::Signless)),
        typeToConstraint(builder,
                         IntegerType::get(ctx, width, IntegerType::Signed)),
        typeToConstraint(builder,
                         IntegerType::get(ctx, width, IntegerType::Unsigned))};
    auto op = builder.create<irdl::AnyOfOp>(UnknownLoc::get(ctx), types);
    return op.getOutput();
  }

  auto type = recordToType(ctx, predRec);

  if (type.has_value()) {
    return typeToConstraint(builder, type.value());
  }

  // Confined type
  if (predRec.isSubClassOf("ConfinedType")) {
    std::vector<Value> constraints;
    constraints.push_back(createTypeConstraint(
        builder, tblgen::Constraint(predRec.getValueAsDef("baseType"))));
    for (const Record *child : predRec.getValueAsListOfDefs("predicateList")) {
      constraints.push_back(createPredicate(builder, tblgen::Pred(child)));
    }
    auto op = builder.create<irdl::AllOfOp>(UnknownLoc::get(ctx), constraints);
    return op.getOutput();
  }

  return createPredicate(builder, constraint.getPredicate());
}

Value createAttrConstraint(OpBuilder &builder, tblgen::Constraint constraint) {
  MLIRContext *ctx = builder.getContext();
  const Record &predRec = constraint.getDef();

  if (predRec.isSubClassOf("DefaultValuedAttr") ||
      predRec.isSubClassOf("DefaultValuedOptionalAttr") ||
      predRec.isSubClassOf("OptionalAttr")) {
    return createAttrConstraint(builder, predRec.getValueAsDef("baseAttr"));
  }

  if (predRec.isSubClassOf("ConfinedAttr")) {
    std::vector<Value> constraints;
    constraints.push_back(createAttrConstraint(
        builder, tblgen::Constraint(predRec.getValueAsDef("baseAttr"))));
    for (const Record *child :
         predRec.getValueAsListOfDefs("attrConstraints")) {
      constraints.push_back(createPredicate(
          builder, tblgen::Pred(child->getValueAsDef("predicate"))));
    }
    auto op = builder.create<irdl::AllOfOp>(UnknownLoc::get(ctx), constraints);
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AnyAttrOf")) {
    std::vector<Value> constraints;
    for (const Record *child :
         predRec.getValueAsListOfDefs("allowedAttributes")) {
      constraints.push_back(
          createAttrConstraint(builder, tblgen::Constraint(child)));
    }
    auto op = builder.create<irdl::AnyOfOp>(UnknownLoc::get(ctx), constraints);
    return op.getOutput();
  }

  if (predRec.getName() == "AnyAttr") {
    auto op = builder.create<irdl::AnyOp>(UnknownLoc::get(ctx));
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AnyIntegerAttrBase") ||
      predRec.isSubClassOf("SignlessIntegerAttrBase") ||
      predRec.isSubClassOf("SignedIntegerAttrBase") ||
      predRec.isSubClassOf("UnsignedIntegerAttrBase") ||
      predRec.isSubClassOf("BoolAttr")) {
    return baseToConstraint(builder, "!builtin.integer");
  }

  if (predRec.isSubClassOf("FloatAttrBase")) {
    return baseToConstraint(builder, "!builtin.float");
  }

  if (predRec.isSubClassOf("StringBasedAttr")) {
    return baseToConstraint(builder, "!builtin.string");
  }

  if (predRec.getName() == "UnitAttr") {
    auto op =
        builder.create<irdl::IsOp>(UnknownLoc::get(ctx), UnitAttr::get(ctx));
    return op.getOutput();
  }

  if (predRec.isSubClassOf("AttrDef")) {
    auto dialect = predRec.getValueAsDef("dialect")->getValueAsString("name");
    if (dialect == selectedDialect) {
      std::string combined = ("#" + predRec.getValueAsString("mnemonic")).str();
      SmallVector<FlatSymbolRefAttr> nested = {SymbolRefAttr::get(ctx, combined)

      };
      auto typeSymbol = SymbolRefAttr::get(ctx, dialect, nested);
      auto op = builder.create<irdl::BaseOp>(UnknownLoc::get(ctx), typeSymbol);
      return op.getOutput();
    }
    std::string typeName = ("#" + predRec.getValueAsString("attrName")).str();
    auto op = builder.create<irdl::BaseOp>(UnknownLoc::get(ctx),
                                           StringAttr::get(ctx, typeName));
    return op.getOutput();
  }

  return createPredicate(builder, constraint.getPredicate());
}

Value createRegionConstraint(OpBuilder &builder, tblgen::Region constraint) {
  MLIRContext *ctx = builder.getContext();
  const Record &predRec = constraint.getDef();

  if (predRec.getName() == "AnyRegion") {
    ValueRange entryBlockArgs = {};
    auto op =
        builder.create<irdl::RegionOp>(UnknownLoc::get(ctx), entryBlockArgs);
    return op.getResult();
  }

  if (predRec.isSubClassOf("SizedRegion")) {
    ValueRange entryBlockArgs = {};
    auto ty = IntegerType::get(ctx, 32);
    auto op = builder.create<irdl::RegionOp>(
        UnknownLoc::get(ctx), entryBlockArgs,
        IntegerAttr::get(ty, predRec.getValueAsInt("blocks")));
    return op.getResult();
  }

  return createPredicate(builder, constraint.getPredicate());
}

/// Returns the name of the operation without the dialect prefix.
static StringRef getOperatorName(tblgen::Operator &tblgenOp) {
  StringRef opName = tblgenOp.getDef().getValueAsString("opName");
  return opName;
}

/// Returns the name of the type without the dialect prefix.
static StringRef getTypeName(tblgen::TypeDef &tblgenType) {
  StringRef opName = tblgenType.getDef()->getValueAsString("mnemonic");
  return opName;
}

/// Returns the name of the attr without the dialect prefix.
static StringRef getAttrName(tblgen::AttrDef &tblgenType) {
  StringRef opName = tblgenType.getDef()->getValueAsString("mnemonic");
  return opName;
}

/// Extract an operation to IRDL.
irdl::OperationOp createIRDLOperation(OpBuilder &builder,
                                      tblgen::Operator &tblgenOp) {
  MLIRContext *ctx = builder.getContext();
  StringRef opName = getOperatorName(tblgenOp);

  irdl::OperationOp op = builder.create<irdl::OperationOp>(
      UnknownLoc::get(ctx), StringAttr::get(ctx, opName));

  // Add the block in the region.
  Block &opBlock = op.getBody().emplaceBlock();
  OpBuilder consBuilder = OpBuilder::atBlockBegin(&opBlock);

  SmallDenseSet<StringRef> usedNames;
  for (auto &namedCons : tblgenOp.getOperands())
    usedNames.insert(namedCons.name);
  for (auto &namedCons : tblgenOp.getResults())
    usedNames.insert(namedCons.name);
  for (auto &namedReg : tblgenOp.getRegions())
    usedNames.insert(namedReg.name);

  size_t generateCounter = 0;
  auto generateName = [&](StringRef prefix) -> StringAttr {
    SmallString<16> candidate;
    do {
      candidate.clear();
      raw_svector_ostream candidateStream(candidate);
      candidateStream << prefix << generateCounter;
      generateCounter++;
    } while (usedNames.contains(candidate));
    return StringAttr::get(ctx, candidate);
  };
  auto normalizeName = [&](StringRef name) -> StringAttr {
    if (name == "")
      return generateName("unnamed");
    return StringAttr::get(ctx, name);
  };

  auto getValues = [&](tblgen::Operator::const_value_range namedCons) {
    SmallVector<Value> operands;
    SmallVector<Attribute> names;
    SmallVector<irdl::VariadicityAttr> variadicity;

    for (const NamedTypeConstraint &namedCons : namedCons) {
      auto operand = createTypeConstraint(consBuilder, namedCons.constraint);
      operands.push_back(operand);

      names.push_back(normalizeName(namedCons.name));

      irdl::VariadicityAttr var;
      if (namedCons.isOptional())
        var = consBuilder.getAttr<irdl::VariadicityAttr>(
            irdl::Variadicity::optional);
      else if (namedCons.isVariadic())
        var = consBuilder.getAttr<irdl::VariadicityAttr>(
            irdl::Variadicity::variadic);
      else
        var = consBuilder.getAttr<irdl::VariadicityAttr>(
            irdl::Variadicity::single);

      variadicity.push_back(var);
    }
    return std::make_tuple(operands, names, variadicity);
  };

  auto [operands, operandNames, operandVariadicity] =
      getValues(tblgenOp.getOperands());
  auto [results, resultNames, resultVariadicity] =
      getValues(tblgenOp.getResults());

  SmallVector<Value> attributes;
  SmallVector<Attribute> attrNames;
  for (auto namedAttr : tblgenOp.getAttributes()) {
    if (namedAttr.attr.isOptional())
      continue;
    attributes.push_back(createAttrConstraint(consBuilder, namedAttr.attr));
    attrNames.push_back(StringAttr::get(ctx, namedAttr.name));
  }

  SmallVector<Value> regions;
  SmallVector<Attribute> regionNames;
  for (auto namedRegion : tblgenOp.getRegions()) {
    regions.push_back(
        createRegionConstraint(consBuilder, namedRegion.constraint));
    regionNames.push_back(normalizeName(namedRegion.name));
  }

  // Create the operands and results operations.
  if (!operands.empty())
    consBuilder.create<irdl::OperandsOp>(UnknownLoc::get(ctx), operands,
                                         ArrayAttr::get(ctx, operandNames),
                                         operandVariadicity);
  if (!results.empty())
    consBuilder.create<irdl::ResultsOp>(UnknownLoc::get(ctx), results,
                                        ArrayAttr::get(ctx, resultNames),
                                        resultVariadicity);
  if (!attributes.empty())
    consBuilder.create<irdl::AttributesOp>(UnknownLoc::get(ctx), attributes,
                                           ArrayAttr::get(ctx, attrNames));
  if (!regions.empty())
    consBuilder.create<irdl::RegionsOp>(UnknownLoc::get(ctx), regions,
                                        ArrayAttr::get(ctx, regionNames));

  return op;
}

irdl::TypeOp createIRDLType(OpBuilder &builder, tblgen::TypeDef &tblgenType) {
  MLIRContext *ctx = builder.getContext();
  StringRef typeName = getTypeName(tblgenType);
  std::string combined = ("!" + typeName).str();

  irdl::TypeOp op = builder.create<irdl::TypeOp>(
      UnknownLoc::get(ctx), StringAttr::get(ctx, combined));

  op.getBody().emplaceBlock();

  return op;
}

irdl::AttributeOp createIRDLAttr(OpBuilder &builder,
                                 tblgen::AttrDef &tblgenAttr) {
  MLIRContext *ctx = builder.getContext();
  StringRef attrName = getAttrName(tblgenAttr);
  std::string combined = ("#" + attrName).str();

  irdl::AttributeOp op = builder.create<irdl::AttributeOp>(
      UnknownLoc::get(ctx), StringAttr::get(ctx, combined));

  op.getBody().emplaceBlock();

  return op;
}

static irdl::DialectOp createIRDLDialect(OpBuilder &builder) {
  MLIRContext *ctx = builder.getContext();
  return builder.create<irdl::DialectOp>(UnknownLoc::get(ctx),
                                         StringAttr::get(ctx, selectedDialect));
}

static bool emitDialectIRDLDefs(const RecordKeeper &records, raw_ostream &os) {
  // Initialize.
  MLIRContext ctx;
  ctx.getOrLoadDialect<irdl::IRDLDialect>();
  OpBuilder builder(&ctx);

  // Create a module op and set it as the insertion point.
  OwningOpRef<ModuleOp> module =
      builder.create<ModuleOp>(UnknownLoc::get(&ctx));
  builder = builder.atBlockBegin(module->getBody());
  // Create the dialect and insert it.
  irdl::DialectOp dialect = createIRDLDialect(builder);
  // Set insertion point to start of DialectOp.
  builder = builder.atBlockBegin(&dialect.getBody().emplaceBlock());

  for (const Record *type :
       records.getAllDerivedDefinitionsIfDefined("TypeDef")) {
    tblgen::TypeDef tblgenType(type);
    if (tblgenType.getDialect().getName() != selectedDialect)
      continue;
    createIRDLType(builder, tblgenType);
  }

  for (const Record *attr :
       records.getAllDerivedDefinitionsIfDefined("AttrDef")) {
    tblgen::AttrDef tblgenAttr(attr);
    if (tblgenAttr.getDialect().getName() != selectedDialect)
      continue;
    createIRDLAttr(builder, tblgenAttr);
  }

  for (const Record *def : records.getAllDerivedDefinitionsIfDefined("Op")) {
    tblgen::Operator tblgenOp(def);
    if (tblgenOp.getDialectName() != selectedDialect)
      continue;

    createIRDLOperation(builder, tblgenOp);
  }

  // Print the module.
  module->print(os);

  return false;
}

static mlir::GenRegistration
    genOpDefs("gen-dialect-irdl-defs", "Generate IRDL dialect definitions",
              [](const RecordKeeper &records, raw_ostream &os) {
                return emitDialectIRDLDefs(records, os);
              });