Emit cast instead of dyn_cast_or_null where attribute is required.
authorJacques Pienaar <jpienaar@google.com>
Fri, 10 May 2019 15:51:34 +0000 (08:51 -0700)
committerMehdi Amini <joker.eph@gmail.com>
Sat, 11 May 2019 02:28:29 +0000 (19:28 -0700)
    If the attribute needs to exist for the validity of the op, then no need to use
    dyn_cast_or_null as the op would be invalid in the cases where cast fails, so
    just use cast.

--

PiperOrigin-RevId: 247617696

mlir/test/mlir-tblgen/attr-enum.td
mlir/test/mlir-tblgen/op-attribute.td
mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp

index 3347165..daf31b0 100644 (file)
@@ -24,7 +24,7 @@ def NS_OpA : NS_Op<"op_a_with_enum_attr", []> {
 // ---
 
 // DEF-LABEL: StringRef OpA::attr()
-// DEF-NEXT:    auto attr = this->getAttr("attr").dyn_cast_or_null<StringAttr>();
+// DEF-NEXT:    auto attr = this->getAttr("attr").cast<StringAttr>();
 // DEF-NEXT:    return attr.getValue();
 
 // DEF-LABEL: OpA::verify()
index e1b4060..0272d0e 100644 (file)
@@ -32,7 +32,7 @@ def AOp : NS_Op<"a_op", []> {
 // ---
 
 // CHECK:      some-return-type AOp::aAttr() {
-// CHECK-NEXT:   auto attr = this->getAttr("aAttr").dyn_cast_or_null<some-attr-kind>();
+// CHECK-NEXT:   auto attr = this->getAttr("aAttr").cast<some-attr-kind>();
 // CHECK-NEXT:   return attr.some-convert-from-storage();
 
 // CHECK:      some-return-type AOp::bAttr() {
index 36464f7..343d61f 100644 (file)
@@ -441,8 +441,12 @@ void OpEmitter::genAttrGetters() {
     // Emit normal emitter.
 
     // Return the queried attribute with the correct return type.
-    auto attrVal = formatv("this->getAttr(\"{0}\").dyn_cast_or_null<{1}>()",
-                           name, attr.getStorageType());
+    auto attrVal =
+        (attr.hasDefaultValueInitializer() || attr.isOptional())
+            ? formatv("this->getAttr(\"{0}\").dyn_cast_or_null<{1}>()", name,
+                      attr.getStorageType())
+            : formatv("this->getAttr(\"{0}\").cast<{1}>()", name,
+                      attr.getStorageType());
     body << "  auto attr = " << attrVal << ";\n";
     if (attr.hasDefaultValueInitializer()) {
       // Returns the default value if not set.