[clang] [flang] [mlir] [mlir][ODS] Include headers declaring used type and attribute constraints (PR #240449)

Markus Böck via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 9 08:52:34 PST 2026


https://github.com/zero9178 created https://github.com/llvm/llvm-project/pull/240449

#236155 added `cppIncludes` to traits and interfaces so that generated declarations include the headers of the traits they use.

Extend `cppIncludes` to type and attribute constraints. It lists the C++ headers declaring the C++ classes a constraint refers to. A single header is not always enough: e.g. `TypeAttrOf<T>` needs `BuiltinAttributes.h` and the header of `T`. Generated op
declarations now include the headers of the constraints of their operands, results and attributes, and generated attribute and type declarations include the headers of attribute and type parameters.

The builtin type and attribute constraints and the builtin dialect attributes, types and locations set their headers, as do the base classes of dialect attributes and types.

>From c86f3532abb7dfd9e3cecd3988b32a2d7dd37852 Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Mon, 9 Nov 2026 15:24:37 +0000
Subject: [PATCH] [mlir][ODS] Include headers declaring used type and attribute
 constraints

#236155 added `cppIncludes` to traits and interfaces so that generated
declarations include the headers of the traits they use.

Extend `cppIncludes` to type and attribute constraints. It lists the C++
headers declaring the C++ classes a constraint refers to. A single header is
not always enough: e.g. `TypeAttrOf<T>` needs `BuiltinAttributes.h` and the
header of `T`. Generated op
declarations now include the headers of the constraints of their operands,
results and attributes, and generated attribute and type declarations
include the headers of attribute and type parameters.

The builtin type and attribute constraints and the builtin dialect
attributes, types and locations set their headers, as do the base classes of
dialect attributes and types.

Co-authored-by: Claude <noreply at anthropic.com>
---
 .../include/clang/CIR/Dialect/IR/CIRAttrs.td  |  1 +
 .../include/clang/CIR/Dialect/IR/CIRTypes.td  |  1 +
 .../Dialect/CUF/Attributes/CUFAttr.td         |  4 +-
 .../flang/Optimizer/Dialect/FIRAttr.td        |  4 +-
 .../flang/Optimizer/Dialect/FIRTypes.td       |  1 +
 mlir/docs/DefiningDialects/Constraints.md     | 14 +++
 .../include/Standalone/StandaloneTypes.td     |  1 +
 .../mlir/Dialect/AMDGPU/IR/AMDGPUTypes.td     |  1 +
 .../mlir/Dialect/Async/IR/AsyncTypes.td       |  1 +
 .../Dialect/Complex/IR/ComplexAttributes.td   |  1 +
 mlir/include/mlir/Dialect/DLTI/DLTIAttrs.td   |  4 +-
 .../mlir/Dialect/EmitC/IR/EmitCAttributes.td  |  1 +
 .../mlir/Dialect/EmitC/IR/EmitCTypes.td       |  1 +
 mlir/include/mlir/Dialect/GPU/IR/GPUBase.td   |  1 +
 .../include/mlir/Dialect/IRDL/IR/IRDLTypes.td |  1 +
 .../mlir/Dialect/LLVMIR/LLVMAttrDefs.td       |  1 +
 mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.td |  1 +
 mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td   |  1 +
 .../include/mlir/Dialect/LLVMIR/ROCDLAttrs.td |  1 +
 mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td   |  1 +
 .../MLProgram/IR/MLProgramAttributes.td       |  1 +
 .../Dialect/MLProgram/IR/MLProgramTypes.td    |  4 +-
 mlir/include/mlir/Dialect/MPI/IR/MPITypes.td  |  1 +
 .../mlir/Dialect/NVGPU/IR/NVGPUTypes.td       |  1 +
 .../mlir/Dialect/OpenACC/OpenACCOps.td        |  1 +
 .../mlir/Dialect/OpenACC/OpenACCOpsTypes.td   |  1 +
 .../mlir/Dialect/OpenMP/OpenMPAttrDefs.td     |  1 +
 .../mlir/Dialect/OpenMP/OpenMPOpBase.td       |  1 +
 mlir/include/mlir/Dialect/PDL/IR/PDLTypes.td  |  1 +
 .../mlir/Dialect/Ptr/IR/PtrAttrDefs.td        |  1 +
 .../include/mlir/Dialect/Ptr/IR/PtrDialect.td |  1 +
 mlir/include/mlir/Dialect/SMT/IR/SMTTypes.td  |  4 +-
 .../mlir/Dialect/SPIRV/IR/SPIRVAttributes.td  |  1 +
 .../mlir/Dialect/Shape/IR/ShapeBase.td        |  1 +
 .../mlir/Dialect/Shard/IR/ShardBase.td        |  1 +
 .../SparseTensor/IR/SparseTensorAttrDefs.td   |  4 +-
 .../SparseTensor/IR/SparseTensorTypes.td      |  4 +-
 .../mlir/Dialect/Tosa/IR/TosaOpBase.td        |  1 +
 .../mlir/Dialect/Tosa/IR/TosaTypesBase.td     |  1 +
 .../Dialect/Transform/IR/TransformAttrs.td    |  1 +
 mlir/include/mlir/Dialect/UB/IR/UBOps.td      |  1 +
 .../mlir/Dialect/WasmSSA/IR/WasmSSATypes.td   |  1 +
 mlir/include/mlir/Dialect/X86/X86.td          |  1 +
 .../mlir/Dialect/XeGPU/IR/XeGPUAttrs.td       |  1 +
 .../mlir/Dialect/XeGPU/IR/XeGPUTypes.td       |  1 +
 mlir/include/mlir/IR/BuiltinAttributes.td     |  1 +
 .../mlir/IR/BuiltinLocationAttributes.td      |  1 +
 mlir/include/mlir/IR/BuiltinTypes.td          |  1 +
 mlir/include/mlir/IR/CommonAttrConstraints.td | 28 ++++++
 mlir/include/mlir/IR/CommonTypeConstraints.td | 66 ++++++++++---
 mlir/include/mlir/IR/Constraints.td           | 18 +++-
 mlir/include/mlir/TableGen/AttrOrTypeDef.h    |  4 +
 mlir/include/mlir/TableGen/Constraint.h       |  5 +
 mlir/lib/TableGen/AttrOrTypeDef.cpp           |  7 ++
 mlir/lib/TableGen/Constraint.cpp              |  7 ++
 .../mlir-tblgen/constraint-cpp-includes.td    | 96 +++++++++++++++++++
 .../trait-cpp-includes-op-decls.td            |  3 +
 mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp   |  7 +-
 mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp   | 18 +++-
 59 files changed, 316 insertions(+), 25 deletions(-)
 create mode 100644 mlir/test/mlir-tblgen/constraint-cpp-includes.td

diff --git a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
index 2fb7102b0ccf2c..85715890d112eb 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRAttrs.td
@@ -29,6 +29,7 @@ include "clang/CIR/Interfaces/ASTAttrInterfaces.td"
 
 class CIR_Attr<string name, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<CIR_Dialect, name, traits> {
+  let cppIncludes = ["clang/CIR/Dialect/IR/CIRAttrs.h"];
   let mnemonic = attrMnemonic;
   // Setting this to 0 will make the CXXABILowering always consider this
   // attribute 'legal', so that it won't require any transformation. This should
diff --git a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
index b1be62ce056fcf..caacdb2bf8de59 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIRTypes.td
@@ -28,6 +28,7 @@ include "mlir/IR/EnumAttr.td"
 class CIR_Type<string name, string typeMnemonic, list<Trait> traits = [],
                string baseCppClass = "::mlir::Type">
     : TypeDef<CIR_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["clang/CIR/Dialect/IR/CIRTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/flang/include/flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.td b/flang/include/flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.td
index bc56fe1719049d..16fef9b4e65449 100644
--- a/flang/include/flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.td
+++ b/flang/include/flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.td
@@ -16,7 +16,9 @@
 include "flang/Optimizer/Dialect/CUF/CUFDialect.td"
 include "mlir/IR/EnumAttr.td"
 
-class cuf_Attr<string name> : AttrDef<CUFDialect, name>;
+class cuf_Attr<string name> : AttrDef<CUFDialect, name> {
+  let cppIncludes = ["flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.h"];
+}
 
 def cuf_DataAttribute : I32EnumAttr<
     "DataAttribute",
diff --git a/flang/include/flang/Optimizer/Dialect/FIRAttr.td b/flang/include/flang/Optimizer/Dialect/FIRAttr.td
index f6a68079e51ece..d7caf01030dcac 100644
--- a/flang/include/flang/Optimizer/Dialect/FIRAttr.td
+++ b/flang/include/flang/Optimizer/Dialect/FIRAttr.td
@@ -18,7 +18,9 @@ include "mlir/Dialect/OpenACC/OpenACCAttributes.td"
 include "mlir/IR/CommonAttrConstraints.td"
 include "mlir/IR/EnumAttr.td"
 
-class fir_Attr<string name> : AttrDef<FIROpsDialect, name>;
+class fir_Attr<string name> : AttrDef<FIROpsDialect, name> {
+  let cppIncludes = ["flang/Optimizer/Dialect/FIRAttr.h"];
+}
 
 //===----------------------------------------------------------------------===//
 // Linkage
diff --git a/flang/include/flang/Optimizer/Dialect/FIRTypes.td b/flang/include/flang/Optimizer/Dialect/FIRTypes.td
index cc6b92f5171e25..e45d5d6066d18b 100644
--- a/flang/include/flang/Optimizer/Dialect/FIRTypes.td
+++ b/flang/include/flang/Optimizer/Dialect/FIRTypes.td
@@ -25,6 +25,7 @@ include "flang/Optimizer/Dialect/FIRDialect.td"
 class FIR_Type<string name, string typeMnemonic, list<Trait> traits = [],
                string baseCppClass = "::mlir::Type">
     : TypeDef<FIROpsDialect, name, traits, baseCppClass> {
+  let cppIncludes = ["flang/Optimizer/Dialect/FIRType.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/docs/DefiningDialects/Constraints.md b/mlir/docs/DefiningDialects/Constraints.md
index 40863e7aecf4a3..1acb48ada57eee 100644
--- a/mlir/docs/DefiningDialects/Constraints.md
+++ b/mlir/docs/DefiningDialects/Constraints.md
@@ -24,6 +24,20 @@ code is generated for type/attribute constraints. Type constraints can not only
 be used when defining operation arguments, but also when defining type
 parameters.
 
+The C++ headers declaring the C++ classes a type/attribute constraint refers to
+(e.g. the C++ type of a type, or the attribute class and return type of an
+attribute) can be specified in the `cppIncludes` list. ODS then include these
+headers for every constraint used. Type and attribute constraints default to
+`mlir/IR/Types.h` and `mlir/IR/Attributes.h` respectively.
+
+```tablegen
+class MyDialect_Type<string name, string typeMnemonic>
+    : TypeDef<MyDialect, name> {
+  let mnemonic = typeMnemonic;
+  let cppIncludes = ["MyDialect/MyDialectTypes.h"];
+}
+```
+
 Optionally, C++ functions can be generated, so that type/attribute constraints
 can be checked from C++. The name of the C++ function must be specified in the
 `cppFunctionName` field. If no function name is specified, no C++ function is
diff --git a/mlir/examples/standalone/include/Standalone/StandaloneTypes.td b/mlir/examples/standalone/include/Standalone/StandaloneTypes.td
index 05b4c45da476c9..f71b4bcc73695c 100644
--- a/mlir/examples/standalone/include/Standalone/StandaloneTypes.td
+++ b/mlir/examples/standalone/include/Standalone/StandaloneTypes.td
@@ -18,6 +18,7 @@ include "Standalone/StandaloneDialect.td"
 
 class Standalone_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<Standalone_Dialect, name, traits> {
+  let cppIncludes = ["Standalone/StandaloneTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUTypes.td b/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUTypes.td
index 169e6a16b19be0..6632746d0ebc1c 100644
--- a/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUTypes.td
+++ b/mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPUTypes.td
@@ -19,6 +19,7 @@ include "mlir/IR/BuiltinTypeInterfaces.td"
 
 class AMDGPU_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<AMDGPU_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/AMDGPU/IR/AMDGPUDialect.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Async/IR/AsyncTypes.td b/mlir/include/mlir/Dialect/Async/IR/AsyncTypes.td
index a9dced68aae52d..0621bd1c1b06e5 100644
--- a/mlir/include/mlir/Dialect/Async/IR/AsyncTypes.td
+++ b/mlir/include/mlir/Dialect/Async/IR/AsyncTypes.td
@@ -22,6 +22,7 @@ include "mlir/Dialect/Async/IR/AsyncDialect.td"
 
 class Async_Type<string name, string typeMnemonic> : TypeDef<AsyncDialect,
                                                              name> {
+  let cppIncludes = ["mlir/Dialect/Async/IR/AsyncTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.td b/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.td
index a47dc9927dd8ce..b83ef7266bd21f 100644
--- a/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.td
+++ b/mlir/include/mlir/Dialect/Complex/IR/ComplexAttributes.td
@@ -20,6 +20,7 @@ include "mlir/Dialect/Complex/IR/ComplexBase.td"
 class Complex_Attr<string attrName, string attrMnemonic,
                    list<Trait> traits = []>
     : AttrDef<Complex_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/Complex/IR/Complex.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/DLTI/DLTIAttrs.td b/mlir/include/mlir/Dialect/DLTI/DLTIAttrs.td
index 8e16363adf8c33..b33e4fcda52df9 100644
--- a/mlir/include/mlir/Dialect/DLTI/DLTIAttrs.td
+++ b/mlir/include/mlir/Dialect/DLTI/DLTIAttrs.td
@@ -15,7 +15,9 @@ include "mlir/IR/AttrTypeBase.td"
 
 class DLTIAttr<string name, list<Trait> traits = [],
                 string baseCppClass = "::mlir::Attribute">
-    : AttrDef<DLTI_Dialect, name, traits, baseCppClass> { }
+    : AttrDef<DLTI_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/DLTI/DLTI.h"];
+}
 
 //===----------------------------------------------------------------------===//
 // DataLayoutEntryAttr
diff --git a/mlir/include/mlir/Dialect/EmitC/IR/EmitCAttributes.td b/mlir/include/mlir/Dialect/EmitC/IR/EmitCAttributes.td
index 97cbd6aa7af31a..6b1170469d36b4 100644
--- a/mlir/include/mlir/Dialect/EmitC/IR/EmitCAttributes.td
+++ b/mlir/include/mlir/Dialect/EmitC/IR/EmitCAttributes.td
@@ -24,6 +24,7 @@ include "mlir/Dialect/EmitC/IR/EmitCBase.td"
 
 class EmitC_Attr<string name, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<EmitC_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/EmitC/IR/EmitC.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td b/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
index 134ef04f26dd4b..15bee4054f6ed8 100644
--- a/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
+++ b/mlir/include/mlir/Dialect/EmitC/IR/EmitCTypes.td
@@ -33,6 +33,7 @@ def EmitCFloatType : Type<CPred<"emitc::isSupportedFloatType($_self)">,
 
 class EmitC_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<EmitC_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/EmitC/IR/EmitC.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/GPU/IR/GPUBase.td b/mlir/include/mlir/Dialect/GPU/IR/GPUBase.td
index f75d3ae0bd02fa..581678c359e6c5 100644
--- a/mlir/include/mlir/Dialect/GPU/IR/GPUBase.td
+++ b/mlir/include/mlir/Dialect/GPU/IR/GPUBase.td
@@ -242,6 +242,7 @@ def GPU_AsyncOpInterface : OpInterface<"AsyncOpInterface"> {
 
 class GPU_Attr<string attrName, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<GPU_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/GPU/IR/GPUBase.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/IRDL/IR/IRDLTypes.td b/mlir/include/mlir/Dialect/IRDL/IR/IRDLTypes.td
index 9cde433cf33a6f..483e4ed79ac038 100644
--- a/mlir/include/mlir/Dialect/IRDL/IR/IRDLTypes.td
+++ b/mlir/include/mlir/Dialect/IRDL/IR/IRDLTypes.td
@@ -18,6 +18,7 @@ include "mlir/Dialect/IRDL/IR/IRDL.td"
 
 class IRDL_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<IRDL_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/IRDL/IR/IRDL.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
index 2dcc73dc38bfa1..c1222fc6f92993 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMAttrDefs.td
@@ -21,6 +21,7 @@ class LLVM_Attr<string name, string attrMnemonic,
                 list<Trait> traits = [],
                 string baseCppClass = "::mlir::Attribute">
     : AttrDef<LLVM_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/LLVMIR/LLVMAttrs.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.td
index e31323651ceda1..ae6961c18fe43a 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMTypes.td
@@ -18,6 +18,7 @@ include "mlir/Interfaces/MemorySlotInterfaces.td"
 /// Base class for all LLVM dialect types.
 class LLVMType<string typeName, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<LLVM_Dialect, typeName, traits> {
+  let cppIncludes = ["mlir/Dialect/LLVMIR/LLVMTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
index cf3b2e00b82585..f51a18960c6236 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td
@@ -56,6 +56,7 @@ class NVVM_PTXBuilder_Op<string mnemonic, list<Trait> extraTraits = []> :
 
 class NVVM_Attr<string attrName, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<NVVM_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/LLVMIR/NVVMAttributes.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td
index e1de0e861d6e76..c8880818aace0d 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td
@@ -20,6 +20,7 @@ include "mlir/IR/EnumAttr.td"
 
 class ROCDL_Attr<string attrName, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<ROCDL_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/LLVMIR/ROCDLDialect.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td
index 995bb758924c2f..2aa818824db0f4 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td
@@ -41,6 +41,7 @@ def XeVM_Dialect : Dialect {
 
 class XeVM_Attr<string attrName, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<XeVM_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/LLVMIR/XeVMDialect.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.td b/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.td
index 9b0020e985cd25..6325b0433a5aa7 100644
--- a/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.td
+++ b/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramAttributes.td
@@ -16,6 +16,7 @@ include "mlir/Dialect/MLProgram/IR/MLProgramBase.td"
 // Base class for MLProgram dialect attributes.
 class MLProgram_Attr<string name, list<Trait> traits = []>
     : AttrDef<MLProgram_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/MLProgram/IR/MLProgramAttributes.h"];
   let mnemonic = ?;
 }
 
diff --git a/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.td b/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.td
index 1cc5f7f81e8d04..d97070e560aebc 100644
--- a/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.td
+++ b/mlir/include/mlir/Dialect/MLProgram/IR/MLProgramTypes.td
@@ -14,7 +14,9 @@ include "mlir/Dialect/MLProgram/IR/MLProgramBase.td"
 
 class MLProgram_Type<string name, list<Trait> traits = [],
                      string baseCppClass = "::mlir::Type">
-    : TypeDef<MLProgram_Dialect, name, traits, baseCppClass> {}
+    : TypeDef<MLProgram_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/MLProgram/IR/MLProgramTypes.h"];
+}
 
 def MLProgram_TokenType : MLProgram_Type<"Token"> {
   let summary = "Token for establishing execution ordering in a graph";
diff --git a/mlir/include/mlir/Dialect/MPI/IR/MPITypes.td b/mlir/include/mlir/Dialect/MPI/IR/MPITypes.td
index adc35a70b58379..e36033c1cb8e51 100644
--- a/mlir/include/mlir/Dialect/MPI/IR/MPITypes.td
+++ b/mlir/include/mlir/Dialect/MPI/IR/MPITypes.td
@@ -22,6 +22,7 @@ include "mlir/Dialect/MPI/IR/MPI.td"
 
 class MPI_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<MPI_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/MPI/IR/MPI.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.td b/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.td
index 8836a1a9dfcd8c..970c04b4a7b878 100644
--- a/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.td
+++ b/mlir/include/mlir/Dialect/NVGPU/IR/NVGPUTypes.td
@@ -23,6 +23,7 @@ include "mlir/Dialect/NVGPU/IR/NVGPU.td"
 
 class NVGPU_Type<string name, string typeMnemonic,
         list<Trait> traits = []> : TypeDef<NVGPU_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/NVGPU/IR/NVGPUDialect.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.td b/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.td
index 23387bb938e9bb..af58f9fb6e3723 100644
--- a/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.td
+++ b/mlir/include/mlir/Dialect/OpenACC/OpenACCOps.td
@@ -348,6 +348,7 @@ class OpenACC_Attr<string name, string attrMnemonic,
                    list<Trait> traits = [],
                    string baseCppClass = "::mlir::Attribute">
     : AttrDef<OpenACC_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/OpenACC/OpenACC.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.td b/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.td
index e942a49be1fb9e..acc5c6d8aa7c28 100644
--- a/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.td
+++ b/mlir/include/mlir/Dialect/OpenACC/OpenACCOpsTypes.td
@@ -17,6 +17,7 @@ include "mlir/IR/AttrTypeBase.td"
 include "mlir/Dialect/OpenACC/OpenACCBase.td"
 
 class OpenACC_Type<string name, string typeMnemonic> : TypeDef<OpenACC_Dialect, name> {
+  let cppIncludes = ["mlir/Dialect/OpenACC/OpenACC.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPAttrDefs.td b/mlir/include/mlir/Dialect/OpenMP/OpenMPAttrDefs.td
index ebd4d64f22f45f..13fbbea29b6ddd 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPAttrDefs.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPAttrDefs.td
@@ -19,6 +19,7 @@ include "mlir/IR/CommonAttrConstraints.td"
 class OpenMP_Attr<string name, string attrMnemonic, list<Trait> traits = [],
                   string baseCppClass = "::mlir::Attribute">
     : AttrDef<OpenMP_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/OpenMP/OpenMPOpsAttributes.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOpBase.td b/mlir/include/mlir/Dialect/OpenMP/OpenMPOpBase.td
index c1017826ab0c9c..b2b7c895ad1480 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOpBase.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOpBase.td
@@ -25,6 +25,7 @@ include "mlir/IR/OpBase.td"
 
 class OpenMP_Type<string name, string typeMnemonic> :
       TypeDef<OpenMP_Dialect, name> {
+  let cppIncludes = ["mlir/Dialect/OpenMP/OpenMPDialect.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.td b/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.td
index 721668edead62f..83652d91bfae79 100644
--- a/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.td
+++ b/mlir/include/mlir/Dialect/PDL/IR/PDLTypes.td
@@ -22,6 +22,7 @@ include "mlir/Dialect/PDL/IR/PDLDialect.td"
 
 class PDL_Type<string name, string typeMnemonic>
     : TypeDef<PDL_Dialect, name, [], "::mlir::pdl::PDLType"> {
+  let cppIncludes = ["mlir/Dialect/PDL/IR/PDLTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Ptr/IR/PtrAttrDefs.td b/mlir/include/mlir/Dialect/Ptr/IR/PtrAttrDefs.td
index 78006d2dec40df..840a02bd3ad717 100644
--- a/mlir/include/mlir/Dialect/Ptr/IR/PtrAttrDefs.td
+++ b/mlir/include/mlir/Dialect/Ptr/IR/PtrAttrDefs.td
@@ -19,6 +19,7 @@ class Ptr_Attr<string name, string attrMnemonic,
                 list<Trait> traits = [],
                 string baseCppClass = "::mlir::Attribute">
     : AttrDef<Ptr_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/Ptr/IR/PtrAttrs.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Ptr/IR/PtrDialect.td b/mlir/include/mlir/Dialect/Ptr/IR/PtrDialect.td
index c98df5775195ad..6b9c76e4c78e9b 100644
--- a/mlir/include/mlir/Dialect/Ptr/IR/PtrDialect.td
+++ b/mlir/include/mlir/Dialect/Ptr/IR/PtrDialect.td
@@ -44,6 +44,7 @@ def Ptr_Dialect : Dialect {
 
 class Ptr_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<Ptr_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/Ptr/IR/PtrTypes.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/SMT/IR/SMTTypes.td b/mlir/include/mlir/Dialect/SMT/IR/SMTTypes.td
index b22fb0a6e7234c..5ada7f336441d8 100644
--- a/mlir/include/mlir/Dialect/SMT/IR/SMTTypes.td
+++ b/mlir/include/mlir/Dialect/SMT/IR/SMTTypes.td
@@ -12,7 +12,9 @@
 include "mlir/Dialect/SMT/IR/SMTDialect.td"
 include "mlir/IR/AttrTypeBase.td"
 
-class SMTTypeDef<string name> : TypeDef<SMTDialect, name> { }
+class SMTTypeDef<string name> : TypeDef<SMTDialect, name> {
+  let cppIncludes = ["mlir/Dialect/SMT/IR/SMTTypes.h"];
+}
 
 def BoolType : SMTTypeDef<"Bool"> {
   let mnemonic = "bool";
diff --git a/mlir/include/mlir/Dialect/SPIRV/IR/SPIRVAttributes.td b/mlir/include/mlir/Dialect/SPIRV/IR/SPIRVAttributes.td
index 5f5c273b12dec8..58b0644ba1f11f 100644
--- a/mlir/include/mlir/Dialect/SPIRV/IR/SPIRVAttributes.td
+++ b/mlir/include/mlir/Dialect/SPIRV/IR/SPIRVAttributes.td
@@ -25,6 +25,7 @@ include "mlir/Dialect/SPIRV/IR/SPIRVBase.td"
 
 class SPIRV_Attr<string attrName, string attrMnemonic>
     : AttrDef<SPIRV_Dialect, attrName> {
+  let cppIncludes = ["mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Shape/IR/ShapeBase.td b/mlir/include/mlir/Dialect/Shape/IR/ShapeBase.td
index 9c0257954d3e87..fb4af69bf50f34 100644
--- a/mlir/include/mlir/Dialect/Shape/IR/ShapeBase.td
+++ b/mlir/include/mlir/Dialect/Shape/IR/ShapeBase.td
@@ -44,6 +44,7 @@ def ShapeDialect : Dialect {
 }
 
 class Shape_Type<string name, string typeMnemonic> : TypeDef<ShapeDialect, name> {
+  let cppIncludes = ["mlir/Dialect/Shape/IR/Shape.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Shard/IR/ShardBase.td b/mlir/include/mlir/Dialect/Shard/IR/ShardBase.td
index 84c426252f4ab5..0bb0687e6ff6a6 100644
--- a/mlir/include/mlir/Dialect/Shard/IR/ShardBase.td
+++ b/mlir/include/mlir/Dialect/Shard/IR/ShardBase.td
@@ -66,6 +66,7 @@ def Shard_ReductionKindAttr : EnumAttr<Shard_Dialect, Shard_ReductionKind, "part
 class Shard_Type<string name, string typeMnemonic, list<Trait> traits = [],
                    string baseCppClass = "::mlir::Type">
     : TypeDef<Shard_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/Shard/IR/ShardOps.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td b/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td
index b13a9928ae29d4..ba8745cbfd8e48 100644
--- a/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td
+++ b/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td
@@ -18,7 +18,9 @@ include "mlir/IR/TensorEncoding.td"
 // All of the sparse tensor attributes will extend this class.
 class SparseTensor_Attr<string name,
                         list<Trait> traits = []>
-    : AttrDef<SparseTensor_Dialect, name, traits>;
+    : AttrDef<SparseTensor_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/SparseTensor/IR/SparseTensor.h"];
+}
 
 //===----------------------------------------------------------------------===//
 // A simple bitset attribute wrapped around a single int64_t to encode a set of
diff --git a/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.td b/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.td
index 79113d8778743c..56bd915e919071 100644
--- a/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.td
+++ b/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorTypes.td
@@ -19,7 +19,9 @@ include "mlir/Dialect/SparseTensor/IR/SparseTensorBase.td"
 // Base class for Builtin dialect types.
 class SparseTensor_Type<string name, list<Trait> traits = [],
                    string baseCppClass = "::mlir::Type">
-    : TypeDef<SparseTensor_Dialect, name, traits, baseCppClass> {}
+    : TypeDef<SparseTensor_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/SparseTensor/IR/SparseTensor.h"];
+}
 
 //===----------------------------------------------------------------------===//
 // Sparse Tensor Dialect Types.
diff --git a/mlir/include/mlir/Dialect/Tosa/IR/TosaOpBase.td b/mlir/include/mlir/Dialect/Tosa/IR/TosaOpBase.td
index fa0a1dbd60c461..26288cc49cc22f 100644
--- a/mlir/include/mlir/Dialect/Tosa/IR/TosaOpBase.td
+++ b/mlir/include/mlir/Dialect/Tosa/IR/TosaOpBase.td
@@ -61,6 +61,7 @@ def Tosa_Dialect : Dialect {
 
 class Tosa_Attr<string attrName, string attrMnemonic, list<Trait> traits = []>
     : AttrDef<Tosa_Dialect, attrName, traits> {
+  let cppIncludes = ["mlir/Dialect/Tosa/IR/TosaOps.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Tosa/IR/TosaTypesBase.td b/mlir/include/mlir/Dialect/Tosa/IR/TosaTypesBase.td
index deb38ab7de2c3b..b095eed5cff54f 100644
--- a/mlir/include/mlir/Dialect/Tosa/IR/TosaTypesBase.td
+++ b/mlir/include/mlir/Dialect/Tosa/IR/TosaTypesBase.td
@@ -26,6 +26,7 @@ include "mlir/Dialect/Tosa/IR/TosaOpBase.td"
 // The base class for Tosa dialect types.
 class Tosa_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<Tosa_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/Tosa/IR/TosaOps.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/Transform/IR/TransformAttrs.td b/mlir/include/mlir/Dialect/Transform/IR/TransformAttrs.td
index e67a9444c24a8b..9f8343e27a11ac 100644
--- a/mlir/include/mlir/Dialect/Transform/IR/TransformAttrs.td
+++ b/mlir/include/mlir/Dialect/Transform/IR/TransformAttrs.td
@@ -16,6 +16,7 @@ class Transform_Attr<string name, string attrMnemonic,
                      list<Trait> traits = [],
                      string baseCppClass = "::mlir::Attribute">
     : AttrDef<Transform_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/Transform/IR/TransformAttrs.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/UB/IR/UBOps.td b/mlir/include/mlir/Dialect/UB/IR/UBOps.td
index 1bff39add691e8..2c3c9b1b2686c2 100644
--- a/mlir/include/mlir/Dialect/UB/IR/UBOps.td
+++ b/mlir/include/mlir/Dialect/UB/IR/UBOps.td
@@ -25,6 +25,7 @@ def UB_Dialect : Dialect {
 // Base class for UB dialect attributes.
 class UB_Attr<string name, string attrMnemonic, list<Trait> traits = []> :
     AttrDef<UB_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/UB/IR/UBOps.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/WasmSSA/IR/WasmSSATypes.td b/mlir/include/mlir/Dialect/WasmSSA/IR/WasmSSATypes.td
index 4d78836cce75e2..53135f420e3b89 100644
--- a/mlir/include/mlir/Dialect/WasmSSA/IR/WasmSSATypes.td
+++ b/mlir/include/mlir/Dialect/WasmSSA/IR/WasmSSATypes.td
@@ -25,6 +25,7 @@ def WasmSSA_VecType : AnyTypeOf<[I128]>;
 
 class WasmSSA_Type<string name, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<WasmSSA_Dialect, name, traits> {
+  let cppIncludes = ["mlir/Dialect/WasmSSA/IR/WasmSSA.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/X86/X86.td b/mlir/include/mlir/Dialect/X86/X86.td
index 193cbdfc1424ee..39a85366cc4f78 100644
--- a/mlir/include/mlir/Dialect/X86/X86.td
+++ b/mlir/include/mlir/Dialect/X86/X86.td
@@ -692,6 +692,7 @@ def CvtPackedOddIndexedToF32Op
 
 class AMX_Type<string typeName, string typeMnemonic, list<Trait> traits = []>
     : TypeDef<X86_Dialect, "AMX" # typeName, traits> {
+  let cppIncludes = ["mlir/Dialect/X86/X86Dialect.h"];
   let mnemonic = "amx." # typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUAttrs.td b/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUAttrs.td
index 5b4b23348c0632..31cb2d2adaa818 100644
--- a/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUAttrs.td
+++ b/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUAttrs.td
@@ -16,6 +16,7 @@ include "mlir/IR/EnumAttr.td"
 class XeGPUAttr<string name, string attrMnemonic, list<Trait> traits = [],
                 string baseCppClass = "::mlir::Attribute">
     : AttrDef<XeGPU_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/XeGPU/IR/XeGPU.h"];
   let mnemonic = attrMnemonic;
 }
 
diff --git a/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUTypes.td b/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUTypes.td
index ec0e083aa207cd..8d0f7741edd03d 100644
--- a/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUTypes.td
+++ b/mlir/include/mlir/Dialect/XeGPU/IR/XeGPUTypes.td
@@ -39,6 +39,7 @@ def XeGPU_LaneShuffleType
 class XeGPUTypeDef<string name, string typeMnemonic, list<Trait> traits = [],
                    string baseCppClass = "::mlir::Type">
     : TypeDef<XeGPU_Dialect, name, traits, baseCppClass> {
+  let cppIncludes = ["mlir/Dialect/XeGPU/IR/XeGPU.h"];
   let mnemonic = typeMnemonic;
 }
 
diff --git a/mlir/include/mlir/IR/BuiltinAttributes.td b/mlir/include/mlir/IR/BuiltinAttributes.td
index ba2c374a9ab48b..5e2f08c1585894 100644
--- a/mlir/include/mlir/IR/BuiltinAttributes.td
+++ b/mlir/include/mlir/IR/BuiltinAttributes.td
@@ -30,6 +30,7 @@ class Builtin_Attr<string name, string attrMnemonic, list<Trait> traits = [],
     : AttrDef<Builtin_Dialect, name, traits, baseCppClass> {
   let mnemonic = ?;
   let attrName = "builtin." # attrMnemonic;
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/IR/BuiltinLocationAttributes.td b/mlir/include/mlir/IR/BuiltinLocationAttributes.td
index fe4e61100872f2..d9afd92cc363b7 100644
--- a/mlir/include/mlir/IR/BuiltinLocationAttributes.td
+++ b/mlir/include/mlir/IR/BuiltinLocationAttributes.td
@@ -21,6 +21,7 @@ class Builtin_LocationAttr<string name, list<Trait> traits = []>
     : LocationAttrDef<Builtin_Dialect, name, traits> {
   let cppClassName = name;
   let mnemonic = ?;
+  let cppIncludes = ["mlir/IR/Location.h"];
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/IR/BuiltinTypes.td b/mlir/include/mlir/IR/BuiltinTypes.td
index f575b9d68f95a6..f6738529ad422f 100644
--- a/mlir/include/mlir/IR/BuiltinTypes.td
+++ b/mlir/include/mlir/IR/BuiltinTypes.td
@@ -30,6 +30,7 @@ class Builtin_Type<string name, string typeMnemonic, list<Trait> traits = [],
     : TypeDef<Builtin_Dialect, name, traits, baseCppClass> {
   let mnemonic = ?;
   let typeName = "builtin." # typeMnemonic;
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/IR/CommonAttrConstraints.td b/mlir/include/mlir/IR/CommonAttrConstraints.td
index 3ddb0deb14bea7..6925673ca5036d 100644
--- a/mlir/include/mlir/IR/CommonAttrConstraints.td
+++ b/mlir/include/mlir/IR/CommonAttrConstraints.td
@@ -108,6 +108,7 @@ class DefaultValuedAttr<Attr attr, string val> :
   let valueType = attr.valueType;
 
   let baseAttr = attr;
+  let cppIncludes = attr.cppIncludes;
 }
 
 // Decorates an optional attribute to have an (unvalidated) default value
@@ -126,6 +127,7 @@ class DefaultValuedOptionalAttr<Attr attr, string val> :
   let isOptional = 1;
 
   let baseAttr = attr;
+  let cppIncludes = attr.cppIncludes;
 }
 
 // Decorates an attribute as optional. The return type of the generated
@@ -141,6 +143,7 @@ class OptionalAttr<Attr attr> : Attr<attr.predicate, attr.summary> {
   let isOptional = 1;
 
   let baseAttr = attr;
+  let cppIncludes = attr.cppIncludes;
 }
 
 // Default-valued string-based attribute. Wraps the default value in escaped
@@ -162,6 +165,7 @@ class TypedAttrBase<Type attrValType, string attrKind, Pred condition,
   let constBuilderCall = "$_builder.get" # attrKind # "(" #
                          attrValType.builderCall # ", $0)";
   let storageType = "::mlir::" # attrKind;
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let valueType = attrValType;
 }
 
@@ -185,11 +189,13 @@ class AnyAttrOf<list<Attr> allowedAttrs, string summary = "",
     let returnType = cppType;
     let convertFromStorage = fromStorage;
     list<Attr> allowedAttributes = allowedAttrs;
+    let cppIncludes = AllCppIncludes<allowedAttrs>.ret;
 }
 
 def LocationAttr : Attr<CPred<"::llvm::isa<::mlir::LocationAttr>($_self)">,
                         "location attribute"> {
   let storageType = [{ ::mlir::LocationAttr }];
+  let cppIncludes = ["mlir/IR/Location.h"];
   let returnType = [{ ::mlir::Location }];
   let convertFromStorage = "::mlir::Location($_self)";
   let constBuilderCall = "(::mlir::LocationAttr)$0";
@@ -199,12 +205,14 @@ def LocationAttr : Attr<CPred<"::llvm::isa<::mlir::LocationAttr>($_self)">,
 def AnyDistinctAttr : Attr<CPred<"::llvm::isa<::mlir::DistinctAttr>($_self)">,
                            "distinct attribute"> {
   let storageType = "::mlir::DistinctAttr";
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = "::mlir::DistinctAttr";
   let convertFromStorage = "$_self";
 }
 
 def BoolAttr : Attr<CPred<"::llvm::isa<::mlir::BoolAttr>($_self)">, "bool attribute"> {
   let storageType = [{ ::mlir::BoolAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ bool }];
   let valueType = I1;
   let constBuilderCall = "$_builder.getBoolAttr($0)";
@@ -242,6 +250,7 @@ def AnyI64Attr : AnyIntegerAttrBase<AnyI64, "64-bit integer attribute">;
 def APIntAttr : Attr<CPred<"::llvm::isa<::mlir::IntegerAttr>($_self)">,
                      "arbitrary integer attribute"> {
   let storageType = [{ ::mlir::IntegerAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::APInt }];
 }
 
@@ -357,6 +366,7 @@ def BF16Attr : TypedAttrBase<BF16, "FloatAttr",
 class StringBasedAttr<Pred condition, string descr> : Attr<condition, descr> {
   let constBuilderCall = "$_builder.getStringAttr($0)";
   let storageType = [{ ::mlir::StringAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::llvm::StringRef }];
   let valueType = NoneType;
 }
@@ -389,6 +399,7 @@ class TypeAttrBase<string retType, string summary,
                     "::llvm::cast<::mlir::TypeAttr>($_self).getValue()", typePred>]>,
     summary> {
   let storageType = [{ ::mlir::TypeAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = retType;
   let valueType = NoneType;
   let convertFromStorage = "::llvm::cast<" # retType # ">($_self.getValue())";
@@ -402,6 +413,9 @@ class TypeAttrOf<Type ty>
    : TypeAttrBase<ty.cppType, "type attribute of " # ty.summary,
                     ty.predicate> {
   let constBuilderCall = "::mlir::TypeAttr::get($0)";
+  // The accessors return the type stored in the `TypeAttr`.
+  let cppIncludes = !listconcat(["mlir/IR/BuiltinAttributes.h"],
+                               ty.cppIncludes);
 }
 
 // The mere presence of unit attributes has a meaning.  Therefore, unit
@@ -409,6 +423,7 @@ class TypeAttrOf<Type ty>
 // "true" if the attribute is present and "false" otherwise.
 def UnitAttr : Attr<CPred<"::llvm::isa<::mlir::UnitAttr>($_self)">, "unit attribute"> {
   let storageType = [{ ::mlir::UnitAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let constBuilderCall = "(($0) ? $_builder.getUnitAttr() : nullptr)";
   let convertFromStorage = "$_self != nullptr";
   let returnType = "bool";
@@ -424,6 +439,7 @@ def UnitAttr : Attr<CPred<"::llvm::isa<::mlir::UnitAttr>($_self)">, "unit attrib
 class DictionaryAttrBase<Pred condition, string summary> :
     Attr<condition, summary> {
   let storageType = [{ ::mlir::DictionaryAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let constBuilderCall = "$_builder.getDictionaryAttr($0)";
   let returnType = [{ ::mlir::DictionaryAttr }];
   let valueType = NoneType;
@@ -437,6 +453,7 @@ def DictionaryAttr
 class ElementsAttrBase<Pred condition, string summary> :
     Attr<condition, summary> {
   let storageType = [{ ::mlir::ElementsAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributeInterfaces.h"];
   let returnType = [{ ::mlir::ElementsAttr }];
   let convertFromStorage = "$_self";
 }
@@ -449,6 +466,7 @@ class IntElementsAttrBase<Pred condition, string summary> :
                           condition]>,
                      summary> {
   let storageType = [{ ::mlir::DenseIntElementsAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::DenseIntElementsAttr }];
 
   let convertFromStorage = "$_self";
@@ -458,6 +476,7 @@ class DenseArrayAttrBase<string denseAttrName, string cppType, string summaryNam
     ElementsAttrBase<CPred<"::llvm::isa<::mlir::" # denseAttrName # ">($_self)">,
                      summaryName # " dense array attribute"> {
   let storageType = "::mlir::" # denseAttrName;
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = "::llvm::ArrayRef<" # cppType # ">";
   let constBuilderCall = "$_builder.get" # denseAttrName # "($0)";
 }
@@ -531,6 +550,7 @@ class FloatElementsAttr<int width> : ElementsAttrBase<
   width # "-bit float elements attribute"> {
 
   let storageType = [{ ::mlir::DenseElementsAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::DenseElementsAttr }];
 
   // Note that this is only constructing scalar elements attribute.
@@ -556,6 +576,7 @@ class RankedFloatElementsAttr<int width, list<int> dims> : ElementsAttrBase<
   !interleave(dims, ", ") # "]"> {
 
   let storageType = [{ ::mlir::DenseFPElementsAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::DenseFPElementsAttr }];
 
   let constBuilderCall = "::llvm::cast<::mlir::DenseFPElementsAttr>("
@@ -574,6 +595,7 @@ def StringElementsAttr : ElementsAttrBase<
   "string elements attribute"> {
 
   let storageType = [{ ::mlir::DenseElementsAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::DenseElementsAttr }];
 
   let convertFromStorage = "$_self";
@@ -583,6 +605,7 @@ def StringElementsAttr : ElementsAttrBase<
 def AffineMapAttr : Attr<
 CPred<"::llvm::isa<::mlir::AffineMapAttr>($_self)">, "AffineMap attribute"> {
   let storageType = [{::mlir::AffineMapAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h", "mlir/IR/AffineMap.h"];
   let returnType = [{ ::mlir::AffineMap }];
   let valueType = Index;
   let constBuilderCall = "::mlir::AffineMapAttr::get($0)";
@@ -592,6 +615,7 @@ CPred<"::llvm::isa<::mlir::AffineMapAttr>($_self)">, "AffineMap attribute"> {
 def IntegerSetAttr : Attr<
 CPred<"::llvm::isa<::mlir::IntegerSetAttr>($_self)">, "IntegerSet attribute"> {
   let storageType = [{::mlir::IntegerSetAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h", "mlir/IR/IntegerSet.h"];
   let returnType = [{ ::mlir::IntegerSet }];
   let valueType = NoneType;
   let constBuilderCall = "::mlir::IntegerSetAttr::get($0)";
@@ -600,6 +624,7 @@ CPred<"::llvm::isa<::mlir::IntegerSetAttr>($_self)">, "IntegerSet attribute"> {
 // Base class for array attributes.
 class ArrayAttrBase<Pred condition, string summary> : Attr<condition, summary> {
   let storageType = [{ ::mlir::ArrayAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::ArrayAttr }];
   let valueType = NoneType;
   let convertFromStorage = "$_self";
@@ -677,6 +702,7 @@ def DictArrayAttr :
 def SymbolRefAttr : Attr<CPred<"::llvm::isa<::mlir::SymbolRefAttr>($_self)">,
                         "symbol reference attribute"> {
   let storageType = [{ ::mlir::SymbolRefAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::mlir::SymbolRefAttr }];
   let valueType = NoneType;
   let constBuilderCall =
@@ -687,6 +713,7 @@ def SymbolRefAttr : Attr<CPred<"::llvm::isa<::mlir::SymbolRefAttr>($_self)">,
 def FlatSymbolRefAttr : Attr<CPred<"::llvm::isa<::mlir::FlatSymbolRefAttr>($_self)">,
                                    "flat symbol reference attribute"> {
   let storageType = [{ ::mlir::FlatSymbolRefAttr }];
+  let cppIncludes = ["mlir/IR/BuiltinAttributes.h"];
   let returnType = [{ ::llvm::StringRef }];
   let valueType = NoneType;
   let constBuilderCall =
@@ -785,6 +812,7 @@ class ConfinedAttr<Attr attr, list<AttrConstraint> constraints> : Attr<
   let isOptional = attr.isOptional;
 
   let baseAttr = attr;
+  let cppIncludes = attr.cppIncludes;
 
   list<AttrConstraint> attrConstraints = constraints;
 }
diff --git a/mlir/include/mlir/IR/CommonTypeConstraints.td b/mlir/include/mlir/IR/CommonTypeConstraints.td
index 3f550dd86e07c9..7a45d41f425a4a 100644
--- a/mlir/include/mlir/IR/CommonTypeConstraints.td
+++ b/mlir/include/mlir/IR/CommonTypeConstraints.td
@@ -118,6 +118,7 @@ class TypeAlias<Type t, string summary = t.summary> :
     Type<t.predicate, summary, t.cppType> {
   let description = t.description;
   let builderCall = t.builderCall;
+  let cppIncludes = t.cppIncludes;
 }
 
 // A type of a specific dialect.
@@ -133,6 +134,7 @@ class Variadic<Type type> : TypeConstraint<type.predicate,
                                            "variadic of " # type.summary,
                                            type.cppType> {
   Type baseType = type;
+  let cppIncludes = type.cppIncludes;
 }
 
 // A nested variadic type constraint. It expands to zero or more variadic ranges
@@ -150,6 +152,7 @@ class VariadicOfVariadic<Type type, string variadicSegmentAttrName>
 class Optional<Type type> : TypeConstraint<type.predicate, type.summary,
                                            type.cppType> {
   Type baseType = type;
+  let cppIncludes = type.cppIncludes;
 }
 
 // A type that can be constructed using MLIR::Builder.
@@ -180,12 +183,16 @@ def AnyType : Type<Neg<IsTokenTypePred>, "any non-token type">;
 
 // The builtin token type.
 def Token : Type<IsTokenTypePred, "token", "::mlir::TokenType">,
-            BuildableType<"$_builder.getType<::mlir::TokenType>()">;
+            BuildableType<"$_builder.getType<::mlir::TokenType>()"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // None type
 def NoneType : Type<CPred<"::llvm::isa<::mlir::NoneType>($_self)">, "none type",
                     "::mlir::NoneType">,
-      BuildableType<"$_builder.getType<::mlir::NoneType>()">;
+      BuildableType<"$_builder.getType<::mlir::NoneType>()"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any type from the given list
 class AnyTypeOf<list<Type> allowedTypeList, string summary = "",
@@ -197,6 +204,7 @@ class AnyTypeOf<list<Type> allowedTypeList, string summary = "",
         summary),
     cppType> {
   list<Type> allowedTypes = allowedTypeList;
+  let cppIncludes = AllCppIncludes<allowedTypeList>.ret;
 }
 
 // A type that satisfies the constraints of all given types.
@@ -209,6 +217,7 @@ class AllOfType<list<Type> allowedTypeList, string summary = "",
         summary),
     cppType> {
   list<Type> allowedTypes = allowedTypeList;
+  let cppIncludes = AllCppIncludes<allowedTypeList>.ret;
 }
 
 // A type that satisfies additional predicates.
@@ -218,8 +227,13 @@ class ConfinedType<Type type, list<Pred> predicates, string summary = "",
     summary, cppType> {
     Type baseType = type;
     list<Pred> predicateList = predicates;
+    let cppIncludes = type.cppIncludes;
 }
 
+// Constraints on builtin types. The types are declared in the builtin types
+// header.
+let cppIncludes = ["mlir/IR/BuiltinTypes.h"] in {
+
 // Integer types.
 
 // Any integer type irrespective of its width and signedness semantics.
@@ -420,6 +434,8 @@ def FunctionType : Type<CPred<"::llvm::isa<::mlir::FunctionType>($_self)">,
 def GraphType : Type<CPred<"::llvm::isa<::mlir::GraphType>($_self)">,
                               "graph type", "::mlir::GraphType">;
 
+} // cppIncludes = ["mlir/IR/BuiltinTypes.h"]
+
 // A container type is a type that has another type embedded within it.
 class ContainerType<Type etype, Pred containerPred, code elementTypeCall,
                     string descr, string cppType = "::mlir::Type"> :
@@ -439,7 +455,11 @@ class ShapedContainerType<list<Type> allowedTypes,
                 SubstLeaves<"$_self", "elementType",
                 AnyTypeOf<allowedTypes>.predicate>,
                 "; }(::llvm::cast<::mlir::ShapedType>($_self).getElementType())">]>,
-         descr # " of " # AnyTypeOf<allowedTypes>.summary # " values" # summary, cppType>;
+         descr # " of " # AnyTypeOf<allowedTypes>.summary # " values" # summary, cppType> {
+  // Shaped container types with a specific C++ type are builtin types.
+  let cppIncludes = !if(!eq(cppType, "::mlir::Type"), ["mlir/IR/Types.h"],
+                       ["mlir/IR/BuiltinTypes.h"]);
+}
 
 // Whether a shaped type is ranked.
 def HasRankPred : CPred<"::llvm::cast<::mlir::ShapedType>($_self).hasRank()">;
@@ -532,17 +552,23 @@ class IsScalableVectorOfRankPred<list<int> allowedRanks> :
 // Any vector where the rank is from the given `allowedRanks` list
 class VectorOfRank<list<int> allowedRanks> : Type<
   IsVectorOfRankPred<allowedRanks>,
-  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType">;
+  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any fixed-length vector where the rank is from the given `allowedRanks` list
 class FixedVectorOfRank<list<int> allowedRanks> : Type<
   IsFixedVectorOfRankPred<allowedRanks>,
-  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType">;
+  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any scalable vector where the rank is from the given `allowedRanks` list
 class ScalableVectorOfRank<list<int> allowedRanks> : Type<
   IsScalableVectorOfRankPred<allowedRanks>,
-  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType">;
+  " of ranks " # !interleave(allowedRanks, "/"), "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any vector where the rank is from the given `allowedRanks` list and the type
 // is from the given `allowedTypes` list
@@ -642,35 +668,45 @@ class IsVectorOfShape<list<int> shape>
 class VectorOfLength<list<int> allowedLengths> : Type<
   IsVectorOfLengthPred<allowedLengths>,
   " of length " # !interleave(allowedLengths, "/"),
-  "::mlir::VectorType">;
+  "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any vector where the number of elements is more than
 // or equal to minLength.
 class VectorOfMinLength<int minLength> : Type<
   IsVectorOfMinLengthPred<minLength>,
   " of at least length " # minLength,
-  "::mlir::VectorType">;
+  "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any vector where the number of elements is less than
 // or equal to maxLength.
 class VectorOfMaxLength<int maxLength> : Type<
   IsVectorOfMaxLengthPred<maxLength>,
   " of at most length " # maxLength,
-  "::mlir::VectorType">;
+  "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any fixed-length vector where the number of elements is from the given
 // `allowedLengths` list
 class FixedVectorOfLength<list<int> allowedLengths> : Type<
   IsFixedVectorOfLengthPred<allowedLengths>,
   " of length " # !interleave(allowedLengths, "/"),
-  "::mlir::VectorType">;
+  "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any scalable vector where the number of elements is from the given
 // `allowedLengths` list
 class ScalableVectorOfLength<list<int> allowedLengths> : Type<
   IsScalableVectorOfLengthPred<allowedLengths>,
   " of length " # !interleave(allowedLengths, "/"),
-  "::mlir::VectorType">;
+  "::mlir::VectorType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any vector where the number of elements is from the given
 // `allowedLengths` list and the type is from the given `allowedTypes`
@@ -755,7 +791,9 @@ class ScalableVectorOfRankAndLengthAndType<list<int> allowedRanks,
 class ShapedTypeWithNthDimOfSize<int n, list<int> allowedSizes> : Type<
   IsNthDimSizeIsOneOfPred<n, allowedSizes>,
   " with dim " # n # " having a size of {" # !interleave(allowedSizes, ", ") # "}",
-  "::mlir::ShapedType">;
+  "::mlir::ShapedType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // Any scalable vector with a single trailing scalable dimensions, where the
 // size of the trailing dimension is in `allowedTrailingSizes` list, and the
@@ -947,7 +985,9 @@ class StridedMemRefRankOf<list<Type> allowedTypes, list<int> ranks> :
          MemRefOf<allowedTypes>.summary>;
 
 // This represents a generic tuple without any constraints on element type.
-def AnyTuple : Type<IsTupleTypePred, "tuple", "::mlir::TupleType">;
+def AnyTuple : Type<IsTupleTypePred, "tuple", "::mlir::TupleType"> {
+  let cppIncludes = ["mlir/IR/BuiltinTypes.h"];
+}
 
 // A container type that has other types embedded in it, but (unlike
 // ContainerType) can hold elements with a mix of types. Requires a call that
diff --git a/mlir/include/mlir/IR/Constraints.td b/mlir/include/mlir/IR/Constraints.td
index 0d59fffce9df9b..4dce50e7ee0c9b 100644
--- a/mlir/include/mlir/IR/Constraints.td
+++ b/mlir/include/mlir/IR/Constraints.td
@@ -155,6 +155,18 @@ class AttrTypeConstraint<Pred pred, string summary = "",
   // The name of the C++ function that is generated for this constraint.
   // If empty, no C++ function is generated.
   string cppFunctionName = cppFunctionNameParam;
+
+  // The C++ headers declaring the C++ classes this constraint refers to
+  // as written in an `#include` directive. Generated declarations using
+  // this constraint include these headers. Type and attribute constraints
+  // default to the header of `::mlir::Type` and `::mlir::Attribute` respectively.
+  list<string> cppIncludes = [];
+}
+
+// Returns the `cppIncludes` headers of all `constraints`.
+class AllCppIncludes<list<AttrTypeConstraint> constraints> {
+  list<string> ret = !listflatten(!foreach(constraint, constraints,
+                                           constraint.cppIncludes));
 }
 
 // Subclasses used to differentiate different constraint kinds. These are used
@@ -169,12 +181,16 @@ class TypeConstraint<Pred predicate, string summary = "",
     AttrTypeConstraint<predicate, summary, cppFunctionNameParam> {
   // The name of the C++ Type class if known, or Type if not.
   string cppType = cppTypeParam;
+
+  let cppIncludes = ["mlir/IR/Types.h"];
 }
 
 // Subclass for constraints on an attribute.
 class AttrConstraint<Pred predicate, string summary = "",
                      string cppFunctionNameParam = ""> :
-    AttrTypeConstraint<predicate, summary, cppFunctionNameParam>;
+    AttrTypeConstraint<predicate, summary, cppFunctionNameParam> {
+  let cppIncludes = ["mlir/IR/Attributes.h"];
+}
 
 // Subclass for constraints on a property.
 class PropConstraint<Pred predicate, string summary = "", string interfaceTypeParam = ""> :
diff --git a/mlir/include/mlir/TableGen/AttrOrTypeDef.h b/mlir/include/mlir/TableGen/AttrOrTypeDef.h
index 65992f9fef5e95..8ef660c62a4739 100644
--- a/mlir/include/mlir/TableGen/AttrOrTypeDef.h
+++ b/mlir/include/mlir/TableGen/AttrOrTypeDef.h
@@ -87,6 +87,10 @@ class AttrOrTypeParameter {
   /// Get the C++ code to convert from the storage type to the parameter type.
   StringRef getConvertFromStorage() const;
 
+  /// Get the C++ headers declaring the C++ type of this parameter. Only
+  /// parameters that are attribute or type constraints specify headers.
+  std::vector<StringRef> getCppIncludes() const;
+
   /// Get an optional C++ parameter parser.
   std::optional<StringRef> getParser() const;
 
diff --git a/mlir/include/mlir/TableGen/Constraint.h b/mlir/include/mlir/TableGen/Constraint.h
index 641c6b9290856f..c80eac2680a895 100644
--- a/mlir/include/mlir/TableGen/Constraint.h
+++ b/mlir/include/mlir/TableGen/Constraint.h
@@ -17,6 +17,7 @@
 #include "mlir/TableGen/Predicate.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include <vector>
 
 namespace llvm {
 class Record;
@@ -80,6 +81,10 @@ class Constraint {
   /// constraint, or std::nullopt if no C++ function should be generated.
   std::optional<StringRef> getCppFunctionName() const;
 
+  /// Returns the C++ headers declaring the C++ classes this type or attribute
+  /// constraint refers to.
+  std::vector<StringRef> getCppIncludes() const;
+
   Kind getKind() const { return kind; }
 
   /// Return the underlying def.
diff --git a/mlir/lib/TableGen/AttrOrTypeDef.cpp b/mlir/lib/TableGen/AttrOrTypeDef.cpp
index bf835a860cd5b0..eef65b0b4f5875 100644
--- a/mlir/lib/TableGen/AttrOrTypeDef.cpp
+++ b/mlir/lib/TableGen/AttrOrTypeDef.cpp
@@ -320,6 +320,13 @@ StringRef AttrOrTypeParameter::getConvertFromStorage() const {
   return getDefValue<StringInit>("convertFromStorage").value_or("$_self");
 }
 
+std::vector<StringRef> AttrOrTypeParameter::getCppIncludes() const {
+  if (const auto *param = dyn_cast<DefInit>(getDef()))
+    if (param->getDef()->getValue("cppIncludes"))
+      return param->getDef()->getValueAsListOfStrings("cppIncludes");
+  return {};
+}
+
 std::optional<StringRef> AttrOrTypeParameter::getParser() const {
   return getDefValue<StringInit>("parser");
 }
diff --git a/mlir/lib/TableGen/Constraint.cpp b/mlir/lib/TableGen/Constraint.cpp
index ca356a90bf5347..a38b969186d12d 100644
--- a/mlir/lib/TableGen/Constraint.cpp
+++ b/mlir/lib/TableGen/Constraint.cpp
@@ -54,6 +54,13 @@ std::string Constraint::getConditionTemplate() const {
   return getPredicate().getCondition();
 }
 
+std::vector<StringRef> Constraint::getCppIncludes() const {
+  // Only type and attribute constraints have the field.
+  if (!def->getValue("cppIncludes"))
+    return {};
+  return def->getValueAsListOfStrings("cppIncludes");
+}
+
 StringRef Constraint::getSummary() const {
   if (std::optional<StringRef> summary =
           def->getValueAsOptionalString("summary"))
diff --git a/mlir/test/mlir-tblgen/constraint-cpp-includes.td b/mlir/test/mlir-tblgen/constraint-cpp-includes.td
new file mode 100644
index 00000000000000..498fe9f54ff495
--- /dev/null
+++ b/mlir/test/mlir-tblgen/constraint-cpp-includes.td
@@ -0,0 +1,96 @@
+// RUN: mlir-tblgen -gen-op-decls -op-include-regex='^test\.wrappers$' -I %S/../../include %s | FileCheck %s --check-prefix=WRAPPERS
+// RUN: mlir-tblgen -gen-op-decls -op-include-regex='^test\.any_of$' -I %S/../../include %s | FileCheck %s --check-prefix=ANYOF
+// RUN: mlir-tblgen -gen-op-decls -op-include-regex='^test\.attrs$' -I %S/../../include %s | FileCheck %s --check-prefix=ATTRS
+// RUN: mlir-tblgen -gen-attrdef-decls -I %S/../../include %s | FileCheck %s --check-prefix=PARAMS
+
+include "mlir/IR/AttrTypeBase.td"
+include "mlir/IR/OpBase.td"
+
+def Test_Dialect : Dialect {
+  let name = "test";
+  let cppNamespace = "::test";
+}
+
+// Dialect types and attributes set their header in their base class.
+class Test_Type<string name> : TypeDef<Test_Dialect, name> {
+  let cppIncludes = ["test/TestTypes.h"];
+}
+class Test_Attr<string name> : AttrDef<Test_Dialect, name> {
+  let cppIncludes = ["test/TestAttrs.h"];
+}
+
+def Test_FooType : Test_Type<"Foo"> { let mnemonic = "foo"; }
+def Test_FooAttr : Test_Attr<"Foo"> { let mnemonic = "foo"; }
+def Test_OtherType : TypeDef<Test_Dialect, "Other"> {
+  let mnemonic = "other";
+  let cppIncludes = ["test/OtherTypes.h", "test/OtherTypeUtils.h"];
+}
+
+//===----------------------------------------------------------------------===//
+// Ops
+//===----------------------------------------------------------------------===//
+
+// Type constraint wrappers keep the headers of the wrapped constraint.
+
+// WRAPPERS-LABEL: #undef GET_OP_CLASSES
+// WRAPPERS-EMPTY:
+// WRAPPERS-NEXT: #include "mlir/IR/OpDefinition.h"
+// WRAPPERS-NEXT: #include "test/OtherTypeUtils.h"
+// WRAPPERS-NEXT: #include "test/OtherTypes.h"
+// WRAPPERS-NEXT: #include "test/TestTypes.h"
+// WRAPPERS-EMPTY:
+def WrappersOp : Op<Test_Dialect, "wrappers"> {
+  let arguments = (ins Variadic<Test_OtherType>:$others);
+  let results = (outs Optional<Test_FooType>:$foo);
+}
+
+// `AnyTypeOf` keeps the headers of all allowed types.
+
+// ANYOF-LABEL: #undef GET_OP_CLASSES
+// ANYOF-EMPTY:
+// ANYOF-NEXT: #include "mlir/IR/OpDefinition.h"
+// ANYOF-NEXT: #include "test/OtherTypeUtils.h"
+// ANYOF-NEXT: #include "test/OtherTypes.h"
+// ANYOF-NEXT: #include "test/TestTypes.h"
+// ANYOF-EMPTY:
+def AnyOfOp : Op<Test_Dialect, "any_of"> {
+  let arguments = (ins AnyTypeOf<[Test_FooType, Test_OtherType]>:$value);
+}
+
+// Attribute wrappers keep the headers of the wrapped attribute. An attribute
+// needs headers for both its attribute class and its return type, e.g.
+// `AffineMapAttr` and `AffineMap`.
+
+// ATTRS-LABEL: #undef GET_OP_CLASSES
+// ATTRS-EMPTY:
+// ATTRS-NEXT: #include "mlir/Bytecode/BytecodeOpInterface.h"
+// ATTRS-NEXT: #include "mlir/IR/AffineMap.h"
+// ATTRS-NEXT: #include "mlir/IR/BuiltinAttributes.h"
+// ATTRS-NEXT: #include "mlir/IR/OpDefinition.h"
+// ATTRS-NEXT: #include "test/OtherTypeUtils.h"
+// ATTRS-NEXT: #include "test/OtherTypes.h"
+// ATTRS-NEXT: #include "test/TestAttrs.h"
+// ATTRS-EMPTY:
+def AttrsOp : Op<Test_Dialect, "attrs"> {
+  let arguments = (ins OptionalAttr<Test_FooAttr>:$foo,
+                       AffineMapAttr:$map,
+                       TypeAttrOf<Test_OtherType>:$type);
+}
+
+//===----------------------------------------------------------------------===//
+// Attribute and type parameters
+//===----------------------------------------------------------------------===//
+
+// Parameters that are types or attributes include their headers.
+
+// PARAMS-LABEL: #undef GET_ATTRDEF_CLASSES
+// PARAMS-EMPTY:
+// PARAMS-NEXT: #include "mlir/IR/Attributes.h"
+// PARAMS-NEXT: #include "test/OtherTypeUtils.h"
+// PARAMS-NEXT: #include "test/OtherTypes.h"
+// PARAMS-EMPTY:
+def Test_ParamAttr : AttrDef<Test_Dialect, "Param"> {
+  let mnemonic = "param";
+  let parameters = (ins Test_OtherType:$type, "int":$value);
+  let assemblyFormat = "`<` $type `,` $value `>`";
+}
diff --git a/mlir/test/mlir-tblgen/trait-cpp-includes-op-decls.td b/mlir/test/mlir-tblgen/trait-cpp-includes-op-decls.td
index 3ddeed8a7f20f8..94f5d91102ed91 100644
--- a/mlir/test/mlir-tblgen/trait-cpp-includes-op-decls.td
+++ b/mlir/test/mlir-tblgen/trait-cpp-includes-op-decls.td
@@ -50,8 +50,11 @@ def DecoratorEffectInterface
 // CHECK-NEXT: #undef GET_OP_CLASSES
 // CHECK-EMPTY:
 // CHECK-NEXT: #include "mlir/Bytecode/BytecodeOpInterface.h"
+// CHECK-NEXT: #include "mlir/IR/Attributes.h"
+// CHECK-NEXT: #include "mlir/IR/BuiltinAttributes.h"
 // CHECK-NEXT: #include "mlir/IR/OpDefinition.h"
 // CHECK-NEXT: #include "mlir/IR/OpImplementation.h"
+// CHECK-NEXT: #include "mlir/IR/Types.h"
 // CHECK-NEXT: #include "mlir/Interfaces/DerivedAttributeOpInterface.h"
 // CHECK-NEXT: #include "test/BaseOpInterface.h"
 // CHECK-NEXT: #include "test/DeclaredMethodsOpInterface.h"
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index 94081c9dde5fcf..78ddf6ebe98e74 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -196,10 +196,13 @@ DefGen::DefGen(const AttrOrTypeDef &def)
     : def(def), params(def.getParameters()), defCls(def.getCppClassName()),
       valueType(isa<AttrDef>(def) ? "Attribute" : "Type"),
       defType(isa<AttrDef>(def) ? "Attr" : "Type") {
-  // Check that all parameters have names.
-  for (const AttrOrTypeParameter &param : def.getParameters())
+  // Check that all parameters have names and record the headers declaring
+  // their types.
+  for (const AttrOrTypeParameter &param : def.getParameters()) {
     if (param.isAnonymous())
       llvm::PrintFatalError("all parameters must have a name");
+    llvm::append_range(requiredIncludes, param.getCppIncludes());
+  }
 
   // If a storage class is needed, create one.
   if (def.getNumParameters() > 0)
diff --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
index 5eda6ce65c82f2..c205a8cab561d9 100644
--- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
@@ -538,7 +538,7 @@ class OpEmitter {
 
 public:
   // Emits the declaration of `op` to `os` and appends the headers declaring
-  // the traits it uses to `includes`.
+  // the traits and constraints it uses to `includes`.
   static void
   emitDecl(const Operator &op, raw_ostream &os,
            const StaticVerifierFunctionEmitter &staticVerifierEmitter,
@@ -567,6 +567,10 @@ class OpEmitter {
   void addTrait(const tblgen::NativeTrait &trait);
   void addTrait(const tblgen::InterfaceTrait &trait);
 
+  // Records the headers declaring the type and attribute constraints of the
+  // operands, results and attributes as required by the op declaration.
+  void addConstraintIncludes();
+
   // Generate methods for accessing the attribute names of this operation.
   void genAttrNameGetters();
 
@@ -783,7 +787,7 @@ class OpEmitter {
   // avoid duplicates.
   llvm::StringSet<> interfaceUsingNames;
 
-  // The headers declaring the traits added to the op class.
+  // The headers declaring the traits and constraints used by the op class.
   SmallVector<StringRef> requiredIncludes;
 
   // The headers required by the op definition beyond those of the declaration.
@@ -1037,6 +1041,7 @@ OpEmitter::OpEmitter(const Operator &op,
   verifyCtx.addSubst("_ctxt", "this->getOperation()->getContext()");
 
   genTraits();
+  addConstraintIncludes();
 
   // Generate C++ code for various op methods. The order here determines the
   // methods in the generated file.
@@ -1108,6 +1113,15 @@ void OpEmitter::addTrait(const tblgen::InterfaceTrait &trait) {
   addTrait(trait.getFullyQualifiedTraitName(), trait.getCppIncludes());
 }
 
+void OpEmitter::addConstraintIncludes() {
+  for (const NamedTypeConstraint &operand : op.getOperands())
+    llvm::append_range(requiredIncludes, operand.constraint.getCppIncludes());
+  for (const NamedTypeConstraint &result : op.getResults())
+    llvm::append_range(requiredIncludes, result.constraint.getCppIncludes());
+  for (const NamedAttribute &namedAttr : op.getAttributes())
+    llvm::append_range(requiredIncludes, namedAttr.attr.getCppIncludes());
+}
+
 static void errorIfPruned(size_t line, Method *m, const Twine &methodName,
                           const Operator &op) {
   if (m)



More information about the cfe-commits mailing list