[flang-commits] [flang] bb1d976 - [mlir][flang] use OpBuilder& instead of Builder* in <Op>::build methods

Alex Zinenko via flang-commits flang-commits at lists.llvm.org
Tue Apr 28 01:42:17 PDT 2020


Author: Alex Zinenko
Date: 2020-04-28T10:42:08+02:00
New Revision: bb1d976febf25e272a9f7ae51974207232481e3e

URL: https://github.com/llvm/llvm-project/commit/bb1d976febf25e272a9f7ae51974207232481e3e
DIFF: https://github.com/llvm/llvm-project/commit/bb1d976febf25e272a9f7ae51974207232481e3e.diff

LOG: [mlir][flang] use OpBuilder& instead of Builder* in <Op>::build methods

As we start defining more complex Ops, we increasingly see the need for
Ops-with-regions to be able to construct Ops within their regions in
their ::build methods. However, these methods only have access to
Builder, and not OpBuilder. Creating a local instance of OpBuilder
inside ::build and using it fails to trigger the operation creation
hooks in derived builders (e.g., ConversionPatternRewriter). In this
case, we risk breaking the logic of the derived builder. At the same
time, OpBuilder::create, which is by far the largest user of ::build
already passes "this" as the first argument, so an OpBuilder instance is
already available.

Update all ::build methods in all Ops in MLIR and Flang to take
"OpBuilder &" instead of "Builder *". Note the change from pointer and
to reference to comply with the common style in MLIR, this also ensures
all other users must change their ::build methods.

Differential Revision: https://reviews.llvm.org/D78713

Added: 
    

Modified: 
    flang/include/flang/Optimizer/Dialect/FIROps.h
    flang/include/flang/Optimizer/Dialect/FIROps.td
    flang/lib/Optimizer/Dialect/FIROps.cpp
    mlir/docs/DeclarativeRewrites.md
    mlir/docs/OpDefinitions.md
    mlir/docs/Tutorials/Toy/Ch-2.md
    mlir/examples/toy/Ch2/include/toy/Ops.td
    mlir/examples/toy/Ch2/mlir/Dialect.cpp
    mlir/examples/toy/Ch3/include/toy/Ops.td
    mlir/examples/toy/Ch3/mlir/Dialect.cpp
    mlir/examples/toy/Ch4/include/toy/Ops.td
    mlir/examples/toy/Ch4/mlir/Dialect.cpp
    mlir/examples/toy/Ch5/include/toy/Ops.td
    mlir/examples/toy/Ch5/mlir/Dialect.cpp
    mlir/examples/toy/Ch6/include/toy/Ops.td
    mlir/examples/toy/Ch6/mlir/Dialect.cpp
    mlir/examples/toy/Ch7/include/toy/Ops.td
    mlir/examples/toy/Ch7/mlir/Dialect.cpp
    mlir/include/mlir/Dialect/Affine/IR/AffineOps.h
    mlir/include/mlir/Dialect/Affine/IR/AffineOps.td
    mlir/include/mlir/Dialect/GPU/GPUOps.td
    mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
    mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td
    mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
    mlir/include/mlir/Dialect/LoopOps/LoopOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVAtomicOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVCompositeOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVControlFlowOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVLogicalOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVNonUniformOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVOps.td
    mlir/include/mlir/Dialect/SPIRV/SPIRVStructureOps.td
    mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td
    mlir/include/mlir/Dialect/StandardOps/IR/Ops.h
    mlir/include/mlir/Dialect/StandardOps/IR/Ops.td
    mlir/include/mlir/Dialect/Vector/VectorOps.td
    mlir/include/mlir/IR/Builders.h
    mlir/include/mlir/IR/Function.h
    mlir/include/mlir/IR/Module.h
    mlir/include/mlir/IR/OpBase.td
    mlir/include/mlir/IR/OpDefinition.h
    mlir/include/mlir/IR/PatternMatch.h
    mlir/include/mlir/Transforms/FoldUtils.h
    mlir/lib/Conversion/LinalgToSPIRV/LinalgToSPIRV.cpp
    mlir/lib/Dialect/Affine/IR/AffineOps.cpp
    mlir/lib/Dialect/GPU/IR/GPUDialect.cpp
    mlir/lib/Dialect/GPU/Transforms/KernelOutlining.cpp
    mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
    mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
    mlir/lib/Dialect/LoopOps/LoopOps.cpp
    mlir/lib/Dialect/SPIRV/SPIRVLowering.cpp
    mlir/lib/Dialect/SPIRV/SPIRVOps.cpp
    mlir/lib/Dialect/SPIRV/Serialization/Deserializer.cpp
    mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
    mlir/lib/Dialect/StandardOps/IR/Ops.cpp
    mlir/lib/Dialect/Vector/VectorOps.cpp
    mlir/lib/IR/Function.cpp
    mlir/lib/IR/Module.cpp
    mlir/lib/IR/Operation.cpp
    mlir/test/lib/Dialect/Test/TestOps.td
    mlir/test/lib/Dialect/Test/TestPatterns.cpp
    mlir/test/mlir-tblgen/op-attribute.td
    mlir/test/mlir-tblgen/op-decl.td
    mlir/test/mlir-tblgen/op-result.td
    mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
    mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
    mlir/unittests/Dialect/SPIRV/SerializationTest.cpp

Removed: 
    


################################################################################
diff  --git a/flang/include/flang/Optimizer/Dialect/FIROps.h b/flang/include/flang/Optimizer/Dialect/FIROps.h
index 992fe48d539c..df43f4dc6ee1 100644
--- a/flang/include/flang/Optimizer/Dialect/FIROps.h
+++ b/flang/include/flang/Optimizer/Dialect/FIROps.h
@@ -21,10 +21,10 @@ class FirEndOp;
 class LoopOp;
 class RealAttr;
 
-void buildCmpFOp(mlir::Builder *builder, mlir::OperationState &result,
+void buildCmpFOp(mlir::OpBuilder &builder, mlir::OperationState &result,
                  mlir::CmpFPredicate predicate, mlir::Value lhs,
                  mlir::Value rhs);
-void buildCmpCOp(mlir::Builder *builder, mlir::OperationState &result,
+void buildCmpCOp(mlir::OpBuilder &builder, mlir::OperationState &result,
                  mlir::CmpFPredicate predicate, mlir::Value lhs,
                  mlir::Value rhs);
 unsigned getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,

diff  --git a/flang/include/flang/Optimizer/Dialect/FIROps.td b/flang/include/flang/Optimizer/Dialect/FIROps.td
index 8ecb1711c7e0..46c39a1d498b 100644
--- a/flang/include/flang/Optimizer/Dialect/FIROps.td
+++ b/flang/include/flang/Optimizer/Dialect/FIROps.td
@@ -140,7 +140,7 @@ class fir_SimpleOp<string mnemonic, list<OpTrait> traits>
 
 // Base builder for allocate operations
 def fir_AllocateOpBuilder : OpBuilder<
-  "Builder *builder, OperationState &result, Type inType,"
+  "OpBuilder &builder, OperationState &result, Type inType,"
   "ValueRange lenParams = {}, ValueRange sizes = {},"
   "ArrayRef<NamedAttribute> attributes = {}",
   [{
@@ -151,19 +151,19 @@ def fir_AllocateOpBuilder : OpBuilder<
   }]>;
 
 def fir_NamedAllocateOpBuilder : OpBuilder<
-  "Builder *builder, OperationState &result, Type inType, StringRef name,"
+  "OpBuilder &builder, OperationState &result, Type inType, StringRef name,"
   "ValueRange lenParams = {}, ValueRange sizes = {},"
   "ArrayRef<NamedAttribute> attributes = {}",
   [{
     result.addTypes(getRefTy(inType));
     result.addAttribute("in_type", TypeAttr::get(inType));
-    result.addAttribute("name", builder->getStringAttr(name));
+    result.addAttribute("name", builder.getStringAttr(name));
     result.addOperands(sizes);
     result.addAttributes(attributes);
   }]>;
 
 def fir_OneResultOpBuilder : OpBuilder<
-  "Builder *, OperationState &result, Type resultType,"
+  "OpBuilder &, OperationState &result, Type resultType,"
   "ValueRange operands, ArrayRef<NamedAttribute> attributes = {}",
   [{
     if (resultType)
@@ -370,7 +370,7 @@ def fir_LoadOp : fir_OneResultOp<"load", [MemoryEffects<[MemRead]>]> {
   let arguments = (ins AnyReferenceLike:$memref);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value refVal",
+    "OpBuilder &builder, OperationState &result, Value refVal",
     [{
       if (!refVal) {
         mlir::emitError(result.location, "LoadOp has null argument");
@@ -605,7 +605,7 @@ class fir_IntegralSwitchTerminatorOp<string mnemonic,
 
   let skipDefaultBuilders = 1;
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value selector,"
+    "OpBuilder &builder, OperationState &result, Value selector,"
     "ArrayRef<int64_t> compareOperands, ArrayRef<Block *> destinations,"
     "ArrayRef<ValueRange> destOperands = {},"
     "ArrayRef<NamedAttribute> attributes = {}",
@@ -613,9 +613,9 @@ class fir_IntegralSwitchTerminatorOp<string mnemonic,
       result.addOperands(selector);
       llvm::SmallVector<mlir::Attribute, 8> ivalues;
       for (auto iv : compareOperands)
-        ivalues.push_back(builder->getI64IntegerAttr(iv));
-      ivalues.push_back(builder->getUnitAttr());
-      result.addAttribute(getCasesAttr(), builder->getArrayAttr(ivalues));
+        ivalues.push_back(builder.getI64IntegerAttr(iv));
+      ivalues.push_back(builder.getUnitAttr());
+      result.addAttribute(getCasesAttr(), builder.getArrayAttr(ivalues));
       const auto count = destinations.size();
       for (auto d : destinations)
         result.addSuccessors(d);
@@ -633,9 +633,9 @@ class fir_IntegralSwitchTerminatorOp<string mnemonic,
         }
       }
       result.addAttribute(getOperandSegmentSizeAttr(),
-                          builder->getI32VectorAttr({1, 0, sumArgs}));
+                          builder.getI32VectorAttr({1, 0, sumArgs}));
       result.addAttribute(getTargetOffsetAttr(),
-                          builder->getI32VectorAttr(argOffs));
+                          builder.getI32VectorAttr(argOffs));
       result.addAttributes(attributes);
     }]
   >];
@@ -793,11 +793,11 @@ def fir_SelectCaseOp : fir_SwitchTerminatorOp<"select_case"> {
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, Value selector,"
+    OpBuilder<"OpBuilder &builder, OperationState &result, Value selector,"
     "ArrayRef<mlir::Attribute> compareAttrs, ArrayRef<ValueRange> cmpOperands,"
     "ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
     "ArrayRef<NamedAttribute> attributes = {}">,
-    OpBuilder<"Builder *builder, OperationState &result, Value selector,"
+    OpBuilder<"OpBuilder &builder, OperationState &result, Value selector,"
     "ArrayRef<mlir::Attribute> compareAttrs, ArrayRef<Value> cmpOpList,"
     "ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
     "ArrayRef<NamedAttribute> attributes = {}">];
@@ -886,13 +886,13 @@ def fir_SelectTypeOp : fir_SwitchTerminatorOp<"select_type"> {
 
   let skipDefaultBuilders = 1;
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value selector,"
+    "OpBuilder &builder, OperationState &result, Value selector,"
     "ArrayRef<mlir::Attribute> typeOperands,"
     "ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
     "ArrayRef<NamedAttribute> attributes = {}",
     [{
       result.addOperands(selector);
-      result.addAttribute(getCasesAttr(), builder->getArrayAttr(typeOperands));
+      result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands));
       const auto count = destinations.size();
       for (auto d : destinations)
         result.addSuccessors(d);
@@ -910,9 +910,9 @@ def fir_SelectTypeOp : fir_SwitchTerminatorOp<"select_type"> {
         }
       }
       result.addAttribute(getOperandSegmentSizeAttr(),
-                          builder->getI32VectorAttr({1, 0, sumArgs}));
+                          builder.getI32VectorAttr({1, 0, sumArgs}));
       result.addAttribute(getTargetOffsetAttr(),
-                          builder->getI32VectorAttr(argOffs));
+                          builder.getI32VectorAttr(argOffs));
       result.addAttributes(attributes);
     }]
   >];
@@ -1596,10 +1596,10 @@ def fir_CoordinateOp : fir_Op<"coordinate_of", [NoSideEffect]> {
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "Type type, Value ref, ValueRange coor,"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "Type type, ValueRange operands,"
 	      "ArrayRef<NamedAttribute> attrs = {}">];
 	      
@@ -1708,10 +1708,10 @@ def fir_FieldIndexOp : fir_OneResultOp<"field_index", [NoSideEffect]> {
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, StringRef fieldName,"
+    "OpBuilder &builder, OperationState &result, StringRef fieldName,"
     "Type recTy, ValueRange operands = {}",
     [{
-      result.addAttribute(fieldAttrName(), builder->getStringAttr(fieldName));
+      result.addAttribute(fieldAttrName(), builder.getStringAttr(fieldName));
       result.addAttribute(typeAttrName(), TypeAttr::get(recTy));
       result.addOperands(operands);
     }]
@@ -1832,9 +1832,9 @@ def fir_LenParamIndexOp : fir_OneResultOp<"len_param_index", [NoSideEffect]> {
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, StringRef fieldName, Type recTy",
+    "OpBuilder &builder, OperationState &result, StringRef fieldName, Type recTy",
     [{
-      result.addAttribute(fieldAttrName(), builder->getStringAttr(fieldName));
+      result.addAttribute(fieldAttrName(), builder.getStringAttr(fieldName));
       result.addAttribute(typeAttrName(), TypeAttr::get(recTy));
     }]
   >];
@@ -1864,7 +1864,7 @@ def fir_ResultOp : fir_Op<"result", [NoSideEffect, ReturnLike, Terminator]> {
 
   let arguments = (ins Variadic<AnyType>:$results);
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result", "/* do nothing */">
+    OpBuilder<"OpBuilder &builder, OperationState &result", "/* do nothing */">
   ];
 
   let assemblyFormat = "($results^ `:` type($results))? attr-dict";
@@ -1919,7 +1919,7 @@ def fir_LoopOp : region_Op<"do_loop",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "mlir::Value lowerBound, mlir::Value upperBound,"
               "mlir::Value step, bool unordered = false,"
               "ValueRange iterArgs = llvm::None,"
@@ -1996,9 +1996,9 @@ def fir_WhereOp : region_Op<"if"> {
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "Value cond, bool withOtherRegion">,
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "TypeRange resultTypes, Value cond, bool withOtherRegion">
   ];
 
@@ -2043,7 +2043,7 @@ def fir_IterWhileOp : region_Op<"iterate_while",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "mlir::Value lowerBound, mlir::Value upperBound,"
 	      "mlir::Value step, mlir::Value iterate,"
               "ValueRange iterArgs = llvm::None,"
@@ -2367,7 +2367,7 @@ def fir_CmpfOp : fir_Op<"cmpf",
   let results = (outs AnyLogicalLike);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, CmpFPredicate predicate,"
+    "OpBuilder &builder, OperationState &result, CmpFPredicate predicate,"
     "Value lhs, Value rhs", [{
       buildCmpFOp(builder, result, predicate, lhs, rhs);
   }]>];
@@ -2476,7 +2476,7 @@ def fir_CmpcOp : fir_Op<"cmpc",
   let printer = "printCmpcOp(p, *this);";
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, CmpFPredicate predicate,"
+    "OpBuilder &builder, OperationState &result, CmpFPredicate predicate,"
     "Value lhs, Value rhs", [{
       buildCmpCOp(builder, result, predicate, lhs, rhs);
   }]>];
@@ -2608,7 +2608,7 @@ def fir_GenTypeDescOp : fir_OneResultOp<"gentypedesc", [NoSideEffect]> {
   }];
 
   let builders = [
-    OpBuilder<"Builder *, OperationState &result, mlir::TypeAttr inty">
+    OpBuilder<"OpBuilder &, OperationState &result, mlir::TypeAttr inty">
   ];
 
   let verifier = [{
@@ -2713,23 +2713,23 @@ def fir_GlobalOp : fir_Op<"global", [IsolatedFromAbove, Symbol]> {
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, Type type, ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, bool isConstant, Type type,"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, Type type, StringAttr linkage = {},"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, bool isConstant, Type type,"
 	      "StringAttr linkage = {},"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, Type type, Attribute initVal,"
 	      "StringAttr linkage = {},"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
-    OpBuilder<"mlir::Builder *builder, OperationState &result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState &result,"
               "StringRef name, bool isConstant, Type type,"
 	      "Attribute initVal, StringAttr linkage = {},"
 	      "ArrayRef<NamedAttribute> attrs = {}">,
@@ -2891,11 +2891,11 @@ def fir_DispatchTableOp : fir_Op<"dispatch_table",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"mlir::Builder *builder, OperationState *result,"
+    OpBuilder<"mlir::OpBuilder &builder, OperationState *result,"
               "StringRef name, Type type, ArrayRef<NamedAttribute> attrs = {}",
     [{
       result->addAttribute(mlir::SymbolTable::getSymbolAttrName(),
-                           builder->getStringAttr(name));
+                           builder.getStringAttr(name));
       result->addAttributes(attrs);
     }]>
   ];

diff  --git a/flang/lib/Optimizer/Dialect/FIROps.cpp b/flang/lib/Optimizer/Dialect/FIROps.cpp
index d8ef6f6f8515..1dd15fc959be 100644
--- a/flang/lib/Optimizer/Dialect/FIROps.cpp
+++ b/flang/lib/Optimizer/Dialect/FIROps.cpp
@@ -228,13 +228,13 @@ mlir::CmpFPredicate fir::CmpfOp::getPredicateByName(llvm::StringRef name) {
   return pred.getValue();
 }
 
-void fir::buildCmpFOp(Builder *builder, OperationState &result,
+void fir::buildCmpFOp(OpBuilder &builder, OperationState &result,
                       CmpFPredicate predicate, Value lhs, Value rhs) {
   result.addOperands({lhs, rhs});
-  result.types.push_back(builder->getI1Type());
+  result.types.push_back(builder.getI1Type());
   result.addAttribute(
       CmpfOp::getPredicateAttrName(),
-      builder->getI64IntegerAttr(static_cast<int64_t>(predicate)));
+      builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
 }
 
 template <typename OPTY>
@@ -294,13 +294,13 @@ mlir::ParseResult fir::parseCmpfOp(mlir::OpAsmParser &parser,
 // CmpcOp
 //===----------------------------------------------------------------------===//
 
-void fir::buildCmpCOp(Builder *builder, OperationState &result,
+void fir::buildCmpCOp(OpBuilder &builder, OperationState &result,
                       CmpFPredicate predicate, Value lhs, Value rhs) {
   result.addOperands({lhs, rhs});
-  result.types.push_back(builder->getI1Type());
+  result.types.push_back(builder.getI1Type());
   result.addAttribute(
       fir::CmpcOp::getPredicateAttrName(),
-      builder->getI64IntegerAttr(static_cast<int64_t>(predicate)));
+      builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
 }
 
 static void printCmpcOp(OpAsmPrinter &p, fir::CmpcOp op) { printCmpOp(p, op); }
@@ -388,7 +388,7 @@ mlir::Type fir::CoordinateOp::getBaseType() {
   return getAttr(CoordinateOp::baseType()).cast<mlir::TypeAttr>().getValue();
 }
 
-void fir::CoordinateOp::build(Builder *, OperationState &result,
+void fir::CoordinateOp::build(OpBuilder &, OperationState &result,
                               mlir::Type resType, ValueRange operands,
                               ArrayRef<NamedAttribute> attrs) {
   assert(operands.size() >= 1u && "mismatched number of parameters");
@@ -399,7 +399,7 @@ void fir::CoordinateOp::build(Builder *, OperationState &result,
   result.addTypes({resType});
 }
 
-void fir::CoordinateOp::build(Builder *builder, OperationState &result,
+void fir::CoordinateOp::build(OpBuilder &builder, OperationState &result,
                               mlir::Type resType, mlir::Value ref,
                               ValueRange coor, ArrayRef<NamedAttribute> attrs) {
   llvm::SmallVector<mlir::Value, 16> operands{ref};
@@ -471,7 +471,7 @@ static mlir::ParseResult parseEmboxOp(mlir::OpAsmParser &parser,
 // GenTypeDescOp
 //===----------------------------------------------------------------------===//
 
-void fir::GenTypeDescOp::build(Builder *, OperationState &result,
+void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result,
                                mlir::TypeAttr inty) {
   result.addAttribute("in_type", inty);
   result.addTypes(TypeDescType::get(inty.getValue()));
@@ -538,17 +538,17 @@ void fir::GlobalOp::appendInitialValue(mlir::Operation *op) {
   getBlock().getOperations().push_back(op);
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, bool isConstant, Type type,
                           Attribute initialVal, StringAttr linkage,
                           ArrayRef<NamedAttribute> attrs) {
   result.addRegion();
   result.addAttribute(typeAttrName(), mlir::TypeAttr::get(type));
   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
-                      builder->getStringAttr(name));
-  result.addAttribute(symbolAttrName(), builder->getSymbolRefAttr(name));
+                      builder.getStringAttr(name));
+  result.addAttribute(symbolAttrName(), builder.getSymbolRefAttr(name));
   if (isConstant)
-    result.addAttribute(constantAttrName(), builder->getUnitAttr());
+    result.addAttribute(constantAttrName(), builder.getUnitAttr());
   if (initialVal)
     result.addAttribute(initValAttrName(), initialVal);
   if (linkage)
@@ -556,31 +556,31 @@ void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
   result.attributes.append(attrs.begin(), attrs.end());
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, Type type, Attribute initialVal,
                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, bool isConstant, Type type,
                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
   build(builder, result, name, isConstant, type, {}, linkage, attrs);
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, Type type, StringAttr linkage,
                           ArrayRef<NamedAttribute> attrs) {
   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, bool isConstant, Type type,
                           ArrayRef<NamedAttribute> attrs) {
   build(builder, result, name, isConstant, type, StringAttr{}, attrs);
 }
 
-void fir::GlobalOp::build(mlir::Builder *builder, OperationState &result,
+void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
                           StringRef name, Type type,
                           ArrayRef<NamedAttribute> attrs) {
   build(builder, result, name, /*isConstant=*/false, type, attrs);
@@ -597,7 +597,7 @@ mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) {
 // IterWhileOp
 //===----------------------------------------------------------------------===//
 
-void fir::IterWhileOp::build(mlir::Builder *builder,
+void fir::IterWhileOp::build(mlir::OpBuilder &builder,
                              mlir::OperationState &result, mlir::Value lb,
                              mlir::Value ub, mlir::Value step,
                              mlir::Value iterate, mlir::ValueRange iterArgs,
@@ -609,7 +609,7 @@ void fir::IterWhileOp::build(mlir::Builder *builder,
     result.addTypes(v.getType());
   mlir::Region *bodyRegion = result.addRegion();
   bodyRegion->push_back(new Block{});
-  bodyRegion->front().addArgument(builder->getIndexType());
+  bodyRegion->front().addArgument(builder.getIndexType());
   bodyRegion->front().addArgument(iterate.getType());
   for (auto v : iterArgs)
     bodyRegion->front().addArgument(v.getType());
@@ -786,7 +786,7 @@ mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
 // LoopOp
 //===----------------------------------------------------------------------===//
 
-void fir::LoopOp::build(mlir::Builder *builder, mlir::OperationState &result,
+void fir::LoopOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
                         mlir::Value lb, mlir::Value ub, mlir::Value step,
                         bool unordered, mlir::ValueRange iterArgs,
                         llvm::ArrayRef<mlir::NamedAttribute> attributes) {
@@ -797,12 +797,12 @@ void fir::LoopOp::build(mlir::Builder *builder, mlir::OperationState &result,
   mlir::Region *bodyRegion = result.addRegion();
   bodyRegion->push_back(new Block{});
   if (iterArgs.empty())
-    LoopOp::ensureTerminator(*bodyRegion, *builder, result.location);
-  bodyRegion->front().addArgument(builder->getIndexType());
+    LoopOp::ensureTerminator(*bodyRegion, builder, result.location);
+  bodyRegion->front().addArgument(builder.getIndexType());
   for (auto v : iterArgs)
     bodyRegion->front().addArgument(v.getType());
   if (unordered)
-    result.addAttribute(unorderedAttrName(), builder->getUnitAttr());
+    result.addAttribute(unorderedAttrName(), builder.getUnitAttr());
   result.addAttributes(attributes);
 }
 
@@ -1162,7 +1162,7 @@ unsigned fir::SelectCaseOp::targetOffsetSize() {
       getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()));
 }
 
-void fir::SelectCaseOp::build(mlir::Builder *builder,
+void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
                               mlir::OperationState &result,
                               mlir::Value selector,
                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
@@ -1171,7 +1171,7 @@ void fir::SelectCaseOp::build(mlir::Builder *builder,
                               llvm::ArrayRef<mlir::ValueRange> destOperands,
                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
   result.addOperands(selector);
-  result.addAttribute(getCasesAttr(), builder->getArrayAttr(compareAttrs));
+  result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
   llvm::SmallVector<int32_t, 8> operOffs;
   int32_t operSize = 0;
   for (auto attr : compareAttrs) {
@@ -1188,7 +1188,7 @@ void fir::SelectCaseOp::build(mlir::Builder *builder,
   for (auto ops : cmpOperands)
     result.addOperands(ops);
   result.addAttribute(getCompareOffsetAttr(),
-                      builder->getI32VectorAttr(operOffs));
+                      builder.getI32VectorAttr(operOffs));
   const auto count = destinations.size();
   for (auto d : destinations)
     result.addSuccessors(d);
@@ -1206,9 +1206,8 @@ void fir::SelectCaseOp::build(mlir::Builder *builder,
     }
   }
   result.addAttribute(getOperandSegmentSizeAttr(),
-                      builder->getI32VectorAttr({1, operSize, sumArgs}));
-  result.addAttribute(getTargetOffsetAttr(),
-                      builder->getI32VectorAttr(argOffs));
+                      builder.getI32VectorAttr({1, operSize, sumArgs}));
+  result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
   result.addAttributes(attributes);
 }
 
@@ -1216,7 +1215,7 @@ void fir::SelectCaseOp::build(mlir::Builder *builder,
 /// operands need not be partitioned by the builder. Instead the operands are
 /// partitioned here, before being passed to the default builder. This
 /// partitioning is unchecked, so can go awry on bad input.
-void fir::SelectCaseOp::build(mlir::Builder *builder,
+void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
                               mlir::OperationState &result,
                               mlir::Value selector,
                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
@@ -1394,14 +1393,14 @@ mlir::OpFoldResult fir::SubfOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
 // WhereOp
 //===----------------------------------------------------------------------===//
 
-void fir::WhereOp::build(mlir::Builder *builder, OperationState &result,
+void fir::WhereOp::build(mlir::OpBuilder &builder, OperationState &result,
                          mlir::Value cond, bool withElseRegion) {
   result.addOperands(cond);
   mlir::Region *thenRegion = result.addRegion();
   mlir::Region *elseRegion = result.addRegion();
-  WhereOp::ensureTerminator(*thenRegion, *builder, result.location);
+  WhereOp::ensureTerminator(*thenRegion, builder, result.location);
   if (withElseRegion)
-    WhereOp::ensureTerminator(*elseRegion, *builder, result.location);
+    WhereOp::ensureTerminator(*elseRegion, builder, result.location);
 }
 
 static mlir::ParseResult parseWhereOp(OpAsmParser &parser,

diff  --git a/mlir/docs/DeclarativeRewrites.md b/mlir/docs/DeclarativeRewrites.md
index 83eb3544da63..adbe251c2737 100644
--- a/mlir/docs/DeclarativeRewrites.md
+++ b/mlir/docs/DeclarativeRewrites.md
@@ -265,7 +265,7 @@ For example, for the above `AOp`, a possible builder is:
 
 ```c++
 
-void AOp::build(Builder *builder, OperationState &state,
+void AOp::build(OpBuilder &builder, OperationState &state,
                 Value input, Attribute attr) {
   state.addOperands({input});
   state.addAttribute("a_attr", attr);

diff  --git a/mlir/docs/OpDefinitions.md b/mlir/docs/OpDefinitions.md
index 9a9e18d79633..098e38d92732 100644
--- a/mlir/docs/OpDefinitions.md
+++ b/mlir/docs/OpDefinitions.md
@@ -490,14 +490,14 @@ The following builders are generated:
 
 ```c++
 // All result-types/operands/attributes have one aggregate parameter.
-static void build(Builder *odsBuilder, OperationState &odsState,
+static void build(OpBuilder &odsBuilder, OperationState &odsState,
                   ArrayRef<Type> resultTypes,
                   ValueRange operands,
                   ArrayRef<NamedAttribute> attributes);
 
 // Each result-type/operand/attribute has a separate parameter. The parameters
 // for attributes are of mlir::Attribute types.
-static void build(Builder *odsBuilder, OperationState &odsState,
+static void build(OpBuilder &odsBuilder, OperationState &odsState,
                   Type i32_result, Type f32_result, ...,
                   Value i32_operand, Value f32_operand, ...,
                   IntegerAttr i32_attr, FloatAttr f32_attr, ...);
@@ -506,20 +506,20 @@ static void build(Builder *odsBuilder, OperationState &odsState,
 // for attributes are raw values unwrapped with mlir::Attribute instances.
 // (Note that this builder will not always be generated. See the following
 // explanation for more details.)
-static void build(Builder *odsBuilder, OperationState &odsState,
+static void build(OpBuilder &odsBuilder, OperationState &odsState,
                   Type i32_result, Type f32_result, ...,
                   Value i32_operand, Value f32_operand, ...,
                   APInt i32_attr, StringRef f32_attr, ...);
 
 // Each operand/attribute has a separate parameter but result type is aggregate.
-static void build(Builder *odsBuilder, OperationState &odsState,
+static void build(OpBuilder &odsBuilder, OperationState &odsState,
                   ArrayRef<Type> resultTypes,
                   Value i32_operand, Value f32_operand, ...,
                   IntegerAttr i32_attr, FloatAttr f32_attr, ...);
 
 // All operands/attributes have aggregate parameters.
 // Generated if InferTypeOpInterface interface is specified.
-static void build(Builder *odsBuilder, OperationState &odsState,
+static void build(OpBuilder &odsBuilder, OperationState &odsState,
                   ValueRange operands,
                   ArrayRef<NamedAttribute> attributes);
 
@@ -581,8 +581,8 @@ def MyOp : ... {
   ...
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, float val = 0.5f", [{
-      state.addAttribute("attr", builder->getF32FloatAttr(val));
+    OpBuilder<"OpBuilder &builder, OperationState &state, float val = 0.5f", [{
+      state.addAttribute("attr", builder.getF32FloatAttr(val));
     }]>
   ];
 }
@@ -591,8 +591,8 @@ def MyOp : ... {
 The generated builder will look like:
 
 ```c++
-static void build(Builder *builder, OperationState &state, float val = 0.5f) {
-  state.addAttribute("attr", builder->getF32FloatAttr(val));
+static void build(OpBuilder &builder, OperationState &state, float val = 0.5f) {
+  state.addAttribute("attr", builder.getF32FloatAttr(val));
 }
 ```
 

diff  --git a/mlir/docs/Tutorials/Toy/Ch-2.md b/mlir/docs/Tutorials/Toy/Ch-2.md
index e57bd7da4b22..71450c2397b7 100755
--- a/mlir/docs/Tutorials/Toy/Ch-2.md
+++ b/mlir/docs/Tutorials/Toy/Ch-2.md
@@ -476,7 +476,7 @@ def ConstantOp : Toy_Op<"constant"> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "DenseElementsAttr value", [{
       // Call into an autogenerated `build` method.
       build(builder, result, value.getType(), value);
@@ -484,7 +484,7 @@ def ConstantOp : Toy_Op<"constant"> {
 
     // Build a constant with a given constant floating-point value. This builder
     // creates a declaration for `ConstantOp::build` with the given parameters.
-    OpBuilder<"Builder *builder, OperationState &result, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &result, double value">
   ];
 }
 ```

diff  --git a/mlir/examples/toy/Ch2/include/toy/Ops.td b/mlir/examples/toy/Ch2/include/toy/Ops.td
index e82302952e6f..4e06634c6d4e 100644
--- a/mlir/examples/toy/Ch2/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch2/include/toy/Ops.td
@@ -68,13 +68,13 @@ def ConstantOp : Toy_Op<"constant", [NoSideEffect]> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -97,7 +97,7 @@ def AddOp : Toy_Op<"add"> {
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -132,7 +132,7 @@ def GenericCallOp : Toy_Op<"generic_call"> {
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -153,7 +153,7 @@ def MulOp : Toy_Op<"mul"> {
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -217,7 +217,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -241,7 +241,7 @@ def TransposeOp : Toy_Op<"transpose"> {
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch2/mlir/Dialect.cpp b/mlir/examples/toy/Ch2/mlir/Dialect.cpp
index 4aa33c048f6e..b60d792e2e01 100644
--- a/mlir/examples/toy/Ch2/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch2/mlir/Dialect.cpp
@@ -91,9 +91,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -158,29 +158,29 @@ static mlir::LogicalResult verify(ConstantOp op) {
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -225,9 +225,9 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/examples/toy/Ch3/include/toy/Ops.td b/mlir/examples/toy/Ch3/include/toy/Ops.td
index 999ea86f03de..5a407603164a 100644
--- a/mlir/examples/toy/Ch3/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch3/include/toy/Ops.td
@@ -67,13 +67,13 @@ def ConstantOp : Toy_Op<"constant", [NoSideEffect]> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -96,7 +96,7 @@ def AddOp : Toy_Op<"add", [NoSideEffect]> {
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -131,7 +131,7 @@ def GenericCallOp : Toy_Op<"generic_call"> {
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -152,7 +152,7 @@ def MulOp : Toy_Op<"mul", [NoSideEffect]> {
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -219,7 +219,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -246,7 +246,7 @@ def TransposeOp : Toy_Op<"transpose", [NoSideEffect]> {
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch3/mlir/Dialect.cpp b/mlir/examples/toy/Ch3/mlir/Dialect.cpp
index 4aa33c048f6e..b60d792e2e01 100644
--- a/mlir/examples/toy/Ch3/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch3/mlir/Dialect.cpp
@@ -91,9 +91,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -158,29 +158,29 @@ static mlir::LogicalResult verify(ConstantOp op) {
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -225,9 +225,9 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/examples/toy/Ch4/include/toy/Ops.td b/mlir/examples/toy/Ch4/include/toy/Ops.td
index 537177bbd680..1cd20802a0ca 100644
--- a/mlir/examples/toy/Ch4/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch4/include/toy/Ops.td
@@ -69,13 +69,13 @@ def ConstantOp : Toy_Op<"constant", [NoSideEffect]> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -99,7 +99,7 @@ def AddOp : Toy_Op<"add",
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -156,7 +156,7 @@ def GenericCallOp : Toy_Op<"generic_call",
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -178,7 +178,7 @@ def MulOp : Toy_Op<"mul",
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -245,7 +245,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -273,7 +273,7 @@ def TransposeOp : Toy_Op<"transpose",
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch4/mlir/Dialect.cpp b/mlir/examples/toy/Ch4/mlir/Dialect.cpp
index 9a0a3a6c95a6..02a70218af6d 100644
--- a/mlir/examples/toy/Ch4/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch4/mlir/Dialect.cpp
@@ -141,9 +141,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -208,9 +208,9 @@ static mlir::LogicalResult verify(ConstantOp op) {
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -228,12 +228,12 @@ void CastOp::inferShapes() { getResult().setType(getOperand().getType()); }
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 /// Return the callee of the generic call operation, this is required by the
@@ -249,9 +249,9 @@ Operation::operand_range GenericCallOp::getArgOperands() { return inputs(); }
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -300,9 +300,9 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/examples/toy/Ch5/include/toy/Ops.td b/mlir/examples/toy/Ch5/include/toy/Ops.td
index 3645141a0962..7e7d5d10638c 100644
--- a/mlir/examples/toy/Ch5/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch5/include/toy/Ops.td
@@ -69,13 +69,13 @@ def ConstantOp : Toy_Op<"constant", [NoSideEffect]> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -99,7 +99,7 @@ def AddOp : Toy_Op<"add",
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -156,7 +156,7 @@ def GenericCallOp : Toy_Op<"generic_call",
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -178,7 +178,7 @@ def MulOp : Toy_Op<"mul",
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -246,7 +246,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -274,7 +274,7 @@ def TransposeOp : Toy_Op<"transpose",
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch5/mlir/Dialect.cpp b/mlir/examples/toy/Ch5/mlir/Dialect.cpp
index 9a0a3a6c95a6..02a70218af6d 100644
--- a/mlir/examples/toy/Ch5/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch5/mlir/Dialect.cpp
@@ -141,9 +141,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -208,9 +208,9 @@ static mlir::LogicalResult verify(ConstantOp op) {
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -228,12 +228,12 @@ void CastOp::inferShapes() { getResult().setType(getOperand().getType()); }
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 /// Return the callee of the generic call operation, this is required by the
@@ -249,9 +249,9 @@ Operation::operand_range GenericCallOp::getArgOperands() { return inputs(); }
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -300,9 +300,9 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/examples/toy/Ch6/include/toy/Ops.td b/mlir/examples/toy/Ch6/include/toy/Ops.td
index b70e14c2a7a2..dee06c1f3b3c 100644
--- a/mlir/examples/toy/Ch6/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch6/include/toy/Ops.td
@@ -69,13 +69,13 @@ def ConstantOp : Toy_Op<"constant", [NoSideEffect]> {
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -99,7 +99,7 @@ def AddOp : Toy_Op<"add",
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -156,7 +156,7 @@ def GenericCallOp : Toy_Op<"generic_call",
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -178,7 +178,7 @@ def MulOp : Toy_Op<"mul",
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -246,7 +246,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -274,7 +274,7 @@ def TransposeOp : Toy_Op<"transpose",
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch6/mlir/Dialect.cpp b/mlir/examples/toy/Ch6/mlir/Dialect.cpp
index 9a0a3a6c95a6..02a70218af6d 100644
--- a/mlir/examples/toy/Ch6/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch6/mlir/Dialect.cpp
@@ -141,9 +141,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -208,9 +208,9 @@ static mlir::LogicalResult verify(ConstantOp op) {
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -228,12 +228,12 @@ void CastOp::inferShapes() { getResult().setType(getOperand().getType()); }
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 /// Return the callee of the generic call operation, this is required by the
@@ -249,9 +249,9 @@ Operation::operand_range GenericCallOp::getArgOperands() { return inputs(); }
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -300,9 +300,9 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/examples/toy/Ch7/include/toy/Ops.td b/mlir/examples/toy/Ch7/include/toy/Ops.td
index adf56dc040d7..b453f13871ef 100644
--- a/mlir/examples/toy/Ch7/include/toy/Ops.td
+++ b/mlir/examples/toy/Ch7/include/toy/Ops.td
@@ -79,13 +79,13 @@ def ConstantOp : Toy_Op<"constant",
   // using `builder.create<ConstantOp>(...)`.
   let builders = [
     // Build a constant with a given constant tensor value.
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "DenseElementsAttr value", [{
       build(builder, state, value.getType(), value);
     }]>,
 
     // Build a constant with a given constant floating-point value.
-    OpBuilder<"Builder *builder, OperationState &state, double value">
+    OpBuilder<"OpBuilder &builder, OperationState &state, double value">
   ];
 
   // Invoke a static verify method to verify this constant operation.
@@ -112,7 +112,7 @@ def AddOp : Toy_Op<"add",
 
   // Allow building an AddOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -170,7 +170,7 @@ def GenericCallOp : Toy_Op<"generic_call",
 
   // Add custom build methods for the generic call operation.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
               "StringRef callee, ArrayRef<Value> arguments">
   ];
 }
@@ -192,7 +192,7 @@ def MulOp : Toy_Op<"mul",
 
   // Allow building a MulOp with from the two input operands.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value lhs, Value rhs">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value lhs, Value rhs">
   ];
 }
 
@@ -260,7 +260,7 @@ def ReturnOp : Toy_Op<"return", [NoSideEffect, HasParent<"FuncOp">,
 
   // Allow building a ReturnOp with no return operand.
   let builders = [OpBuilder<
-    "Builder *b, OperationState &state", [{ build(b, state, llvm::None); }]
+    "OpBuilder &b, OperationState &state", [{ build(b, state, llvm::None); }]
   >];
 
   // Provide extra utility definitions on the c++ operation class definition.
@@ -287,7 +287,7 @@ def StructAccessOp : Toy_Op<"struct_access", [NoSideEffect]> {
 
   // Allow building a StructAccessOp with just a struct value and an index.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input, size_t index">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input, size_t index">
   ];
 
   let verifier = [{ return ::verify(*this); }];
@@ -335,7 +335,7 @@ def TransposeOp : Toy_Op<"transpose",
 
   // Allow building a TransposeOp with from the input operand.
   let builders = [
-    OpBuilder<"Builder *b, OperationState &state, Value input">
+    OpBuilder<"OpBuilder &b, OperationState &state, Value input">
   ];
 
   // Invoke a static verify method to verify this transpose operation.

diff  --git a/mlir/examples/toy/Ch7/mlir/Dialect.cpp b/mlir/examples/toy/Ch7/mlir/Dialect.cpp
index b3e893e76a15..d653edea6e67 100644
--- a/mlir/examples/toy/Ch7/mlir/Dialect.cpp
+++ b/mlir/examples/toy/Ch7/mlir/Dialect.cpp
@@ -154,9 +154,9 @@ static void printBinaryOp(mlir::OpAsmPrinter &printer, mlir::Operation *op) {
 /// Build a constant operation.
 /// The builder is passed as an argument, so is the state that this method is
 /// expected to fill in order to build the operation.
-void ConstantOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void ConstantOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                        double value) {
-  auto dataType = RankedTensorType::get({}, builder->getF64Type());
+  auto dataType = RankedTensorType::get({}, builder.getF64Type());
   auto dataAttribute = DenseElementsAttr::get(dataType, value);
   ConstantOp::build(builder, state, dataType, dataAttribute);
 }
@@ -260,9 +260,9 @@ void ConstantOp::inferShapes() { getResult().setType(value().getType()); }
 //===----------------------------------------------------------------------===//
 // AddOp
 
-void AddOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void AddOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -280,12 +280,12 @@ void CastOp::inferShapes() { getResult().setType(getOperand().getType()); }
 //===----------------------------------------------------------------------===//
 // GenericCallOp
 
-void GenericCallOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void GenericCallOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                           StringRef callee, ArrayRef<mlir::Value> arguments) {
   // Generic call always returns an unranked Tensor initially.
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(arguments);
-  state.addAttribute("callee", builder->getSymbolRefAttr(callee));
+  state.addAttribute("callee", builder.getSymbolRefAttr(callee));
 }
 
 /// Return the callee of the generic call operation, this is required by the
@@ -301,9 +301,9 @@ Operation::operand_range GenericCallOp::getArgOperands() { return inputs(); }
 //===----------------------------------------------------------------------===//
 // MulOp
 
-void MulOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void MulOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                   mlir::Value lhs, mlir::Value rhs) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands({lhs, rhs});
 }
 
@@ -352,7 +352,7 @@ static mlir::LogicalResult verify(ReturnOp op) {
 //===----------------------------------------------------------------------===//
 // StructAccessOp
 
-void StructAccessOp::build(mlir::Builder *b, mlir::OperationState &state,
+void StructAccessOp::build(mlir::OpBuilder &b, mlir::OperationState &state,
                            mlir::Value input, size_t index) {
   // Extract the result type from the input type.
   StructType structTy = input.getType().cast<StructType>();
@@ -360,7 +360,7 @@ void StructAccessOp::build(mlir::Builder *b, mlir::OperationState &state,
   mlir::Type resultType = structTy.getElementTypes()[index];
 
   // Call into the auto-generated build method.
-  build(b, state, resultType, input, b->getI64IntegerAttr(index));
+  build(b, state, resultType, input, b.getI64IntegerAttr(index));
 }
 
 static mlir::LogicalResult verify(StructAccessOp op) {
@@ -379,9 +379,9 @@ static mlir::LogicalResult verify(StructAccessOp op) {
 //===----------------------------------------------------------------------===//
 // TransposeOp
 
-void TransposeOp::build(mlir::Builder *builder, mlir::OperationState &state,
+void TransposeOp::build(mlir::OpBuilder &builder, mlir::OperationState &state,
                         mlir::Value value) {
-  state.addTypes(UnrankedTensorType::get(builder->getF64Type()));
+  state.addTypes(UnrankedTensorType::get(builder.getF64Type()));
   state.addOperands(value);
 }
 

diff  --git a/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h b/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h
index e0741cfb3afa..2e040adcaec8 100644
--- a/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h
+++ b/mlir/include/mlir/Dialect/Affine/IR/AffineOps.h
@@ -83,7 +83,7 @@ class AffineDmaStartOp : public Op<AffineDmaStartOp, OpTrait::VariadicOperands,
 public:
   using Op::Op;
 
-  static void build(Builder *builder, OperationState &result, Value srcMemRef,
+  static void build(OpBuilder &builder, OperationState &result, Value srcMemRef,
                     AffineMap srcMap, ValueRange srcIndices, Value destMemRef,
                     AffineMap dstMap, ValueRange destIndices, Value tagMemRef,
                     AffineMap tagMap, ValueRange tagIndices, Value numElements,
@@ -271,7 +271,7 @@ class AffineDmaWaitOp : public Op<AffineDmaWaitOp, OpTrait::VariadicOperands,
 public:
   using Op::Op;
 
-  static void build(Builder *builder, OperationState &result, Value tagMemRef,
+  static void build(OpBuilder &builder, OperationState &result, Value tagMemRef,
                     AffineMap tagMap, ValueRange tagIndices, Value numElements);
 
   static StringRef getOperationName() { return "affine.dma_wait"; }
@@ -339,13 +339,13 @@ class AffineLoadOp : public Op<AffineLoadOp, OpTrait::OneResult,
   using Op::Op;
 
   /// Builds an affine load op with the specified map and operands.
-  static void build(Builder *builder, OperationState &result, AffineMap map,
+  static void build(OpBuilder &builder, OperationState &result, AffineMap map,
                     ValueRange operands);
   /// Builds an affine load op with an identity map and operands.
-  static void build(Builder *builder, OperationState &result, Value memref,
+  static void build(OpBuilder &builder, OperationState &result, Value memref,
                     ValueRange indices = {});
   /// Builds an affine load op with the specified map and its operands.
-  static void build(Builder *builder, OperationState &result, Value memref,
+  static void build(OpBuilder &builder, OperationState &result, Value memref,
                     AffineMap map, ValueRange mapOperands);
 
   /// Returns the operand index of the memref.
@@ -408,10 +408,10 @@ class AffineStoreOp : public Op<AffineStoreOp, OpTrait::ZeroResult,
   using Op::Op;
 
   /// Builds an affine store operation with the provided indices (identity map).
-  static void build(Builder *builder, OperationState &result,
+  static void build(OpBuilder &builder, OperationState &result,
                     Value valueToStore, Value memref, ValueRange indices);
   /// Builds an affine store operation with the specified map and its operands.
-  static void build(Builder *builder, OperationState &result,
+  static void build(OpBuilder &builder, OperationState &result,
                     Value valueToStore, Value memref, AffineMap map,
                     ValueRange mapOperands);
 

diff  --git a/mlir/include/mlir/Dialect/Affine/IR/AffineOps.td b/mlir/include/mlir/Dialect/Affine/IR/AffineOps.td
index ce93e103634e..07ea572ae846 100644
--- a/mlir/include/mlir/Dialect/Affine/IR/AffineOps.td
+++ b/mlir/include/mlir/Dialect/Affine/IR/AffineOps.td
@@ -70,9 +70,9 @@ def AffineApplyOp : Affine_Op<"apply", [NoSideEffect]> {
   // has a constant builder. That way we wouldn't need to explicitly specify the
   // result types here.
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "AffineMap map, ValueRange mapOperands", [{
-      build(builder, result, builder->getIndexType(), map, mapOperands);
+      build(builder, result, builder.getIndexType(), map, mapOperands);
     }]>
   ];
 
@@ -177,9 +177,9 @@ def AffineForOp : Affine_Op<"for",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "int64_t lowerBound, int64_t upperBound, int64_t step = 1">,
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "ValueRange lbOperands, AffineMap lbMap, "
               "ValueRange ubOperands, AffineMap ubMap, "
               "int64_t step = 1">
@@ -328,7 +328,7 @@ def AffineIfOp : Affine_Op<"if",
   let skipDefaultBuilders = 1;
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "IntegerSet set, ValueRange args, bool withElseRegion">
   ];
 
@@ -376,10 +376,10 @@ class AffineMinMaxOpBase<string mnemonic, list<OpTrait> traits = []> :
   let results = (outs Index);
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, AffineMap affineMap, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, AffineMap affineMap, "
               "ValueRange mapOperands",
     [{
-      build(builder, result, builder->getIndexType(), affineMap, mapOperands);
+      build(builder, result, builder.getIndexType(), affineMap, mapOperands);
     }]>
   ];
 
@@ -473,11 +473,11 @@ def AffineParallelOp : Affine_Op<"parallel", [ImplicitAffineTerminator]> {
   let regions = (region SizedRegion<1>:$region);
 
   let builders = [
-    OpBuilder<"Builder* builder, OperationState& result,"
+    OpBuilder<"OpBuilder &builder, OperationState &result,"
               "ArrayRef<int64_t> ranges">,
-    OpBuilder<"Builder* builder, OperationState& result, AffineMap lbMap,"
+    OpBuilder<"OpBuilder &builder, OperationState &result, AffineMap lbMap,"
               "ValueRange lbArgs, AffineMap ubMap, ValueRange ubArgs">,
-    OpBuilder<"Builder* builder, OperationState& result, AffineMap lbMap,"
+    OpBuilder<"OpBuilder &builder, OperationState &result, AffineMap lbMap,"
               "ValueRange lbArgs, AffineMap ubMap, ValueRange ubArgs,"
               "ArrayRef<int64_t> steps">
   ];
@@ -535,15 +535,15 @@ def AffinePrefetchOp : Affine_Op<"prefetch"> {
                    BoolAttr:$isDataCache);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value memref,"
+    "OpBuilder &builder, OperationState &result, Value memref,"
     "AffineMap map, ArrayRef<Value> mapOperands, bool isWrite,"
     "unsigned localityHint, bool isDataCache",
     [{
       assert(map.getNumInputs() == mapOperands.size()
              && "inconsistent index info");
-      auto localityHintAttr = builder->getI32IntegerAttr(localityHint);
-      auto isWriteAttr = builder->getBoolAttr(isWrite);
-      auto isDataCacheAttr = builder->getBoolAttr(isDataCache);
+      auto localityHintAttr = builder.getI32IntegerAttr(localityHint);
+      auto isWriteAttr = builder.getBoolAttr(isWrite);
+      auto isDataCacheAttr = builder.getBoolAttr(isDataCache);
       result.addOperands(memref);
       result.addAttribute(getMapAttrName(), AffineMapAttr::get(map));
       result.addOperands(mapOperands);

diff  --git a/mlir/include/mlir/Dialect/GPU/GPUOps.td b/mlir/include/mlir/Dialect/GPU/GPUOps.td
index e48455e06340..82d94557f019 100644
--- a/mlir/include/mlir/Dialect/GPU/GPUOps.td
+++ b/mlir/include/mlir/Dialect/GPU/GPUOps.td
@@ -154,7 +154,7 @@ def GPU_GPUFuncOp : GPU_Op<"func", [HasParent<"GPUModuleOp">,
   let skipDefaultBuilders = 1;
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, StringRef name, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, StringRef name, "
               "FunctionType type, ArrayRef<Type> workgroupAttributions = {}, "
               "ArrayRef<Type> privateAttributions = {}, "
               "ArrayRef<NamedAttribute> attrs = {}">
@@ -323,11 +323,11 @@ def GPU_LaunchFuncOp : GPU_Op<"launch_func">,
   let skipDefaultBuilders = 1;
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, GPUFuncOp kernelFunc, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, GPUFuncOp kernelFunc, "
               "Value gridSizeX, Value gridSizeY, Value gridSizeZ, "
               "Value blockSizeX, Value blockSizeY, Value blockSizeZ, "
               "ValueRange kernelOperands">,
-    OpBuilder<"Builder *builder, OperationState &result, GPUFuncOp kernelFunc, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, GPUFuncOp kernelFunc, "
               "KernelDim3 gridSize, KernelDim3 blockSize, "
               "ValueRange kernelOperands">
   ];
@@ -442,7 +442,7 @@ def GPU_LaunchOp : GPU_Op<"launch">,
   let skipDefaultBuilders = 1;
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, Value gridSizeX,"
+    OpBuilder<"OpBuilder &builder, OperationState &result, Value gridSizeX,"
               "Value gridSizeY, Value gridSizeZ, Value blockSizeX,"
               "Value blockSizeY, Value blockSizeZ">
   ];
@@ -489,7 +489,7 @@ def GPU_ReturnOp : GPU_Op<"return", [HasParent<"GPUFuncOp">, NoSideEffect,
     by an invocation of the `gpu.func`.
   }];
 
-  let builders = [OpBuilder<"Builder *builder, OperationState &result", " // empty">];
+  let builders = [OpBuilder<"OpBuilder &builder, OperationState &result", " // empty">];
 
   let parser = [{ return parseReturnOp(parser, result); }];
   let printer = [{ p << getOperationName(); }];
@@ -668,7 +668,7 @@ def GPU_GPUModuleOp : GPU_Op<"module", [
 
     ```
   }];
-  let builders = [OpBuilder<"Builder *builder, OperationState &result, "
+  let builders = [OpBuilder<"OpBuilder &builder, OperationState &result, "
                             "StringRef name">];
   let parser = [{ return ::parseGPUModuleOp(parser, result); }];
   let printer = [{ return ::print(p, *this); }];

diff  --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index 1bf9f6fa36f9..0a0564c43914 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -23,7 +23,7 @@ class LLVM_Builder<string builder> {
 }
 
 def LLVM_OneResultOpBuilder : OpBuilder<
-  "Builder *, OperationState &result, Type resultType, "
+  "OpBuilder &, OperationState &result, Type resultType, "
   "ValueRange operands, ArrayRef<NamedAttribute> attributes = {}",
   [{
     if (resultType) result.addTypes(resultType);
@@ -34,7 +34,7 @@ def LLVM_OneResultOpBuilder : OpBuilder<
   }]>;
 
 def LLVM_ZeroResultOpBuilder : OpBuilder<
-  "Builder *, OperationState &result, ValueRange operands, "
+  "OpBuilder &, OperationState &result, ValueRange operands, "
   "ArrayRef<NamedAttribute> attributes = {}",
   [{
     result.addOperands(operands);
@@ -56,7 +56,7 @@ class LLVM_OneResultOp<string mnemonic, list<OpTrait> traits = []> :
 // Compatibility builder that takes an instance of wrapped llvm::VoidType
 // to indicate no result.
 def LLVM_VoidResultTypeOpBuilder : OpBuilder<
-  "Builder *builder, OperationState &result, Type resultType, "
+  "OpBuilder &builder, OperationState &result, Type resultType, "
   "ValueRange operands, ArrayRef<NamedAttribute> attributes = {}",
   [{
     auto llvmType = resultType.dyn_cast<LLVM::LLVMType>(); (void)llvmType;
@@ -74,7 +74,7 @@ class LLVM_ZeroResultOp<string mnemonic, list<OpTrait> traits = []> :
 
 // Opaque builder used for terminator operations that contain successors.
 def LLVM_TerminatorPassthroughOpBuilder : OpBuilder<
-  "Builder *, OperationState &result, ValueRange operands, "
+  "OpBuilder &, OperationState &result, ValueRange operands, "
   "SuccessorRange destinations, ArrayRef<NamedAttribute> attributes = {}",
   [{
     result.addOperands(operands);
@@ -150,11 +150,11 @@ def LLVM_ICmpOp : LLVM_OneResultOp<"icmp", [NoSideEffect]>,
     $res = builder.CreateICmp(getLLVMCmpPredicate($predicate), $lhs, $rhs);
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, ICmpPredicate predicate, Value lhs, "
+    "OpBuilder &b, OperationState &result, ICmpPredicate predicate, Value lhs, "
     "Value rhs", [{
       LLVMDialect *dialect = &lhs.getType().cast<LLVMType>().getDialect();
       build(b, result, LLVMType::getInt1Ty(dialect),
-            b->getI64IntegerAttr(static_cast<int64_t>(predicate)), lhs, rhs);
+            b.getI64IntegerAttr(static_cast<int64_t>(predicate)), lhs, rhs);
     }]>];
   let parser = [{ return parseCmpOp<ICmpPredicate>(parser, result); }];
   let printer = [{ printICmpOp(p, *this); }];
@@ -197,11 +197,11 @@ def LLVM_FCmpOp : LLVM_OneResultOp<"fcmp", [NoSideEffect]>,
     $res = builder.CreateFCmp(getLLVMCmpPredicate($predicate), $lhs, $rhs);
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, FCmpPredicate predicate, Value lhs, "
+    "OpBuilder &b, OperationState &result, FCmpPredicate predicate, Value lhs, "
     "Value rhs", [{
       LLVMDialect *dialect = &lhs.getType().cast<LLVMType>().getDialect();
       build(b, result, LLVMType::getInt1Ty(dialect),
-            b->getI64IntegerAttr(static_cast<int64_t>(predicate)), lhs, rhs);
+            b.getI64IntegerAttr(static_cast<int64_t>(predicate)), lhs, rhs);
     }]>];
   let parser = [{ return parseCmpOp<FCmpPredicate>(parser, result); }];
   let printer = [{ printFCmpOp(p, *this); }];
@@ -230,12 +230,12 @@ def LLVM_AllocaOp :
     $res = alloca;
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Type resultType, Value arraySize, "
+    "OpBuilder &b, OperationState &result, Type resultType, Value arraySize, "
     "unsigned alignment",
     [{
       if (alignment == 0)
         return build(b, result, resultType, arraySize, IntegerAttr());
-      build(b, result, resultType, arraySize, b->getI64IntegerAttr(alignment));
+      build(b, result, resultType, arraySize, b.getI64IntegerAttr(alignment));
   }]>];
   let parser = [{ return parseAllocaOp(parser, result); }];
   let printer = [{ printAllocaOp(p, *this); }];
@@ -258,7 +258,7 @@ def LLVM_GEPOp : LLVM_OneResultOp<"getelementptr", [NoSideEffect]>,
 def LLVM_LoadOp : LLVM_OneResultOp<"load">, Arguments<(ins LLVM_Type:$addr)>,
                   LLVM_Builder<"$res = builder.CreateLoad($addr);"> {
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value addr",
+    "OpBuilder &b, OperationState &result, Value addr",
     [{
       auto type = addr.getType().cast<LLVM::LLVMType>().getPointerElementTy();
       build(b, result, type, addr);
@@ -312,7 +312,7 @@ def LLVM_InvokeOp : LLVM_Op<"invoke", [
                               AnySuccessor:$unwindDest);
 
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, ArrayRef<Type> tys, "
+    "OpBuilder &b, OperationState &result, ArrayRef<Type> tys, "
     "FlatSymbolRefAttr callee, ValueRange ops, Block* normal, "
     "ValueRange normalOps, Block* unwind, ValueRange unwindOps",
     [{
@@ -320,7 +320,7 @@ def LLVM_InvokeOp : LLVM_Op<"invoke", [
       build(b, result, tys, ops, normal, normalOps, unwind, unwindOps);
     }]>,
     OpBuilder<
-    "Builder *b, OperationState &result, ArrayRef<Type> tys, "
+    "OpBuilder &b, OperationState &result, ArrayRef<Type> tys, "
     "ValueRange ops, Block* normal, "
     "ValueRange normalOps, Block* unwind, ValueRange unwindOps",
     [{
@@ -345,13 +345,13 @@ def LLVM_CallOp : LLVM_Op<"call">,
                              Variadic<LLVM_Type>)>,
                   Results<(outs Variadic<LLVM_Type>)> {
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, LLVMFuncOp func,"
+    "OpBuilder &builder, OperationState &result, LLVMFuncOp func,"
     "ValueRange operands, ArrayRef<NamedAttribute> attributes = {}",
     [{
       LLVMType resultType = func.getType().getFunctionResultType();
       if (!resultType.isVoidTy())
         result.addTypes(resultType);
-      result.addAttribute("callee", builder->getSymbolRefAttr(func));
+      result.addAttribute("callee", builder.getSymbolRefAttr(func));
       result.addAttributes(attributes);
       result.addOperands(operands);
     }]>];
@@ -370,7 +370,7 @@ def LLVM_ExtractElementOp : LLVM_OneResultOp<"extractelement", [NoSideEffect]>,
     $res = builder.CreateExtractElement($vector, $position);
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value vector, Value position,"
+    "OpBuilder &b, OperationState &result, Value vector, Value position,"
     "ArrayRef<NamedAttribute> attrs = {}">];
   let parser = [{ return parseExtractElementOp(parser, result); }];
   let printer = [{ printExtractElementOp(p, *this); }];
@@ -401,7 +401,7 @@ def LLVM_InsertValueOp : LLVM_OneResultOp<"insertvalue", [NoSideEffect]>,
                                      extractPosition($position));
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value container, Value value, "
+    "OpBuilder &b, OperationState &result, Value container, Value value, "
     "ArrayAttr position",
     [{
       build(b, result, container.getType(), container, value, position);
@@ -418,7 +418,7 @@ def LLVM_ShuffleVectorOp
       $res = builder.CreateShuffleVector($v1, $v2, mask);
   }];
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value v1, Value v2, "
+    "OpBuilder &b, OperationState &result, Value v1, Value v2, "
     "ArrayAttr mask, ArrayRef<NamedAttribute> attrs = {}">];
   let verifier = [{
     auto wrappedVectorType1 = v1().getType().cast<LLVM::LLVMType>();
@@ -443,7 +443,7 @@ def LLVM_SelectOp
       LLVM_Builder<
           "$res = builder.CreateSelect($condition, $trueValue, $falseValue);"> {
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value condition, Value lhs, "
+    "OpBuilder &b, OperationState &result, Value condition, Value lhs, "
     "Value rhs", [{
       build(b, result, lhs.getType(), condition, lhs, rhs);
     }]>];
@@ -480,13 +480,13 @@ def LLVM_CondBrOp : LLVM_TerminatorOp<"cond_br",
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value condition,"
+    "OpBuilder &builder, OperationState &result, Value condition,"
     "Block *trueDest, ValueRange trueOperands,"
     "Block *falseDest, ValueRange falseOperands", [{
       build(builder, result, condition, trueOperands, falseOperands, trueDest,
             falseDest);
   }]>, OpBuilder<
-    "Builder *builder, OperationState &result, Value condition,"
+    "OpBuilder &builder, OperationState &result, Value condition,"
     "Block *trueDest, Block *falseDest, ValueRange falseOperands = {}", [{
       build(builder, result, condition, trueDest, ValueRange(), falseDest,
             falseOperands);
@@ -576,13 +576,13 @@ def LLVM_AddressOfOp
     : LLVM_OneResultOp<"mlir.addressof">,
       Arguments<(ins FlatSymbolRefAttr:$global_name)> {
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, LLVMType resType, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, LLVMType resType, "
               "StringRef name, ArrayRef<NamedAttribute> attrs = {}", [{
-      result.addAttribute("global_name", builder->getSymbolRefAttr(name));
+      result.addAttribute("global_name", builder.getSymbolRefAttr(name));
       result.addAttributes(attrs);
       result.addTypes(resType);}]>,
 
-    OpBuilder<"Builder *builder, OperationState &result, GlobalOp global, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, GlobalOp global, "
               "ArrayRef<NamedAttribute> attrs = {}", [{
       build(builder, result,
             global.getType().getPointerTo(global.addr_space().getZExtValue()),
@@ -629,7 +629,7 @@ def LLVM_GlobalOp
   let regions = (region AnyRegion:$initializer);
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, LLVMType type, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, LLVMType type, "
               "bool isConstant, Linkage linkage, StringRef name, "
               "Attribute value, unsigned addrSpace = 0, "
               "ArrayRef<NamedAttribute> attrs = {}">
@@ -677,7 +677,7 @@ def LLVM_LLVMFuncOp
   let skipDefaultBuilders = 1;
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, StringRef name, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, StringRef name, "
               "LLVMType type, LLVM::Linkage linkage = LLVM::Linkage::External, "
               "ArrayRef<NamedAttribute> attrs = {}, "
               "ArrayRef<NamedAttributeList> argAttrs = {}">

diff  --git a/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td b/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td
index c1b34cc690cb..5fe464231d12 100644
--- a/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td
+++ b/mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td
@@ -49,10 +49,10 @@ def Linalg_RangeOp :
     ````
   }];
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value min, Value max, "
+    "OpBuilder &builder, OperationState &result, Value min, Value max, "
     "Value step",
     [{
-      auto rangeType = RangeType::get(builder->getContext());
+      auto rangeType = RangeType::get(builder.getContext());
       build(builder, result, rangeType, min, max, step);
     }]>];
 
@@ -66,12 +66,12 @@ class Linalg_ReshapeLikeOp<string mnemonic> :
   let builders = [
     // Builder for a contracting reshape whose result type is computed from
     // `src` and `reassociation`.
-    OpBuilder<"Builder *b, OperationState &result, Value src, "
+    OpBuilder<"OpBuilder &b, OperationState &result, Value src, "
     "ArrayRef<ArrayRef<AffineExpr>> reassociation, "
     "ArrayRef<NamedAttribute> attrs = {}">,
     // Builder for a reshape whose result type is passed explicitly. This may be
     // either a contracting or expanding reshape.
-    OpBuilder<"Builder *b, OperationState &result, Type resultType, Value src,"
+    OpBuilder<"OpBuilder &b, OperationState &result, Type resultType, Value src,"
     "ArrayRef<ArrayRef<AffineExpr>> reassociation, "
     "ArrayRef<NamedAttribute> attrs = {}">];
 
@@ -227,7 +227,7 @@ def Linalg_SliceOp : Linalg_Op<"slice", [
   }];
 
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value base, "
+    "OpBuilder &b, OperationState &result, Value base, "
     "ValueRange indexings">];
 
   let extraClassDeclaration = [{
@@ -271,7 +271,7 @@ def Linalg_TransposeOp : Linalg_Op<"transpose", [NoSideEffect]>,
   }];
 
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value view, "
+    "OpBuilder &b, OperationState &result, Value view, "
     "AffineMapAttr permutation, ArrayRef<NamedAttribute> attrs = {}">];
 
   let verifier = [{

diff  --git a/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td b/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
index e7b11df3141a..966ad085245b 100644
--- a/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
+++ b/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
@@ -117,7 +117,7 @@ def CopyOp : LinalgStructured_Op<"copy", [NInputs<1>, NOutputs<1>]> {
   // TODO(ntv) this should go away once the usage of OptionalAttr triggers
   // emission of builders with default arguments left unspecified.
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value input, Value output", [{
+    "OpBuilder &builder, OperationState &result, Value input, Value output", [{
     return build(
       builder, result, input, output, AffineMapAttr(), AffineMapAttr());
   }]>];

diff  --git a/mlir/include/mlir/Dialect/LoopOps/LoopOps.td b/mlir/include/mlir/Dialect/LoopOps/LoopOps.td
index 72ba9cab760d..f0005f6ee5d1 100644
--- a/mlir/include/mlir/Dialect/LoopOps/LoopOps.td
+++ b/mlir/include/mlir/Dialect/LoopOps/LoopOps.td
@@ -135,7 +135,7 @@ def ForOp : Loop_Op<"for",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "Value lowerBound, Value upperBound, Value step, "
               "ValueRange iterArgs = llvm::None">
   ];
@@ -230,9 +230,9 @@ def IfOp : Loop_Op<"if",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "Value cond, bool withElseRegion">,
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "TypeRange resultTypes, Value cond, bool withElseRegion">
   ];
 
@@ -310,7 +310,7 @@ def ParallelOp : Loop_Op<"parallel",
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "ValueRange lowerBounds, ValueRange upperBounds, "
               "ValueRange steps, ValueRange initVals = {}">,
   ];
@@ -363,7 +363,7 @@ def ReduceOp : Loop_Op<"reduce", [HasParent<"ParallelOp">]> {
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "Value operand">
   ];
 
@@ -405,7 +405,7 @@ def YieldOp : Loop_Op<"yield", [NoSideEffect, ReturnLike, Terminator]> {
 
   let arguments = (ins Variadic<AnyType>:$results);
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result",
+    OpBuilder<"OpBuilder &builder, OperationState &result",
               [{ /* nothing to do */ }]>
   ];
 }

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVAtomicOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVAtomicOps.td
index 13eddf687f5f..12fae9972592 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVAtomicOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVAtomicOps.td
@@ -50,7 +50,7 @@ class SPV_AtomicUpdateWithValueOp<string mnemonic, list<OpTrait> traits = []> :
 
   let builders = [
     OpBuilder<
-      [{Builder *builder, OperationState &state, Value pointer,
+      [{OpBuilder &builder, OperationState &state, Value pointer,
         ::mlir::spirv::Scope scope, ::mlir::spirv::MemorySemantics memory,
         Value value}],
       [{build(builder, state, value.getType(), pointer, scope, memory, value);}]

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVCompositeOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVCompositeOps.td
index 8e83221023c4..e7f034b71525 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVCompositeOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVCompositeOps.td
@@ -111,7 +111,7 @@ def SPV_CompositeExtractOp : SPV_Op<"CompositeExtract", [NoSideEffect]> {
   );
 
   let builders = [
-    OpBuilder<[{Builder *builder, OperationState &state,
+    OpBuilder<[{OpBuilder &builder, OperationState &state,
                 Value composite, ArrayRef<int32_t> indices}]>
   ];
 

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVControlFlowOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVControlFlowOps.td
index 864c9a563d32..0e5ed27ed1c5 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVControlFlowOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVControlFlowOps.td
@@ -55,7 +55,7 @@ def SPV_BranchOp : SPV_Op<"Branch", [
 
   let builders = [
     OpBuilder<
-      "Builder *, OperationState &state, "
+      "OpBuilder &, OperationState &state, "
       "Block *successor, ValueRange arguments = {}", [{
         state.addSuccessors(successor);
         state.addOperands(arguments);
@@ -137,7 +137,7 @@ def SPV_BranchConditionalOp : SPV_Op<"BranchConditional", [
 
   let builders = [
     OpBuilder<
-      "Builder *builder, OperationState &state, Value condition, "
+      "OpBuilder &builder, OperationState &state, Value condition, "
       "Block *trueBlock, ValueRange trueArguments, "
       "Block *falseBlock, ValueRange falseArguments, "
       "Optional<std::pair<uint32_t, uint32_t>> weights = {}",
@@ -145,8 +145,8 @@ def SPV_BranchConditionalOp : SPV_Op<"BranchConditional", [
         ArrayAttr weightsAttr;
         if (weights) {
           weightsAttr =
-              builder->getI32ArrayAttr({static_cast<int32_t>(weights->first),
-                                        static_cast<int32_t>(weights->second)});
+              builder.getI32ArrayAttr({static_cast<int32_t>(weights->first),
+                                       static_cast<int32_t>(weights->second)});
         }
         build(builder, state, condition, trueArguments, falseArguments,
               weightsAttr, trueBlock, falseBlock);
@@ -290,7 +290,7 @@ def SPV_LoopOp : SPV_Op<"loop", [InFunctionScope]> {
 
   let regions = (region AnyRegion:$body);
 
-  let builders = [OpBuilder<"Builder *builder, OperationState &state">];
+  let builders = [OpBuilder<"OpBuilder &builder, OperationState &state">];
 
   let extraClassDeclaration = [{
     // Returns the entry block.
@@ -465,8 +465,8 @@ def SPV_SelectionOp : SPV_Op<"selection", [InFunctionScope]> {
     /// newly inserted spv.selection op afterwards.
     static SelectionOp createIfThen(
         Location loc, Value condition,
-        function_ref<void(OpBuilder *builder)> thenBody,
-        OpBuilder *builder);
+        function_ref<void(OpBuilder &builder)> thenBody,
+        OpBuilder &builder);
   }];
 
   let hasOpcode = 0;

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVLogicalOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVLogicalOps.td
index 11ebd5243933..24d3c413b5bc 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVLogicalOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVLogicalOps.td
@@ -854,7 +854,7 @@ def SPV_SelectOp : SPV_Op<"Select",
     SPV_SelectType:$result
   );
 
-  let builders = [OpBuilder<[{Builder *builder, OperationState &state,
+  let builders = [OpBuilder<[{OpBuilder &builder, OperationState &state,
                               Value cond, Value trueValue,
                               Value falseValue}]>];
 

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVNonUniformOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVNonUniformOps.td
index 36b0879669b9..34be336bb2a5 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVNonUniformOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVNonUniformOps.td
@@ -147,7 +147,7 @@ def SPV_GroupNonUniformElectOp : SPV_Op<"GroupNonUniformElect", []> {
   );
 
   let builders = [
-    OpBuilder<[{Builder *builder, OperationState &state, spirv::Scope}]>
+    OpBuilder<[{OpBuilder &builder, OperationState &state, spirv::Scope}]>
   ];
 
   let assemblyFormat = "$execution_scope attr-dict `:` type($result)";

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVOps.td
index c8932652bdfa..e935a85685cd 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVOps.td
@@ -93,7 +93,7 @@ def SPV_AccessChainOp : SPV_Op<"AccessChain", [NoSideEffect]> {
     SPV_AnyPtr:$component_ptr
   );
 
-  let builders = [OpBuilder<[{Builder *builder, OperationState &state,
+  let builders = [OpBuilder<[{OpBuilder &builder, OperationState &state,
                               Value basePtr, ValueRange indices}]>];
 
   let hasCanonicalizer = 1;
@@ -214,7 +214,7 @@ def SPV_ExecutionModeOp : SPV_Op<"ExecutionMode", [InModuleScope]> {
 
   let autogenSerialization = 0;
 
-  let builders = [OpBuilder<[{Builder *builder, OperationState &state,
+  let builders = [OpBuilder<[{OpBuilder &builder, OperationState &state,
                               spirv::FuncOp function,
                               spirv::ExecutionMode executionMode,
                               ArrayRef<int32_t> params}]>];
@@ -269,7 +269,7 @@ def SPV_LoadOp : SPV_Op<"Load", []> {
 
   let builders = [
     OpBuilder<[{
-      Builder *builder, OperationState &state,
+      OpBuilder &builder, OperationState &state,
       Value basePtr, IntegerAttr memory_access = {},
       IntegerAttr alignment = {}
     }]>
@@ -371,7 +371,7 @@ def SPV_StoreOp : SPV_Op<"Store", []> {
   let results = (outs);
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
       "Value ptr, Value value, ArrayRef<NamedAttribute> namedAttrs = {}", [{
       state.addOperands(ptr);
       state.addOperands(value);

diff  --git a/mlir/include/mlir/Dialect/SPIRV/SPIRVStructureOps.td b/mlir/include/mlir/Dialect/SPIRV/SPIRVStructureOps.td
index f83afab138c1..96daa2abec39 100644
--- a/mlir/include/mlir/Dialect/SPIRV/SPIRVStructureOps.td
+++ b/mlir/include/mlir/Dialect/SPIRV/SPIRVStructureOps.td
@@ -60,7 +60,7 @@ def SPV_AddressOfOp : SPV_Op<"_address_of", [InFunctionScope, NoSideEffect]> {
 
   let autogenSerialization = 0;
 
-  let builders = [OpBuilder<[{Builder *builder, OperationState &state,
+  let builders = [OpBuilder<[{OpBuilder &builder, OperationState &state,
                               spirv::GlobalVariableOp var}]>];
 
   let assemblyFormat = "$variable attr-dict `:` type($pointer)";
@@ -122,9 +122,9 @@ def SPV_ConstantOp : SPV_Op<"constant", [ConstantLike, NoSideEffect]> {
     // Creates a constant zero/one of the given `type` at the current insertion
     // point of `builder` and returns it.
     static spirv::ConstantOp getZero(Type type, Location loc,
-                                     OpBuilder *builder);
+                                     OpBuilder &builder);
     static spirv::ConstantOp getOne(Type type, Location loc,
-                                    OpBuilder *builder);
+                                    OpBuilder &builder);
   }];
 
   let hasOpcode = 0;
@@ -189,7 +189,7 @@ def SPV_EntryPointOp : SPV_Op<"EntryPoint", [InModuleScope]> {
 
   let autogenSerialization = 0;
 
-  let builders = [OpBuilder<[{Builder *builder, OperationState &state,
+  let builders = [OpBuilder<[{OpBuilder &builder, OperationState &state,
                               spirv::ExecutionModel executionModel,
                               spirv::FuncOp function,
                               ArrayRef<Attribute> interfaceVars}]>];
@@ -244,7 +244,7 @@ def SPV_FuncOp : SPV_Op<"func", [
   let verifier = [{ return success(); }];
 
   let builders = [OpBuilder<[{
-    Builder *, OperationState &state,
+    OpBuilder &, OperationState &state,
     StringRef name, FunctionType type,
     spirv::FunctionControl control = spirv::FunctionControl::None,
     ArrayRef<NamedAttribute> attrs = {}
@@ -333,15 +333,15 @@ def SPV_GlobalVariableOp : SPV_Op<"globalVariable", [InModuleScope, Symbol]> {
   let results = (outs);
 
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &state, "
+    OpBuilder<"OpBuilder &builder, OperationState &state, "
       "TypeAttr type, ArrayRef<NamedAttribute> namedAttrs", [{
       state.addAttribute("type", type);
       state.addAttributes(namedAttrs);
     }]>,
-    OpBuilder<[{Builder *builder, OperationState &state,
+    OpBuilder<[{OpBuilder &builder, OperationState &state,
                 Type type, StringRef name, unsigned descriptorSet,
                 unsigned binding}]>,
-    OpBuilder<[{Builder *builder, OperationState &state,
+    OpBuilder<[{OpBuilder &builder, OperationState &state,
                 Type type, StringRef name, spirv::BuiltIn builtin}]>
   ];
 
@@ -417,8 +417,8 @@ def SPV_ModuleOp : SPV_Op<"module",
   let regions = (region SizedRegion<1>:$body);
 
   let builders = [
-    OpBuilder<[{Builder *, OperationState &state}]>,
-    OpBuilder<[{Builder *, OperationState &state,
+    OpBuilder<[{OpBuilder &, OperationState &state}]>,
+    OpBuilder<[{OpBuilder &, OperationState &state,
                 spirv::AddressingModel addressing_model,
                 spirv::MemoryModel memory_model}]>
   ];

diff  --git a/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td b/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td
index fa277f4f89de..4b8ec1d7ed91 100644
--- a/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td
+++ b/mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td
@@ -334,7 +334,7 @@ def Shape_YieldOp : Shape_Op<"yield", [NoSideEffect, Terminator]> {
   let arguments = (ins Variadic<AnyType>:$operands);
 
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result", [{ build(b, result, llvm::None); }]
+    "OpBuilder &b, OperationState &result", [{ build(b, result, llvm::None); }]
   >];
 
   let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?";

diff  --git a/mlir/include/mlir/Dialect/StandardOps/IR/Ops.h b/mlir/include/mlir/Dialect/StandardOps/IR/Ops.h
index d28e22c5b61b..51228d3e8437 100644
--- a/mlir/include/mlir/Dialect/StandardOps/IR/Ops.h
+++ b/mlir/include/mlir/Dialect/StandardOps/IR/Ops.h
@@ -47,7 +47,7 @@ class ConstantFloatOp : public ConstantOp {
   using ConstantOp::ConstantOp;
 
   /// Builds a constant float op producing a float of the specified type.
-  static void build(Builder *builder, OperationState &result,
+  static void build(OpBuilder &builder, OperationState &result,
                     const APFloat &value, FloatType type);
 
   APFloat getValue() { return getAttrOfType<FloatAttr>("value").getValue(); }
@@ -64,12 +64,12 @@ class ConstantIntOp : public ConstantOp {
 public:
   using ConstantOp::ConstantOp;
   /// Build a constant int op producing an integer of the specified width.
-  static void build(Builder *builder, OperationState &result, int64_t value,
+  static void build(OpBuilder &builder, OperationState &result, int64_t value,
                     unsigned width);
 
   /// Build a constant int op producing an integer with the specified type,
   /// which must be an integer type.
-  static void build(Builder *builder, OperationState &result, int64_t value,
+  static void build(OpBuilder &builder, OperationState &result, int64_t value,
                     Type type);
 
   int64_t getValue() { return getAttrOfType<IntegerAttr>("value").getInt(); }
@@ -87,7 +87,7 @@ class ConstantIndexOp : public ConstantOp {
   using ConstantOp::ConstantOp;
 
   /// Build a constant int op producing an index.
-  static void build(Builder *builder, OperationState &result, int64_t value);
+  static void build(OpBuilder &builder, OperationState &result, int64_t value);
 
   int64_t getValue() { return getAttrOfType<IntegerAttr>("value").getInt(); }
 
@@ -136,7 +136,7 @@ class DmaStartOp
 public:
   using Op::Op;
 
-  static void build(Builder *builder, OperationState &result, Value srcMemRef,
+  static void build(OpBuilder &builder, OperationState &result, Value srcMemRef,
                     ValueRange srcIndices, Value destMemRef,
                     ValueRange destIndices, Value numElements, Value tagMemRef,
                     ValueRange tagIndices, Value stride = nullptr,
@@ -260,7 +260,7 @@ class DmaWaitOp
 public:
   using Op::Op;
 
-  static void build(Builder *builder, OperationState &result, Value tagMemRef,
+  static void build(OpBuilder &builder, OperationState &result, Value tagMemRef,
                     ValueRange tagIndices, Value numElements);
 
   static StringRef getOperationName() { return "std.dma_wait"; }

diff  --git a/mlir/include/mlir/Dialect/StandardOps/IR/Ops.td b/mlir/include/mlir/Dialect/StandardOps/IR/Ops.td
index 1eac2af639d4..7db3dd849c81 100644
--- a/mlir/include/mlir/Dialect/StandardOps/IR/Ops.td
+++ b/mlir/include/mlir/Dialect/StandardOps/IR/Ops.td
@@ -47,7 +47,7 @@ class CastOp<string mnemonic, list<OpTrait> traits = []> :
   let results = (outs AnyType);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source, Type destType", [{
+    "OpBuilder &builder, OperationState &result, Value source, Type destType", [{
        impl::buildCastOp(builder, result, source, destType);
   }]>];
 
@@ -139,11 +139,11 @@ class AllocLikeOp<string mnemonic,
   let results = (outs Arg<AnyMemRef, "", resultDecorators>);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, MemRefType memrefType", [{
+    "OpBuilder &builder, OperationState &result, MemRefType memrefType", [{
        result.types.push_back(memrefType);
      }]>,
     OpBuilder<
-    "Builder *builder, OperationState &result, MemRefType memrefType, " #
+    "OpBuilder &builder, OperationState &result, MemRefType memrefType, " #
     "ValueRange operands, IntegerAttr alignment = IntegerAttr()", [{
        result.addOperands(operands);
        result.types.push_back(memrefType);
@@ -528,7 +528,7 @@ def GenericAtomicRMWOp : Std_Op<"generic_atomic_rmw", [
 
   let skipDefaultBuilders = 1;
   let builders = [
-    OpBuilder<"Builder *builder, OperationState &result, "
+    OpBuilder<"OpBuilder &builder, OperationState &result, "
               "Value memref, ValueRange ivs">
   ];
 
@@ -583,7 +583,7 @@ def BranchOp : Std_Op<"br",
   let arguments = (ins Variadic<AnyType>:$destOperands);
   let successors = (successor AnySuccessor:$dest);
 
-  let builders = [OpBuilder<"Builder *, OperationState &result, Block *dest, "
+  let builders = [OpBuilder<"OpBuilder &, OperationState &result, Block *dest, "
                             "ValueRange destOperands = {}", [{
     result.addSuccessors(dest);
     result.addOperands(destOperands);
@@ -633,21 +633,21 @@ def CallOp : Std_Op<"call", [CallOpInterface]> {
   let results = (outs Variadic<AnyType>);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, FuncOp callee,"
+    "OpBuilder &builder, OperationState &result, FuncOp callee,"
     "ValueRange operands = {}", [{
       result.addOperands(operands);
-      result.addAttribute("callee", builder->getSymbolRefAttr(callee));
+      result.addAttribute("callee", builder.getSymbolRefAttr(callee));
       result.addTypes(callee.getType().getResults());
   }]>, OpBuilder<
-    "Builder *builder, OperationState &result, SymbolRefAttr callee,"
+    "OpBuilder &builder, OperationState &result, SymbolRefAttr callee,"
     "ArrayRef<Type> results, ValueRange operands = {}", [{
       result.addOperands(operands);
       result.addAttribute("callee", callee);
       result.addTypes(results);
   }]>, OpBuilder<
-    "Builder *builder, OperationState &result, StringRef callee,"
+    "OpBuilder &builder, OperationState &result, StringRef callee,"
     "ArrayRef<Type> results, ValueRange operands = {}", [{
-      build(builder, result, builder->getSymbolRefAttr(callee), results,
+      build(builder, result, builder.getSymbolRefAttr(callee), results,
             operands);
   }]>];
 
@@ -709,7 +709,7 @@ def CallIndirectOp : Std_Op<"call_indirect", [
   let results = (outs Variadic<AnyType>:$results);
 
   let builders = [OpBuilder<
-    "Builder *, OperationState &result, Value callee,"
+    "OpBuilder &, OperationState &result, Value callee,"
     "ValueRange operands = {}", [{
       result.operands.push_back(callee);
       result.addOperands(operands);
@@ -842,7 +842,7 @@ def CmpFOp : Std_Op<"cmpf",
   let results = (outs BoolLike:$result);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, CmpFPredicate predicate,"
+    "OpBuilder &builder, OperationState &result, CmpFPredicate predicate,"
     "Value lhs, Value rhs", [{
       ::buildCmpFOp(builder, result, predicate, lhs, rhs);
   }]>];
@@ -964,7 +964,7 @@ def CmpIOp : Std_Op<"cmpi",
   let results = (outs BoolLike:$result);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, CmpIPredicate predicate,"
+    "OpBuilder &builder, OperationState &result, CmpIPredicate predicate,"
     "Value lhs, Value rhs", [{
       ::buildCmpIOp(builder, result, predicate, lhs, rhs);
   }]>];
@@ -1027,13 +1027,13 @@ def CondBranchOp : Std_Op<"cond_br",
   let successors = (successor AnySuccessor:$trueDest, AnySuccessor:$falseDest);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value condition,"
+    "OpBuilder &builder, OperationState &result, Value condition,"
     "Block *trueDest, ValueRange trueOperands,"
     "Block *falseDest, ValueRange falseOperands", [{
       build(builder, result, condition, trueOperands, falseOperands, trueDest,
             falseDest);
   }]>, OpBuilder<
-    "Builder *builder, OperationState &result, Value condition,"
+    "OpBuilder &builder, OperationState &result, Value condition,"
     "Block *trueDest, Block *falseDest, ValueRange falseOperands = {}", [{
       build(builder, result, condition, trueDest, ValueRange(), falseDest,
             falseOperands);
@@ -1165,7 +1165,7 @@ def ConstantOp : Std_Op<"constant",
   let results = (outs AnyType);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Attribute value",
+    "OpBuilder &builder, OperationState &result, Attribute value",
     [{ build(builder, result, value.getType(), value); }]>];
 
   let extraClassDeclaration = [{
@@ -1314,10 +1314,10 @@ def DimOp : Std_Op<"dim", [NoSideEffect]> {
   let results = (outs Index);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value memrefOrTensor,"
+    "OpBuilder &builder, OperationState &result, Value memrefOrTensor,"
     "unsigned index", [{
-      auto indexType = builder->getIndexType();
-      auto indexAttr = builder->getIntegerAttr(indexType, index);
+      auto indexType = builder.getIndexType();
+      auto indexAttr = builder.getIntegerAttr(indexType, index);
       build(builder, result, indexType, memrefOrTensor, indexAttr);
     }]>];
 
@@ -1410,7 +1410,7 @@ def ExtractElementOp : Std_Op<"extract_element",
   let results = (outs AnyType:$result);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value aggregate,"
+    "OpBuilder &builder, OperationState &result, Value aggregate,"
     "ValueRange indices = {}", [{
       auto resType = aggregate.getType().cast<ShapedType>()
                                          .getElementType();
@@ -1548,7 +1548,7 @@ def LoadOp : Std_Op<"load",
   let results = (outs AnyType:$result);
 
   let builders = [OpBuilder<
-    "Builder *, OperationState &result, Value memref,"
+    "OpBuilder &, OperationState &result, Value memref,"
     "ValueRange indices = {}", [{
       auto memrefType = memref.getType().cast<MemRefType>();
       result.addOperands(memref);
@@ -1800,12 +1800,12 @@ def PrefetchOp : Std_Op<"prefetch"> {
                    BoolAttr:$isDataCache);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value memref,"
+    "OpBuilder &builder, OperationState &result, Value memref,"
     "ArrayRef<Value> indices, bool isWrite, unsigned hint, bool isData",
     [{
-      auto hintAttr = builder->getI32IntegerAttr(hint);
-      auto isWriteAttr = builder->getBoolAttr(isWrite);
-      auto isDataCacheAttr = builder->getBoolAttr(isData);
+      auto hintAttr = builder.getI32IntegerAttr(hint);
+      auto isWriteAttr = builder.getBoolAttr(isWrite);
+      auto isDataCacheAttr = builder.getBoolAttr(isData);
       result.addOperands(memref);
       result.addOperands(indices);
       result.addAttribute("localityHint", hintAttr);
@@ -1846,8 +1846,8 @@ def RankOp : Std_Op<"rank", [NoSideEffect]> {
   let verifier = ?;
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value tensor", [{
-      auto indexType = builder->getIndexType();
+    "OpBuilder &builder, OperationState &result, Value tensor", [{
+      auto indexType = builder.getIndexType();
       build(builder, result, indexType, tensor);
     }]>];
 
@@ -1889,7 +1889,7 @@ def ReturnOp : Std_Op<"return", [NoSideEffect, HasParent<"FuncOp">, ReturnLike,
   let arguments = (ins Variadic<AnyType>:$operands);
 
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result", [{ build(b, result, llvm::None); }]
+    "OpBuilder &b, OperationState &result", [{ build(b, result, llvm::None); }]
   >];
 
   let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?";
@@ -1954,7 +1954,7 @@ def SelectOp : Std_Op<"select", [NoSideEffect,
   let results = (outs AnyType:$result);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value condition,"
+    "OpBuilder &builder, OperationState &result, Value condition,"
     "Value trueValue, Value falseValue", [{
       result.addOperands({condition, trueValue, falseValue});
       result.addTypes(trueValue.getType());
@@ -2113,7 +2113,7 @@ def SignExtendIOp : Std_Op<"sexti",
   let results = (outs SignlessIntegerLike);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value value, Type destType", [{
+    "OpBuilder &builder, OperationState &result, Value value, Type destType", [{
       result.addOperands(value);
       result.addTypes(destType);
   }]>];
@@ -2187,7 +2187,7 @@ def SplatOp : Std_Op<"splat", [NoSideEffect,
   let results = (outs AnyTypeOf<[AnyVector, AnyStaticShapeTensor]>:$aggregate);
 
   let builders =
-      [OpBuilder<"Builder *builder, OperationState &result, Value element, "
+      [OpBuilder<"OpBuilder &builder, OperationState &result, Value element, "
                   "Type aggregateType",
                   [{ build(builder, result, aggregateType, element); }]>];
 
@@ -2265,7 +2265,7 @@ def StoreOp : Std_Op<"store",
                        Variadic<Index>:$indices);
 
   let builders = [OpBuilder<
-    "Builder *, OperationState &result, Value valueToStore, Value memref", [{
+    "OpBuilder &, OperationState &result, Value valueToStore, Value memref", [{
       result.addOperands(valueToStore);
       result.addOperands(memref);
   }]>];
@@ -2445,12 +2445,12 @@ def SubViewOp : Std_Op<"subview", [
 
   let builders = [
     OpBuilder<
-      "Builder *b, OperationState &result, Value source, "
+      "OpBuilder &b, OperationState &result, Value source, "
       "ValueRange offsets, ValueRange sizes, "
       "ValueRange strides, Type resultType = Type(), "
       "ArrayRef<NamedAttribute> attrs = {}">,
     OpBuilder<
-      "Builder *builder, OperationState &result, "
+      "OpBuilder &builder, OperationState &result, "
       "Type resultType, Value source">
   ];
 
@@ -2603,7 +2603,7 @@ def TensorLoadOp : Std_Op<"tensor_load",
   let verifier = ?;
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value memref", [{
+    "OpBuilder &builder, OperationState &result, Value memref", [{
       auto memrefType = memref.getType().cast<MemRefType>();
       auto resultType = RankedTensorType::get(memrefType.getShape(),
                                               memrefType.getElementType());
@@ -2679,7 +2679,7 @@ def TruncateIOp : Std_Op<"trunci", [NoSideEffect, SameOperandsAndResultShape]> {
   let results = (outs SignlessIntegerLike);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value value, Type destType", [{
+    "OpBuilder &builder, OperationState &result, Value value, Type destType", [{
       result.addOperands(value);
       result.addTypes(destType);
   }]>];
@@ -2910,7 +2910,7 @@ def ZeroExtendIOp : Std_Op<"zexti", [NoSideEffect, SameOperandsAndResultShape]>
   let results = (outs SignlessIntegerLike);
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value value, Type destType", [{
+    "OpBuilder &builder, OperationState &result, Value value, Type destType", [{
       result.addOperands(value);
       result.addTypes(destType);
   }]>];

diff  --git a/mlir/include/mlir/Dialect/Vector/VectorOps.td b/mlir/include/mlir/Dialect/Vector/VectorOps.td
index 0abfbdc9c0da..46c6f5773bf0 100644
--- a/mlir/include/mlir/Dialect/Vector/VectorOps.td
+++ b/mlir/include/mlir/Dialect/Vector/VectorOps.td
@@ -143,10 +143,10 @@ def Vector_ContractionOp :
     ```
   }];
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value lhs, Value rhs, "
+    "OpBuilder &builder, OperationState &result, Value lhs, Value rhs, "
     "Value acc, ArrayAttr indexingMaps, ArrayAttr iteratorTypes">,
     OpBuilder<
-      "Builder *builder, OperationState &result, Value lhs, Value rhs, "
+      "OpBuilder &builder, OperationState &result, Value lhs, Value rhs, "
       "Value acc, ArrayRef<ArrayRef<AffineExpr>> indexingExprs, "
       "ArrayRef<StringRef> iteratorTypes">];
   let extraClassDeclaration = [{
@@ -304,7 +304,7 @@ def Vector_ShuffleOp :
                : vector<2xf32>, vector<2xf32>       ; yields vector<4xf32>
     ```
   }];
-  let builders = [OpBuilder<"Builder *builder, OperationState &result,"
+  let builders = [OpBuilder<"OpBuilder &builder, OperationState &result,"
                             "Value v1, Value v2, ArrayRef<int64_t>">];
   let extraClassDeclaration = [{
     static StringRef getMaskAttrName() { return "mask"; }
@@ -372,7 +372,7 @@ def Vector_ExtractOp :
     ```
   }];
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source,"
+    "OpBuilder &builder, OperationState &result, Value source,"
     "ArrayRef<int64_t>">];
   let extraClassDeclaration = [{
     static StringRef getPositionAttrName() { return "position"; }
@@ -418,7 +418,7 @@ def Vector_ExtractSlicesOp :
     ```
   }];
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, TupleType tupleType, " #
+    "OpBuilder &builder, OperationState &result, TupleType tupleType, " #
     "Value vector, ArrayRef<int64_t> sizes, " #
     "ArrayRef<int64_t> strides">];
   let extraClassDeclaration = [{
@@ -464,7 +464,7 @@ def Vector_FMAOp :
   let verifier = ?;
   let assemblyFormat = "$lhs `,` $rhs `,` $acc attr-dict `:` type($lhs)";
   let builders = [OpBuilder<
-    "Builder *b, OperationState &result, Value lhs, Value rhs, Value acc",
+    "OpBuilder &b, OperationState &result, Value lhs, Value rhs, Value acc",
     "build(b, result, lhs.getType(), lhs, rhs, acc);">];
   let extraClassDeclaration = [{
     VectorType getVectorType() { return lhs().getType().cast<VectorType>(); }
@@ -535,7 +535,7 @@ def Vector_InsertOp :
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source, " #
+    "OpBuilder &builder, OperationState &result, Value source, " #
     "Value dest, ArrayRef<int64_t>">];
   let extraClassDeclaration = [{
     static StringRef getPositionAttrName() { return "position"; }
@@ -638,7 +638,7 @@ def Vector_InsertStridedSliceOp :
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source, Value dest, " #
+    "OpBuilder &builder, OperationState &result, Value source, Value dest, " #
     "ArrayRef<int64_t> offsets, ArrayRef<int64_t> strides">];
   let extraClassDeclaration = [{
     static StringRef getOffsetsAttrName() { return "offsets"; }
@@ -849,7 +849,7 @@ def Vector_StridedSliceOp :
     ```
   }];
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source, " #
+    "OpBuilder &builder, OperationState &result, Value source, " #
     "ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, " #
     "ArrayRef<int64_t> strides">];
   let extraClassDeclaration = [{
@@ -1155,7 +1155,7 @@ def Vector_TypeCastOp :
   }];
 
   let builders = [OpBuilder<
-    "Builder *builder, OperationState &result, Value source">];
+    "OpBuilder &builder, OperationState &result, Value source">];
 
   let parser = [{
     return impl::parseCastOp(parser, result);
@@ -1439,13 +1439,13 @@ def Vector_MatmulOp : Vector_Op<"matrix_multiply", [NoSideEffect,
     ```
   }];
   let builders = [
-   OpBuilder<"Builder *builder, OperationState &result, Value lhs, Value rhs, "
+   OpBuilder<"OpBuilder &builder, OperationState &result, Value lhs, Value rhs, "
              "unsigned lhsRows, unsigned lhsColumns, unsigned rhsColumns",
    [{
      result.addOperands({lhs, rhs});
-     result.addAttribute("lhs_rows", builder->getI32IntegerAttr(lhsRows));
-     result.addAttribute("lhs_columns", builder->getI32IntegerAttr(lhsColumns));
-     result.addAttribute("rhs_columns", builder->getI32IntegerAttr(rhsColumns));
+     result.addAttribute("lhs_rows", builder.getI32IntegerAttr(lhsRows));
+     result.addAttribute("lhs_columns", builder.getI32IntegerAttr(lhsColumns));
+     result.addAttribute("rhs_columns", builder.getI32IntegerAttr(rhsColumns));
      result.addTypes(VectorType::get(lhsRows * rhsColumns,
        lhs.getType().cast<VectorType>().getElementType()));
    }]>,

diff  --git a/mlir/include/mlir/IR/Builders.h b/mlir/include/mlir/IR/Builders.h
index b9ef11648e38..23c5ea2edb2a 100644
--- a/mlir/include/mlir/IR/Builders.h
+++ b/mlir/include/mlir/IR/Builders.h
@@ -327,7 +327,7 @@ class OpBuilder : public Builder {
   template <typename OpTy, typename... Args>
   OpTy create(Location location, Args &&... args) {
     OperationState state(location, OpTy::getOperationName());
-    OpTy::build(this, state, std::forward<Args>(args)...);
+    OpTy::build(*this, state, std::forward<Args>(args)...);
     auto *op = createOperation(state);
     auto result = dyn_cast<OpTy>(op);
     assert(result && "builder didn't return the right type");
@@ -343,7 +343,7 @@ class OpBuilder : public Builder {
     // Create the operation without using 'createOperation' as we don't want to
     // insert it yet.
     OperationState state(location, OpTy::getOperationName());
-    OpTy::build(this, state, std::forward<Args>(args)...);
+    OpTy::build(*this, state, std::forward<Args>(args)...);
     Operation *op = Operation::create(state);
 
     // Fold the operation. If successful destroy it, otherwise insert it.

diff  --git a/mlir/include/mlir/IR/Function.h b/mlir/include/mlir/IR/Function.h
index 3e26f8f7399d..93f805a24f46 100644
--- a/mlir/include/mlir/IR/Function.h
+++ b/mlir/include/mlir/IR/Function.h
@@ -50,9 +50,9 @@ class FuncOp
                        ArrayRef<NamedAttribute> attrs,
                        ArrayRef<NamedAttributeList> argAttrs);
 
-  static void build(Builder *builder, OperationState &result, StringRef name,
+  static void build(OpBuilder &builder, OperationState &result, StringRef name,
                     FunctionType type, ArrayRef<NamedAttribute> attrs);
-  static void build(Builder *builder, OperationState &result, StringRef name,
+  static void build(OpBuilder &builder, OperationState &result, StringRef name,
                     FunctionType type, ArrayRef<NamedAttribute> attrs,
                     ArrayRef<NamedAttributeList> argAttrs);
 

diff  --git a/mlir/include/mlir/IR/Module.h b/mlir/include/mlir/IR/Module.h
index c8adc15646ef..4f0bba773ee2 100644
--- a/mlir/include/mlir/IR/Module.h
+++ b/mlir/include/mlir/IR/Module.h
@@ -39,7 +39,7 @@ class ModuleOp
 
   static StringRef getOperationName() { return "module"; }
 
-  static void build(Builder *builder, OperationState &result,
+  static void build(OpBuilder &builder, OperationState &result,
                     Optional<StringRef> name = llvm::None);
 
   /// Construct a module from the given location with an optional name.
@@ -117,7 +117,7 @@ class ModuleTerminatorOp
 public:
   using Op::Op;
   static StringRef getOperationName() { return "module_terminator"; }
-  static void build(Builder *, OperationState &) {}
+  static void build(OpBuilder &, OperationState &) {}
 };
 
 /// This class acts as an owning reference to a module, and will automatically

diff  --git a/mlir/include/mlir/IR/OpBase.td b/mlir/include/mlir/IR/OpBase.td
index 849ed1a1e6bc..59be44672aa3 100644
--- a/mlir/include/mlir/IR/OpBase.td
+++ b/mlir/include/mlir/IR/OpBase.td
@@ -1803,7 +1803,7 @@ def successor;
 // The signature of the builder is always
 //
 // ```c++
-// static void build(Builder *builder, OperationState &state,
+// static void build(OpBuilder &builder, OperationState &state,
 //                   <other-parameters>...) {
 //   <body>...
 // }
@@ -1883,7 +1883,7 @@ class Op<Dialect dialect, string mnemonic, list<OpTrait> props = []> {
   // following signatures:
   //
   // ```c++
-  // static void build(Builder *, OperationState &odsState,
+  // static void build(OpBuilder &, OperationState &odsState,
   //                   Type <result0-name>, Type <result1-name>, ...,
   //                   Value <arg0-name>, Value <arg1-name>, ...,
   //                   Attribute <attr0-name>, Attribute <attr1-name>, ...);
@@ -1891,7 +1891,7 @@ class Op<Dialect dialect, string mnemonic, list<OpTrait> props = []> {
   // * where the attributes follow the same declaration order as in the op.
   //
   // ```c++
-  // static void build(Builder *, OperationState &odsState,
+  // static void build(OpBuilder &, OperationState &odsState,
   //                   ArrayRef<Type> resultTypes,
   //                   ArrayRef<Value> operands,
   //                   ArrayRef<NamedAttribute> attributes);

diff  --git a/mlir/include/mlir/IR/OpDefinition.h b/mlir/include/mlir/IR/OpDefinition.h
index d066c1599714..107234a7158e 100644
--- a/mlir/include/mlir/IR/OpDefinition.h
+++ b/mlir/include/mlir/IR/OpDefinition.h
@@ -25,6 +25,7 @@
 
 namespace mlir {
 class Builder;
+class OpBuilder;
 
 namespace OpTrait {
 template <typename ConcreteType> class OneResult;
@@ -77,14 +78,15 @@ namespace impl {
 /// region's only block if it does not have a terminator already. If the region
 /// is empty, insert a new block first. `buildTerminatorOp` should return the
 /// terminator operation to insert.
-void ensureRegionTerminator(Region &region, Location loc,
-                            function_ref<Operation *()> buildTerminatorOp);
+void ensureRegionTerminator(
+    Region &region, Location loc,
+    function_ref<Operation *(OpBuilder &)> buildTerminatorOp);
 /// Templated version that fills the generates the provided operation type.
 template <typename OpTy>
 void ensureRegionTerminator(Region &region, Builder &builder, Location loc) {
-  ensureRegionTerminator(region, loc, [&] {
+  ensureRegionTerminator(region, loc, [&](OpBuilder &b) {
     OperationState state(loc, OpTy::getOperationName());
-    OpTy::build(&builder, state);
+    OpTy::build(b, state);
     return Operation::create(state);
   });
 }
@@ -1422,7 +1424,7 @@ namespace impl {
 ParseResult parseOneResultOneOperandTypeOp(OpAsmParser &parser,
                                            OperationState &result);
 
-void buildBinaryOp(Builder *builder, OperationState &result, Value lhs,
+void buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs,
                    Value rhs);
 ParseResult parseOneResultSameOperandTypeOp(OpAsmParser &parser,
                                             OperationState &result);
@@ -1436,7 +1438,7 @@ void printOneResultOp(Operation *op, OpAsmPrinter &p);
 // These functions are out-of-line implementations of the methods in CastOp,
 // which avoids them being template instantiated/duplicated.
 namespace impl {
-void buildCastOp(Builder *builder, OperationState &result, Value source,
+void buildCastOp(OpBuilder &builder, OperationState &result, Value source,
                  Type destType);
 ParseResult parseCastOp(OpAsmParser &parser, OperationState &result);
 void printCastOp(Operation *op, OpAsmPrinter &p);

diff  --git a/mlir/include/mlir/IR/PatternMatch.h b/mlir/include/mlir/IR/PatternMatch.h
index 6dbc5b9664d0..9476bcf3bf84 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -218,7 +218,7 @@ class PatternRewriter : public OpBuilder {
   template <typename OpTy, typename... Args>
   OpTy create(Location location, Args... args) {
     OperationState state(location, OpTy::getOperationName());
-    OpTy::build(this, state, args...);
+    OpTy::build(*this, state, args...);
     auto *op = createOperation(state);
     auto result = dyn_cast<OpTy>(op);
     assert(result && "Builder didn't return the right type");
@@ -231,7 +231,7 @@ class PatternRewriter : public OpBuilder {
   template <typename OpTy, typename... Args>
   OpTy createChecked(Location location, Args... args) {
     OperationState state(location, OpTy::getOperationName());
-    OpTy::build(this, state, args...);
+    OpTy::build(*this, state, args...);
     auto *op = createOperation(state);
 
     // If the Operation we produce is valid, return it.

diff  --git a/mlir/include/mlir/Transforms/FoldUtils.h b/mlir/include/mlir/Transforms/FoldUtils.h
index 4155533b122e..f8c678d11b6a 100644
--- a/mlir/include/mlir/Transforms/FoldUtils.h
+++ b/mlir/include/mlir/Transforms/FoldUtils.h
@@ -81,7 +81,7 @@ class OperationFolder {
     // fold). Using create methods of the builder will insert the op, so not
     // using it here.
     OperationState state(location, OpTy::getOperationName());
-    OpTy::build(&builder, state, std::forward<Args>(args)...);
+    OpTy::build(builder, state, std::forward<Args>(args)...);
     Operation *op = Operation::create(state);
 
     if (failed(tryToFold(builder, op, results)) || op->getNumResults() == 0) {

diff  --git a/mlir/lib/Conversion/LinalgToSPIRV/LinalgToSPIRV.cpp b/mlir/lib/Conversion/LinalgToSPIRV/LinalgToSPIRV.cpp
index 14fdc9b207fb..cf67b96fce1e 100644
--- a/mlir/lib/Conversion/LinalgToSPIRV/LinalgToSPIRV.cpp
+++ b/mlir/lib/Conversion/LinalgToSPIRV/LinalgToSPIRV.cpp
@@ -164,7 +164,7 @@ LogicalResult SingleWorkgroupReduction::matchAndRewrite(
 
   // Get the output element accessed by this reduction.
   Value zero = spirv::ConstantOp::getZero(
-      typeConverter.getIndexType(rewriter.getContext()), loc, &rewriter);
+      typeConverter.getIndexType(rewriter.getContext()), loc, rewriter);
   SmallVector<Value, 1> zeroIndices(originalOutputType.getRank(), zero);
   Value outputElementPtr =
       spirv::getElementPtr(typeConverter, originalOutputType, convertedOutput,
@@ -181,18 +181,18 @@ LogicalResult SingleWorkgroupReduction::matchAndRewrite(
   Value condition = rewriter.create<spirv::GroupNonUniformElectOp>(
       loc, spirv::Scope::Subgroup);
 
-  auto createAtomicOp = [&](OpBuilder *builder) {
+  auto createAtomicOp = [&](OpBuilder &builder) {
 #define CREATE_ATOMIC_BIN_OP(opKind, spvOp)                                    \
   case linalg::RegionMatcher::BinaryOpKind::opKind: {                          \
-    builder->create<spirv::spvOp>(loc, outputElementPtr, spirv::Scope::Device, \
-                                  spirv::MemorySemantics::AcquireRelease,      \
-                                  groupOperation);                             \
+    builder.create<spirv::spvOp>(loc, outputElementPtr, spirv::Scope::Device,  \
+                                 spirv::MemorySemantics::AcquireRelease,       \
+                                 groupOperation);                              \
   } break
     switch (*binaryOpKind) { CREATE_ATOMIC_BIN_OP(IAdd, AtomicIAddOp); }
 #undef CREATE_ATOMIC_BIN_OP
   };
 
-  spirv::SelectionOp::createIfThen(loc, condition, createAtomicOp, &rewriter);
+  spirv::SelectionOp::createIfThen(loc, condition, createAtomicOp, rewriter);
 
   rewriter.eraseOp(genericOp);
   return success();

diff  --git a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
index b64ce80bc0d0..8947c2852bac 100644
--- a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
+++ b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
@@ -920,7 +920,7 @@ static LogicalResult foldMemRefCast(Operation *op) {
 //===----------------------------------------------------------------------===//
 
 // TODO(b/133776335) Check that map operands are loop IVs or symbols.
-void AffineDmaStartOp::build(Builder *builder, OperationState &result,
+void AffineDmaStartOp::build(OpBuilder &builder, OperationState &result,
                              Value srcMemRef, AffineMap srcMap,
                              ValueRange srcIndices, Value destMemRef,
                              AffineMap dstMap, ValueRange destIndices,
@@ -1090,7 +1090,7 @@ LogicalResult AffineDmaStartOp::fold(ArrayRef<Attribute> cstOperands,
 //===----------------------------------------------------------------------===//
 
 // TODO(b/133776335) Check that map operands are loop IVs or symbols.
-void AffineDmaWaitOp::build(Builder *builder, OperationState &result,
+void AffineDmaWaitOp::build(OpBuilder &builder, OperationState &result,
                             Value tagMemRef, AffineMap tagMap,
                             ValueRange tagIndices, Value numElements) {
   result.addOperands(tagMemRef);
@@ -1166,7 +1166,7 @@ LogicalResult AffineDmaWaitOp::fold(ArrayRef<Attribute> cstOperands,
 // AffineForOp
 //===----------------------------------------------------------------------===//
 
-void AffineForOp::build(Builder *builder, OperationState &result,
+void AffineForOp::build(OpBuilder &builder, OperationState &result,
                         ValueRange lbOperands, AffineMap lbMap,
                         ValueRange ubOperands, AffineMap ubMap, int64_t step) {
   assert(((!lbMap && lbOperands.empty()) ||
@@ -1179,7 +1179,7 @@ void AffineForOp::build(Builder *builder, OperationState &result,
 
   // Add an attribute for the step.
   result.addAttribute(getStepAttrName(),
-                      builder->getIntegerAttr(builder->getIndexType(), step));
+                      builder.getIntegerAttr(builder.getIndexType(), step));
 
   // Add the lower bound.
   result.addAttribute(getLowerBoundAttrName(), AffineMapAttr::get(lbMap));
@@ -1193,15 +1193,15 @@ void AffineForOp::build(Builder *builder, OperationState &result,
   // the loop induction variable.
   Region *bodyRegion = result.addRegion();
   Block *body = new Block();
-  body->addArgument(IndexType::get(builder->getContext()));
+  body->addArgument(IndexType::get(builder.getContext()));
   bodyRegion->push_back(body);
-  ensureTerminator(*bodyRegion, *builder, result.location);
+  ensureTerminator(*bodyRegion, builder, result.location);
 }
 
-void AffineForOp::build(Builder *builder, OperationState &result, int64_t lb,
+void AffineForOp::build(OpBuilder &builder, OperationState &result, int64_t lb,
                         int64_t ub, int64_t step) {
-  auto lbMap = AffineMap::getConstantMap(lb, builder->getContext());
-  auto ubMap = AffineMap::getConstantMap(ub, builder->getContext());
+  auto lbMap = AffineMap::getConstantMap(lb, builder.getContext());
+  auto ubMap = AffineMap::getConstantMap(ub, builder.getContext());
   return build(builder, result, {}, lbMap, {}, ubMap, step);
 }
 
@@ -1806,15 +1806,15 @@ void AffineIfOp::setConditional(IntegerSet set, ValueRange operands) {
   getOperation()->setOperands(operands);
 }
 
-void AffineIfOp::build(Builder *builder, OperationState &result, IntegerSet set,
-                       ValueRange args, bool withElseRegion) {
+void AffineIfOp::build(OpBuilder &builder, OperationState &result,
+                       IntegerSet set, ValueRange args, bool withElseRegion) {
   result.addOperands(args);
   result.addAttribute(getConditionAttrName(), IntegerSetAttr::get(set));
   Region *thenRegion = result.addRegion();
   Region *elseRegion = result.addRegion();
-  AffineIfOp::ensureTerminator(*thenRegion, *builder, result.location);
+  AffineIfOp::ensureTerminator(*thenRegion, builder, result.location);
   if (withElseRegion)
-    AffineIfOp::ensureTerminator(*elseRegion, *builder, result.location);
+    AffineIfOp::ensureTerminator(*elseRegion, builder, result.location);
 }
 
 /// Canonicalize an affine if op's conditional (integer set + operands).
@@ -1845,7 +1845,7 @@ void AffineIfOp::getCanonicalizationPatterns(OwningRewritePatternList &results,
 // AffineLoadOp
 //===----------------------------------------------------------------------===//
 
-void AffineLoadOp::build(Builder *builder, OperationState &result,
+void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
                          AffineMap map, ValueRange operands) {
   assert(operands.size() == 1 + map.getNumInputs() && "inconsistent operands");
   result.addOperands(operands);
@@ -1855,8 +1855,8 @@ void AffineLoadOp::build(Builder *builder, OperationState &result,
   result.types.push_back(memrefType.getElementType());
 }
 
-void AffineLoadOp::build(Builder *builder, OperationState &result, Value memref,
-                         AffineMap map, ValueRange mapOperands) {
+void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
+                         Value memref, AffineMap map, ValueRange mapOperands) {
   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
   result.addOperands(memref);
   result.addOperands(mapOperands);
@@ -1865,14 +1865,14 @@ void AffineLoadOp::build(Builder *builder, OperationState &result, Value memref,
   result.types.push_back(memrefType.getElementType());
 }
 
-void AffineLoadOp::build(Builder *builder, OperationState &result, Value memref,
-                         ValueRange indices) {
+void AffineLoadOp::build(OpBuilder &builder, OperationState &result,
+                         Value memref, ValueRange indices) {
   auto memrefType = memref.getType().cast<MemRefType>();
   auto rank = memrefType.getRank();
   // Create identity map for memrefs with at least one dimension or () -> ()
   // for zero-dimensional memrefs.
-  auto map = rank ? builder->getMultiDimIdentityMap(rank)
-                  : builder->getEmptyAffineMap();
+  auto map =
+      rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
   build(builder, result, memref, map, indices);
 }
 
@@ -1948,7 +1948,7 @@ OpFoldResult AffineLoadOp::fold(ArrayRef<Attribute> cstOperands) {
 // AffineStoreOp
 //===----------------------------------------------------------------------===//
 
-void AffineStoreOp::build(Builder *builder, OperationState &result,
+void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
                           Value valueToStore, Value memref, AffineMap map,
                           ValueRange mapOperands) {
   assert(map.getNumInputs() == mapOperands.size() && "inconsistent index info");
@@ -1959,15 +1959,15 @@ void AffineStoreOp::build(Builder *builder, OperationState &result,
 }
 
 // Use identity map.
-void AffineStoreOp::build(Builder *builder, OperationState &result,
+void AffineStoreOp::build(OpBuilder &builder, OperationState &result,
                           Value valueToStore, Value memref,
                           ValueRange indices) {
   auto memrefType = memref.getType().cast<MemRefType>();
   auto rank = memrefType.getRank();
   // Create identity map for memrefs with at least one dimension or () -> ()
   // for zero-dimensional memrefs.
-  auto map = rank ? builder->getMultiDimIdentityMap(rank)
-                  : builder->getEmptyAffineMap();
+  auto map =
+      rank ? builder.getMultiDimIdentityMap(rank) : builder.getEmptyAffineMap();
   build(builder, result, valueToStore, memref, map, indices);
 }
 
@@ -2268,19 +2268,19 @@ LogicalResult AffinePrefetchOp::fold(ArrayRef<Attribute> cstOperands,
 // AffineParallelOp
 //===----------------------------------------------------------------------===//
 
-void AffineParallelOp::build(Builder *builder, OperationState &result,
+void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
                              ArrayRef<int64_t> ranges) {
   SmallVector<AffineExpr, 8> lbExprs(ranges.size(),
-                                     builder->getAffineConstantExpr(0));
-  auto lbMap = AffineMap::get(0, 0, lbExprs, builder->getContext());
+                                     builder.getAffineConstantExpr(0));
+  auto lbMap = AffineMap::get(0, 0, lbExprs, builder.getContext());
   SmallVector<AffineExpr, 8> ubExprs;
   for (int64_t range : ranges)
-    ubExprs.push_back(builder->getAffineConstantExpr(range));
-  auto ubMap = AffineMap::get(0, 0, ubExprs, builder->getContext());
+    ubExprs.push_back(builder.getAffineConstantExpr(range));
+  auto ubMap = AffineMap::get(0, 0, ubExprs, builder.getContext());
   build(builder, result, lbMap, {}, ubMap, {});
 }
 
-void AffineParallelOp::build(Builder *builder, OperationState &result,
+void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
                              AffineMap lbMap, ValueRange lbArgs,
                              AffineMap ubMap, ValueRange ubArgs) {
   auto numDims = lbMap.getNumResults();
@@ -2292,7 +2292,7 @@ void AffineParallelOp::build(Builder *builder, OperationState &result,
   build(builder, result, lbMap, lbArgs, ubMap, ubArgs, steps);
 }
 
-void AffineParallelOp::build(Builder *builder, OperationState &result,
+void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
                              AffineMap lbMap, ValueRange lbArgs,
                              AffineMap ubMap, ValueRange ubArgs,
                              ArrayRef<int64_t> steps) {
@@ -2303,7 +2303,7 @@ void AffineParallelOp::build(Builder *builder, OperationState &result,
   assert(numDims == steps.size() && "num dims and num steps mismatch");
   result.addAttribute(getLowerBoundsMapAttrName(), AffineMapAttr::get(lbMap));
   result.addAttribute(getUpperBoundsMapAttrName(), AffineMapAttr::get(ubMap));
-  result.addAttribute(getStepsAttrName(), builder->getI64ArrayAttr(steps));
+  result.addAttribute(getStepsAttrName(), builder.getI64ArrayAttr(steps));
   result.addOperands(lbArgs);
   result.addOperands(ubArgs);
   // Create a region and a block for the body.
@@ -2311,9 +2311,9 @@ void AffineParallelOp::build(Builder *builder, OperationState &result,
   auto body = new Block();
   // Add all the block arguments.
   for (unsigned i = 0; i < numDims; ++i)
-    body->addArgument(IndexType::get(builder->getContext()));
+    body->addArgument(IndexType::get(builder.getContext()));
   bodyRegion->push_back(body);
-  ensureTerminator(*bodyRegion, *builder, result.location);
+  ensureTerminator(*bodyRegion, builder, result.location);
 }
 
 unsigned AffineParallelOp::getNumDims() { return steps().size(); }

diff  --git a/mlir/lib/Dialect/GPU/IR/GPUDialect.cpp b/mlir/lib/Dialect/GPU/IR/GPUDialect.cpp
index e751107820bc..92ececb142d9 100644
--- a/mlir/lib/Dialect/GPU/IR/GPUDialect.cpp
+++ b/mlir/lib/Dialect/GPU/IR/GPUDialect.cpp
@@ -200,9 +200,9 @@ static ParseResult parseShuffleOp(OpAsmParser &parser, OperationState &state) {
 // LaunchOp
 //===----------------------------------------------------------------------===//
 
-void LaunchOp::build(Builder *builder, OperationState &result, Value gridSizeX,
-                     Value gridSizeY, Value gridSizeZ, Value blockSizeX,
-                     Value blockSizeY, Value blockSizeZ) {
+void LaunchOp::build(OpBuilder &builder, OperationState &result,
+                     Value gridSizeX, Value gridSizeY, Value gridSizeZ,
+                     Value blockSizeX, Value blockSizeY, Value blockSizeZ) {
   // Add grid and block sizes as op operands, followed by the data operands.
   result.addOperands(
       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
@@ -213,7 +213,7 @@ void LaunchOp::build(Builder *builder, OperationState &result, Value gridSizeX,
   Region *kernelRegion = result.addRegion();
   Block *body = new Block();
   body->addArguments(
-      std::vector<Type>(kNumConfigRegionAttributes, builder->getIndexType()));
+      std::vector<Type>(kNumConfigRegionAttributes, builder.getIndexType()));
   kernelRegion->push_back(body);
 }
 
@@ -388,7 +388,7 @@ static ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
 // LaunchFuncOp
 //===----------------------------------------------------------------------===//
 
-void LaunchFuncOp::build(Builder *builder, OperationState &result,
+void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
                          GPUFuncOp kernelFunc, Value gridSizeX, Value gridSizeY,
                          Value gridSizeZ, Value blockSizeX, Value blockSizeY,
                          Value blockSizeZ, ValueRange kernelOperands) {
@@ -397,13 +397,12 @@ void LaunchFuncOp::build(Builder *builder, OperationState &result,
       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
   result.addOperands(kernelOperands);
   auto kernelModule = kernelFunc.getParentOfType<GPUModuleOp>();
-  auto kernelSymbol = builder->getSymbolRefAttr(
-      kernelModule.getName(),
-      {builder->getSymbolRefAttr(kernelFunc.getName())});
+  auto kernelSymbol = builder.getSymbolRefAttr(
+      kernelModule.getName(), {builder.getSymbolRefAttr(kernelFunc.getName())});
   result.addAttribute(getKernelAttrName(), kernelSymbol);
 }
 
-void LaunchFuncOp::build(Builder *builder, OperationState &result,
+void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
                          KernelDim3 blockSize, ValueRange kernelOperands) {
   build(builder, result, kernelFunc, gridSize.x, gridSize.y, gridSize.z,
@@ -476,15 +475,16 @@ Value GPUFuncOp::addWorkgroupAttribution(ArrayRef<int64_t> shape,
   return attribution;
 }
 
-void GPUFuncOp::build(Builder *builder, OperationState &result, StringRef name,
-                      FunctionType type, ArrayRef<Type> workgroupAttributions,
+void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
+                      StringRef name, FunctionType type,
+                      ArrayRef<Type> workgroupAttributions,
                       ArrayRef<Type> privateAttributions,
                       ArrayRef<NamedAttribute> attrs) {
   result.addAttribute(SymbolTable::getSymbolAttrName(),
-                      builder->getStringAttr(name));
+                      builder.getStringAttr(name));
   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
-                      builder->getI64IntegerAttr(workgroupAttributions.size()));
+                      builder.getI64IntegerAttr(workgroupAttributions.size()));
   result.addAttributes(attrs);
   Region *body = result.addRegion();
   Block *entryBlock = new Block;
@@ -742,11 +742,11 @@ static LogicalResult verify(gpu::ReturnOp returnOp) {
 // GPUModuleOp
 //===----------------------------------------------------------------------===//
 
-void GPUModuleOp::build(Builder *builder, OperationState &result,
+void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
                         StringRef name) {
-  ensureTerminator(*result.addRegion(), *builder, result.location);
-  result.attributes.push_back(builder->getNamedAttr(
-      ::mlir::SymbolTable::getSymbolAttrName(), builder->getStringAttr(name)));
+  ensureTerminator(*result.addRegion(), builder, result.location);
+  result.attributes.push_back(builder.getNamedAttr(
+      ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
 }
 
 static ParseResult parseGPUModuleOp(OpAsmParser &parser,

diff  --git a/mlir/lib/Dialect/GPU/Transforms/KernelOutlining.cpp b/mlir/lib/Dialect/GPU/Transforms/KernelOutlining.cpp
index 0f4c4103b2a7..1d72f9ec2690 100644
--- a/mlir/lib/Dialect/GPU/Transforms/KernelOutlining.cpp
+++ b/mlir/lib/Dialect/GPU/Transforms/KernelOutlining.cpp
@@ -265,10 +265,10 @@ class GpuKernelOutliningPass
     // prevent manual building of Ops with symbols in code using SymbolTables
     // and then this needs to use the OpBuilder.
     auto context = getOperation().getContext();
-    Builder builder(context);
+    OpBuilder builder(context);
     OperationState state(kernelFunc.getLoc(),
                          gpu::GPUModuleOp::getOperationName());
-    gpu::GPUModuleOp::build(&builder, state, kernelFunc.getName());
+    gpu::GPUModuleOp::build(builder, state, kernelFunc.getName());
     auto kernelModule = cast<gpu::GPUModuleOp>(Operation::create(state));
     SymbolTable symbolTable(kernelModule);
     symbolTable.insert(kernelFunc);

diff  --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index 7ce591de3802..6f7b620bcde2 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -612,7 +612,7 @@ static ParseResult parseCallOp(OpAsmParser &parser, OperationState &result) {
 //===----------------------------------------------------------------------===//
 // Expects vector to be of wrapped LLVM vector type and position to be of
 // wrapped LLVM i32 type.
-void LLVM::ExtractElementOp::build(Builder *b, OperationState &result,
+void LLVM::ExtractElementOp::build(OpBuilder &b, OperationState &result,
                                    Value vector, Value position,
                                    ArrayRef<NamedAttribute> attrs) {
   auto wrappedVectorType = vector.getType().cast<LLVM::LLVMType>();
@@ -892,21 +892,21 @@ static LogicalResult verify(AddressOfOp op) {
 /// the name of the attribute in ODS.
 static StringRef getLinkageAttrName() { return "linkage"; }
 
-void GlobalOp::build(Builder *builder, OperationState &result, LLVMType type,
+void GlobalOp::build(OpBuilder &builder, OperationState &result, LLVMType type,
                      bool isConstant, Linkage linkage, StringRef name,
                      Attribute value, unsigned addrSpace,
                      ArrayRef<NamedAttribute> attrs) {
   result.addAttribute(SymbolTable::getSymbolAttrName(),
-                      builder->getStringAttr(name));
+                      builder.getStringAttr(name));
   result.addAttribute("type", TypeAttr::get(type));
   if (isConstant)
-    result.addAttribute("constant", builder->getUnitAttr());
+    result.addAttribute("constant", builder.getUnitAttr());
   if (value)
     result.addAttribute("value", value);
-  result.addAttribute(getLinkageAttrName(), builder->getI64IntegerAttr(
-                                                static_cast<int64_t>(linkage)));
+  result.addAttribute(getLinkageAttrName(),
+                      builder.getI64IntegerAttr(static_cast<int64_t>(linkage)));
   if (addrSpace != 0)
-    result.addAttribute("addr_space", builder->getI32IntegerAttr(addrSpace));
+    result.addAttribute("addr_space", builder.getI32IntegerAttr(addrSpace));
   result.attributes.append(attrs.begin(), attrs.end());
   result.addRegion();
 }
@@ -1106,8 +1106,8 @@ static LogicalResult verify(GlobalOp op) {
 //===----------------------------------------------------------------------===//
 // Expects vector to be of wrapped LLVM vector type and position to be of
 // wrapped LLVM i32 type.
-void LLVM::ShuffleVectorOp::build(Builder *b, OperationState &result, Value v1,
-                                  Value v2, ArrayAttr mask,
+void LLVM::ShuffleVectorOp::build(OpBuilder &b, OperationState &result,
+                                  Value v1, Value v2, ArrayAttr mask,
                                   ArrayRef<NamedAttribute> attrs) {
   auto wrappedContainerType1 = v1.getType().cast<LLVM::LLVMType>();
   auto vType = LLVMType::getVectorTy(
@@ -1170,16 +1170,16 @@ Block *LLVMFuncOp::addEntryBlock() {
   return entry;
 }
 
-void LLVMFuncOp::build(Builder *builder, OperationState &result, StringRef name,
-                       LLVMType type, LLVM::Linkage linkage,
+void LLVMFuncOp::build(OpBuilder &builder, OperationState &result,
+                       StringRef name, LLVMType type, LLVM::Linkage linkage,
                        ArrayRef<NamedAttribute> attrs,
                        ArrayRef<NamedAttributeList> argAttrs) {
   result.addRegion();
   result.addAttribute(SymbolTable::getSymbolAttrName(),
-                      builder->getStringAttr(name));
+                      builder.getStringAttr(name));
   result.addAttribute("type", TypeAttr::get(type));
-  result.addAttribute(getLinkageAttrName(), builder->getI64IntegerAttr(
-                                                static_cast<int64_t>(linkage)));
+  result.addAttribute(getLinkageAttrName(),
+                      builder.getI64IntegerAttr(static_cast<int64_t>(linkage)));
   result.attributes.append(attrs.begin(), attrs.end());
   if (argAttrs.empty())
     return;

diff  --git a/mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp b/mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
index 9fef7a92d6b8..974bff525f96 100644
--- a/mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
+++ b/mlir/lib/Dialect/Linalg/IR/LinalgOps.cpp
@@ -470,7 +470,7 @@ getSymbolLessAffineMaps(ArrayRef<ArrayRef<AffineExpr>> reassociation) {
 }
 
 void mlir::linalg::ReshapeOp::build(
-    Builder *b, OperationState &result, Value src,
+    OpBuilder &b, OperationState &result, Value src,
     ArrayRef<ArrayRef<AffineExpr>> reassociation,
     ArrayRef<NamedAttribute> attrs) {
   auto maps = getSymbolLessAffineMaps(reassociation);
@@ -478,17 +478,17 @@ void mlir::linalg::ReshapeOp::build(
   auto resultType = computeReshapeCollapsedType(memRefType, maps);
   build(b, result, resultType, src, attrs);
   result.addAttribute(ReshapeOp::getReassociationAttrName(),
-                      b->getAffineMapArrayAttr(maps));
+                      b.getAffineMapArrayAttr(maps));
 }
 
 void mlir::linalg::ReshapeOp::build(
-    Builder *b, OperationState &result, Type resultType, Value src,
+    OpBuilder &b, OperationState &result, Type resultType, Value src,
     ArrayRef<ArrayRef<AffineExpr>> reassociation,
     ArrayRef<NamedAttribute> attrs) {
   auto maps = getSymbolLessAffineMaps(reassociation);
   build(b, result, resultType, src, attrs);
   result.addAttribute(ReshapeOp::getReassociationAttrName(),
-                      b->getAffineMapArrayAttr(maps));
+                      b.getAffineMapArrayAttr(maps));
 }
 
 // Common verifier for reshape-like types. Fills `expandedType` and
@@ -572,7 +572,7 @@ computeTensorReshapeCollapsedType(RankedTensorType type,
 }
 
 void mlir::linalg::TensorReshapeOp::build(
-    Builder *b, OperationState &result, Value src,
+    OpBuilder &b, OperationState &result, Value src,
     ArrayRef<ArrayRef<AffineExpr>> reassociation,
     ArrayRef<NamedAttribute> attrs) {
   auto maps = getSymbolLessAffineMaps(reassociation);
@@ -580,17 +580,17 @@ void mlir::linalg::TensorReshapeOp::build(
       src.getType().cast<RankedTensorType>(), maps);
   build(b, result, resultType, src, attrs);
   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
-                      b->getAffineMapArrayAttr(maps));
+                      b.getAffineMapArrayAttr(maps));
 }
 
 void mlir::linalg::TensorReshapeOp::build(
-    Builder *b, OperationState &result, Type resultType, Value src,
+    OpBuilder &b, OperationState &result, Type resultType, Value src,
     ArrayRef<ArrayRef<AffineExpr>> reassociation,
     ArrayRef<NamedAttribute> attrs) {
   auto maps = getSymbolLessAffineMaps(reassociation);
   build(b, result, resultType, src, attrs);
   result.addAttribute(TensorReshapeOp::getReassociationAttrName(),
-                      b->getAffineMapArrayAttr(maps));
+                      b.getAffineMapArrayAttr(maps));
 }
 
 static LogicalResult verify(TensorReshapeOp op) {
@@ -611,7 +611,7 @@ static LogicalResult verify(TensorReshapeOp op) {
 //===----------------------------------------------------------------------===//
 // SliceOp
 //===----------------------------------------------------------------------===//
-void mlir::linalg::SliceOp::build(Builder *b, OperationState &result,
+void mlir::linalg::SliceOp::build(OpBuilder &b, OperationState &result,
                                   Value base, ValueRange indexings) {
   result.addOperands(base);
   result.addOperands(indexings);
@@ -629,7 +629,7 @@ void mlir::linalg::SliceOp::build(Builder *b, OperationState &result,
   result.addTypes({MemRefType::Builder(memRefType)
                        .setShape(sizes)
                        .setAffineMaps(makeStridedLinearLayoutMap(
-                           strides, offset, b->getContext()))});
+                           strides, offset, b.getContext()))});
 }
 
 static void print(OpAsmPrinter &p, SliceOp op) {
@@ -688,7 +688,7 @@ Value SliceOp::getViewSource() { return view(); }
 //===----------------------------------------------------------------------===//
 // TransposeOp
 //===----------------------------------------------------------------------===//
-void mlir::linalg::TransposeOp::build(Builder *b, OperationState &result,
+void mlir::linalg::TransposeOp::build(OpBuilder &b, OperationState &result,
                                       Value view, AffineMapAttr permutation,
                                       ArrayRef<NamedAttribute> attrs) {
   auto permutationMap = permutation.getValue();
@@ -709,7 +709,7 @@ void mlir::linalg::TransposeOp::build(Builder *b, OperationState &result,
   auto res = getStridesAndOffset(memRefType, strides, offset);
   assert(succeeded(res) && strides.size() == static_cast<unsigned>(rank));
   (void)res;
-  auto map = makeStridedLinearLayoutMap(strides, offset, b->getContext());
+  auto map = makeStridedLinearLayoutMap(strides, offset, b.getContext());
   map = permutationMap ? map.compose(permutationMap) : map;
   // Compute result type.
   MemRefType resultType =

diff  --git a/mlir/lib/Dialect/LoopOps/LoopOps.cpp b/mlir/lib/Dialect/LoopOps/LoopOps.cpp
index 80f8120a81b6..fb3945d33c9c 100644
--- a/mlir/lib/Dialect/LoopOps/LoopOps.cpp
+++ b/mlir/lib/Dialect/LoopOps/LoopOps.cpp
@@ -39,8 +39,8 @@ LoopOpsDialect::LoopOpsDialect(MLIRContext *context)
 // ForOp
 //===----------------------------------------------------------------------===//
 
-void ForOp::build(Builder *builder, OperationState &result, Value lb, Value ub,
-                  Value step, ValueRange iterArgs) {
+void ForOp::build(OpBuilder &builder, OperationState &result, Value lb,
+                  Value ub, Value step, ValueRange iterArgs) {
   result.addOperands({lb, ub, step});
   result.addOperands(iterArgs);
   for (Value v : iterArgs)
@@ -48,8 +48,8 @@ void ForOp::build(Builder *builder, OperationState &result, Value lb, Value ub,
   Region *bodyRegion = result.addRegion();
   bodyRegion->push_back(new Block());
   if (iterArgs.empty())
-    ForOp::ensureTerminator(*bodyRegion, *builder, result.location);
-  bodyRegion->front().addArgument(builder->getIndexType());
+    ForOp::ensureTerminator(*bodyRegion, builder, result.location);
+  bodyRegion->front().addArgument(builder.getIndexType());
   for (Value v : iterArgs)
     bodyRegion->front().addArgument(v.getType());
 }
@@ -233,12 +233,12 @@ void ForOp::getSuccessorRegions(Optional<unsigned> index,
 // IfOp
 //===----------------------------------------------------------------------===//
 
-void IfOp::build(Builder *builder, OperationState &result, Value cond,
+void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
                  bool withElseRegion) {
   build(builder, result, /*resultTypes=*/llvm::None, cond, withElseRegion);
 }
 
-void IfOp::build(Builder *builder, OperationState &result,
+void IfOp::build(OpBuilder &builder, OperationState &result,
                  TypeRange resultTypes, Value cond, bool withElseRegion) {
   result.addOperands(cond);
   result.addTypes(resultTypes);
@@ -246,13 +246,13 @@ void IfOp::build(Builder *builder, OperationState &result,
   Region *thenRegion = result.addRegion();
   thenRegion->push_back(new Block());
   if (resultTypes.empty())
-    IfOp::ensureTerminator(*thenRegion, *builder, result.location);
+    IfOp::ensureTerminator(*thenRegion, builder, result.location);
 
   Region *elseRegion = result.addRegion();
   if (withElseRegion) {
     elseRegion->push_back(new Block());
     if (resultTypes.empty())
-      IfOp::ensureTerminator(*elseRegion, *builder, result.location);
+      IfOp::ensureTerminator(*elseRegion, builder, result.location);
   }
 }
 
@@ -371,22 +371,23 @@ void IfOp::getSuccessorRegions(Optional<unsigned> index,
 // ParallelOp
 //===----------------------------------------------------------------------===//
 
-void ParallelOp::build(Builder *builder, OperationState &result, ValueRange lbs,
-                       ValueRange ubs, ValueRange steps, ValueRange initVals) {
+void ParallelOp::build(OpBuilder &builder, OperationState &result,
+                       ValueRange lbs, ValueRange ubs, ValueRange steps,
+                       ValueRange initVals) {
   result.addOperands(lbs);
   result.addOperands(ubs);
   result.addOperands(steps);
   result.addOperands(initVals);
   result.addAttribute(
       ParallelOp::getOperandSegmentSizeAttr(),
-      builder->getI32VectorAttr({static_cast<int32_t>(lbs.size()),
-                                 static_cast<int32_t>(ubs.size()),
-                                 static_cast<int32_t>(steps.size()),
-                                 static_cast<int32_t>(initVals.size())}));
+      builder.getI32VectorAttr({static_cast<int32_t>(lbs.size()),
+                                static_cast<int32_t>(ubs.size()),
+                                static_cast<int32_t>(steps.size()),
+                                static_cast<int32_t>(initVals.size())}));
   Region *bodyRegion = result.addRegion();
-  ParallelOp::ensureTerminator(*bodyRegion, *builder, result.location);
+  ParallelOp::ensureTerminator(*bodyRegion, builder, result.location);
   for (size_t i = 0, e = steps.size(); i < e; ++i)
-    bodyRegion->front().addArgument(builder->getIndexType());
+    bodyRegion->front().addArgument(builder.getIndexType());
   for (Value init : initVals)
     result.addTypes(init.getType());
 }
@@ -554,7 +555,8 @@ ParallelOp mlir::loop::getParallelForInductionVarOwner(Value val) {
 // ReduceOp
 //===----------------------------------------------------------------------===//
 
-void ReduceOp::build(Builder *builder, OperationState &result, Value operand) {
+void ReduceOp::build(OpBuilder &builder, OperationState &result,
+                     Value operand) {
   auto type = operand.getType();
   result.addOperands(operand);
   Region *bodyRegion = result.addRegion();

diff  --git a/mlir/lib/Dialect/SPIRV/SPIRVLowering.cpp b/mlir/lib/Dialect/SPIRV/SPIRVLowering.cpp
index c6e15d5db485..c9f2983e232b 100644
--- a/mlir/lib/Dialect/SPIRV/SPIRVLowering.cpp
+++ b/mlir/lib/Dialect/SPIRV/SPIRVLowering.cpp
@@ -596,7 +596,7 @@ spirv::AccessChainOp mlir::spirv::getElementPtr(
   }
   SmallVector<Value, 2> linearizedIndices;
   // Add a '0' at the start to index into the struct.
-  auto zero = spirv::ConstantOp::getZero(indexType, loc, &builder);
+  auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
   linearizedIndices.push_back(zero);
   // If it is a zero-rank memref type, extract the element directly.
   if (!ptrLoc) {

diff  --git a/mlir/lib/Dialect/SPIRV/SPIRVOps.cpp b/mlir/lib/Dialect/SPIRV/SPIRVOps.cpp
index 6deae62c6987..ed98d3745d6f 100644
--- a/mlir/lib/Dialect/SPIRV/SPIRVOps.cpp
+++ b/mlir/lib/Dialect/SPIRV/SPIRVOps.cpp
@@ -788,7 +788,7 @@ static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc) {
   return spirv::PointerType::get(resultType, resultStorageClass);
 }
 
-void spirv::AccessChainOp::build(Builder *builder, OperationState &state,
+void spirv::AccessChainOp::build(OpBuilder &builder, OperationState &state,
                                  Value basePtr, ValueRange indices) {
   auto type = getElementPtrType(basePtr.getType(), indices, state.location);
   assert(type && "Unable to deduce return type based on basePtr and indices");
@@ -857,9 +857,9 @@ static LogicalResult verify(spirv::AccessChainOp accessChainOp) {
 // spv._address_of
 //===----------------------------------------------------------------------===//
 
-void spirv::AddressOfOp::build(Builder *builder, OperationState &state,
+void spirv::AddressOfOp::build(OpBuilder &builder, OperationState &state,
                                spirv::GlobalVariableOp var) {
-  build(builder, state, var.type(), builder->getSymbolRefAttr(var));
+  build(builder, state, var.type(), builder.getSymbolRefAttr(var));
 }
 
 static LogicalResult verify(spirv::AddressOfOp addressOfOp) {
@@ -1163,10 +1163,10 @@ static LogicalResult verify(spirv::CompositeConstructOp compositeConstructOp) {
 // spv.CompositeExtractOp
 //===----------------------------------------------------------------------===//
 
-void spirv::CompositeExtractOp::build(Builder *builder, OperationState &state,
+void spirv::CompositeExtractOp::build(OpBuilder &builder, OperationState &state,
                                       Value composite,
                                       ArrayRef<int32_t> indices) {
-  auto indexAttr = builder->getI32ArrayAttr(indices);
+  auto indexAttr = builder.getI32ArrayAttr(indices);
   auto elementType =
       getElementType(composite.getType(), indexAttr, state.location);
   if (!elementType) {
@@ -1386,28 +1386,28 @@ bool spirv::ConstantOp::isBuildableWith(Type type) {
 }
 
 spirv::ConstantOp spirv::ConstantOp::getZero(Type type, Location loc,
-                                             OpBuilder *builder) {
+                                             OpBuilder &builder) {
   if (auto intType = type.dyn_cast<IntegerType>()) {
     unsigned width = intType.getWidth();
     if (width == 1)
-      return builder->create<spirv::ConstantOp>(loc, type,
-                                                builder->getBoolAttr(false));
-    return builder->create<spirv::ConstantOp>(
-        loc, type, builder->getIntegerAttr(type, APInt(width, 0)));
+      return builder.create<spirv::ConstantOp>(loc, type,
+                                               builder.getBoolAttr(false));
+    return builder.create<spirv::ConstantOp>(
+        loc, type, builder.getIntegerAttr(type, APInt(width, 0)));
   }
 
   llvm_unreachable("unimplemented types for ConstantOp::getZero()");
 }
 
 spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc,
-                                            OpBuilder *builder) {
+                                            OpBuilder &builder) {
   if (auto intType = type.dyn_cast<IntegerType>()) {
     unsigned width = intType.getWidth();
     if (width == 1)
-      return builder->create<spirv::ConstantOp>(loc, type,
-                                                builder->getBoolAttr(true));
-    return builder->create<spirv::ConstantOp>(
-        loc, type, builder->getIntegerAttr(type, APInt(width, 1)));
+      return builder.create<spirv::ConstantOp>(loc, type,
+                                               builder.getBoolAttr(true));
+    return builder.create<spirv::ConstantOp>(
+        loc, type, builder.getIntegerAttr(type, APInt(width, 1)));
   }
 
   llvm_unreachable("unimplemented types for ConstantOp::getOne()");
@@ -1417,14 +1417,14 @@ spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc,
 // spv.EntryPoint
 //===----------------------------------------------------------------------===//
 
-void spirv::EntryPointOp::build(Builder *builder, OperationState &state,
+void spirv::EntryPointOp::build(OpBuilder &builder, OperationState &state,
                                 spirv::ExecutionModel executionModel,
                                 spirv::FuncOp function,
                                 ArrayRef<Attribute> interfaceVars) {
   build(builder, state,
-        builder->getI32IntegerAttr(static_cast<int32_t>(executionModel)),
-        builder->getSymbolRefAttr(function),
-        builder->getArrayAttr(interfaceVars));
+        builder.getI32IntegerAttr(static_cast<int32_t>(executionModel)),
+        builder.getSymbolRefAttr(function),
+        builder.getArrayAttr(interfaceVars));
 }
 
 static ParseResult parseEntryPointOp(OpAsmParser &parser,
@@ -1479,13 +1479,13 @@ static LogicalResult verify(spirv::EntryPointOp entryPointOp) {
 // spv.ExecutionMode
 //===----------------------------------------------------------------------===//
 
-void spirv::ExecutionModeOp::build(Builder *builder, OperationState &state,
+void spirv::ExecutionModeOp::build(OpBuilder &builder, OperationState &state,
                                    spirv::FuncOp function,
                                    spirv::ExecutionMode executionMode,
                                    ArrayRef<int32_t> params) {
-  build(builder, state, builder->getSymbolRefAttr(function),
-        builder->getI32IntegerAttr(static_cast<int32_t>(executionMode)),
-        builder->getI32ArrayAttr(params));
+  build(builder, state, builder.getSymbolRefAttr(function),
+        builder.getI32IntegerAttr(static_cast<int32_t>(executionMode)),
+        builder.getI32ArrayAttr(params));
 }
 
 static ParseResult parseExecutionModeOp(OpAsmParser &parser,
@@ -1632,16 +1632,15 @@ LogicalResult spirv::FuncOp::verifyBody() {
   return failure(walkResult.wasInterrupted());
 }
 
-void spirv::FuncOp::build(Builder *builder, OperationState &state,
+void spirv::FuncOp::build(OpBuilder &builder, OperationState &state,
                           StringRef name, FunctionType type,
                           spirv::FunctionControl control,
                           ArrayRef<NamedAttribute> attrs) {
   state.addAttribute(SymbolTable::getSymbolAttrName(),
-                     builder->getStringAttr(name));
+                     builder.getStringAttr(name));
   state.addAttribute(getTypeAttrName(), TypeAttr::get(type));
-  state.addAttribute(
-      spirv::attributeName<spirv::FunctionControl>(),
-      builder->getI32IntegerAttr(static_cast<uint32_t>(control)));
+  state.addAttribute(spirv::attributeName<spirv::FunctionControl>(),
+                     builder.getI32IntegerAttr(static_cast<uint32_t>(control)));
   state.attributes.append(attrs.begin(), attrs.end());
   state.addRegion();
 }
@@ -1725,27 +1724,27 @@ Operation::operand_range spirv::FunctionCallOp::getArgOperands() {
 // spv.globalVariable
 //===----------------------------------------------------------------------===//
 
-void spirv::GlobalVariableOp::build(Builder *builder, OperationState &state,
+void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
                                     Type type, StringRef name,
                                     unsigned descriptorSet, unsigned binding) {
-  build(builder, state, TypeAttr::get(type), builder->getStringAttr(name),
+  build(builder, state, TypeAttr::get(type), builder.getStringAttr(name),
         nullptr);
   state.addAttribute(
       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet),
-      builder->getI32IntegerAttr(descriptorSet));
+      builder.getI32IntegerAttr(descriptorSet));
   state.addAttribute(
       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding),
-      builder->getI32IntegerAttr(binding));
+      builder.getI32IntegerAttr(binding));
 }
 
-void spirv::GlobalVariableOp::build(Builder *builder, OperationState &state,
+void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
                                     Type type, StringRef name,
                                     spirv::BuiltIn builtin) {
-  build(builder, state, TypeAttr::get(type), builder->getStringAttr(name),
+  build(builder, state, TypeAttr::get(type), builder.getStringAttr(name),
         nullptr);
   state.addAttribute(
       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn),
-      builder->getStringAttr(spirv::stringifyBuiltIn(builtin)));
+      builder.getStringAttr(spirv::stringifyBuiltIn(builtin)));
 }
 
 static ParseResult parseGlobalVariableOp(OpAsmParser &parser,
@@ -1849,10 +1848,10 @@ static LogicalResult verify(spirv::GroupNonUniformBallotOp ballotOp) {
 // spv.GroupNonUniformElectOp
 //===----------------------------------------------------------------------===//
 
-void spirv::GroupNonUniformElectOp::build(Builder *builder,
+void spirv::GroupNonUniformElectOp::build(OpBuilder &builder,
                                           OperationState &state,
                                           spirv::Scope scope) {
-  build(builder, state, builder->getI1Type(), scope);
+  build(builder, state, builder.getI1Type(), scope);
 }
 
 static LogicalResult verify(spirv::GroupNonUniformElectOp groupOp) {
@@ -1868,7 +1867,7 @@ static LogicalResult verify(spirv::GroupNonUniformElectOp groupOp) {
 // spv.LoadOp
 //===----------------------------------------------------------------------===//
 
-void spirv::LoadOp::build(Builder *builder, OperationState &state,
+void spirv::LoadOp::build(OpBuilder &builder, OperationState &state,
                           Value basePtr, IntegerAttr memory_access,
                           IntegerAttr alignment) {
   auto ptrType = basePtr.getType().cast<spirv::PointerType>();
@@ -1926,9 +1925,9 @@ static LogicalResult verify(spirv::LoadOp loadOp) {
 // spv.loop
 //===----------------------------------------------------------------------===//
 
-void spirv::LoopOp::build(Builder *builder, OperationState &state) {
+void spirv::LoopOp::build(OpBuilder &builder, OperationState &state) {
   state.addAttribute("loop_control",
-                     builder->getI32IntegerAttr(
+                     builder.getI32IntegerAttr(
                          static_cast<uint32_t>(spirv::LoopControl::None)));
   state.addRegion();
 }
@@ -2104,19 +2103,19 @@ static LogicalResult verify(spirv::MergeOp mergeOp) {
 // spv.module
 //===----------------------------------------------------------------------===//
 
-void spirv::ModuleOp::build(Builder *builder, OperationState &state) {
-  ensureTerminator(*state.addRegion(), *builder, state.location);
+void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state) {
+  ensureTerminator(*state.addRegion(), builder, state.location);
 }
 
-void spirv::ModuleOp::build(Builder *builder, OperationState &state,
+void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
                             spirv::AddressingModel addressing_model,
                             spirv::MemoryModel memory_model) {
   state.addAttribute(
       "addressing_model",
-      builder->getI32IntegerAttr(static_cast<int32_t>(addressing_model)));
-  state.addAttribute("memory_model", builder->getI32IntegerAttr(
+      builder.getI32IntegerAttr(static_cast<int32_t>(addressing_model)));
+  state.addAttribute("memory_model", builder.getI32IntegerAttr(
                                          static_cast<int32_t>(memory_model)));
-  ensureTerminator(*state.addRegion(), *builder, state.location);
+  ensureTerminator(*state.addRegion(), builder, state.location);
 }
 
 static ParseResult parseModuleOp(OpAsmParser &parser, OperationState &state) {
@@ -2272,8 +2271,8 @@ static LogicalResult verify(spirv::ReturnValueOp retValOp) {
 // spv.Select
 //===----------------------------------------------------------------------===//
 
-void spirv::SelectOp::build(Builder *builder, OperationState &state, Value cond,
-                            Value trueValue, Value falseValue) {
+void spirv::SelectOp::build(OpBuilder &builder, OperationState &state,
+                            Value cond, Value trueValue, Value falseValue) {
   build(builder, state, trueValue.getType(), cond, trueValue, falseValue);
 }
 
@@ -2381,10 +2380,10 @@ void spirv::SelectionOp::addMergeBlock() {
 
 spirv::SelectionOp spirv::SelectionOp::createIfThen(
     Location loc, Value condition,
-    function_ref<void(OpBuilder *builder)> thenBody, OpBuilder *builder) {
-  auto selectionControl = builder->getI32IntegerAttr(
+    function_ref<void(OpBuilder &builder)> thenBody, OpBuilder &builder) {
+  auto selectionControl = builder.getI32IntegerAttr(
       static_cast<uint32_t>(spirv::SelectionControl::None));
-  auto selectionOp = builder->create<spirv::SelectionOp>(loc, selectionControl);
+  auto selectionOp = builder.create<spirv::SelectionOp>(loc, selectionControl);
 
   selectionOp.addMergeBlock();
   Block *mergeBlock = selectionOp.getMergeBlock();
@@ -2392,17 +2391,17 @@ spirv::SelectionOp spirv::SelectionOp::createIfThen(
 
   // Build the "then" block.
   {
-    OpBuilder::InsertionGuard guard(*builder);
-    thenBlock = builder->createBlock(mergeBlock);
+    OpBuilder::InsertionGuard guard(builder);
+    thenBlock = builder.createBlock(mergeBlock);
     thenBody(builder);
-    builder->create<spirv::BranchOp>(loc, mergeBlock);
+    builder.create<spirv::BranchOp>(loc, mergeBlock);
   }
 
   // Build the header block.
   {
-    OpBuilder::InsertionGuard guard(*builder);
-    builder->createBlock(thenBlock);
-    builder->create<spirv::BranchConditionalOp>(
+    OpBuilder::InsertionGuard guard(builder);
+    builder.createBlock(thenBlock);
+    builder.create<spirv::BranchConditionalOp>(
         loc, condition, thenBlock,
         /*trueArguments=*/ArrayRef<Value>(), mergeBlock,
         /*falseArguments=*/ArrayRef<Value>());

diff  --git a/mlir/lib/Dialect/SPIRV/Serialization/Deserializer.cpp b/mlir/lib/Dialect/SPIRV/Serialization/Deserializer.cpp
index 9ea6ac02be0a..fc8d980b3ed5 100644
--- a/mlir/lib/Dialect/SPIRV/Serialization/Deserializer.cpp
+++ b/mlir/lib/Dialect/SPIRV/Serialization/Deserializer.cpp
@@ -521,9 +521,9 @@ Optional<spirv::ModuleOp> Deserializer::collect() { return module; }
 //===----------------------------------------------------------------------===//
 
 spirv::ModuleOp Deserializer::createModuleOp() {
-  Builder builder(context);
+  OpBuilder builder(context);
   OperationState state(unknownLoc, spirv::ModuleOp::getOperationName());
-  spirv::ModuleOp::build(&builder, state);
+  spirv::ModuleOp::build(builder, state);
   return cast<spirv::ModuleOp>(Operation::create(state));
 }
 

diff  --git a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
index daee70976ac2..139b6bc093d0 100644
--- a/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
+++ b/mlir/lib/Dialect/SPIRV/Transforms/LowerABIAttributesPass.cpp
@@ -194,7 +194,7 @@ LogicalResult ProcessInterfaceVarABI::matchAndRewrite(
     if (argType.value().cast<spirv::SPIRVType>().isScalarOrVector()) {
       auto indexType = SPIRVTypeConverter::getIndexType(funcOp.getContext());
       auto zero =
-          spirv::ConstantOp::getZero(indexType, funcOp.getLoc(), &rewriter);
+          spirv::ConstantOp::getZero(indexType, funcOp.getLoc(), rewriter);
       auto loadPtr = rewriter.create<spirv::AccessChainOp>(
           funcOp.getLoc(), replacement, zero.constant());
       replacement = rewriter.create<spirv::LoadOp>(funcOp.getLoc(), loadPtr);

diff  --git a/mlir/lib/Dialect/StandardOps/IR/Ops.cpp b/mlir/lib/Dialect/StandardOps/IR/Ops.cpp
index 0de8f42ab4c2..85efc4391234 100644
--- a/mlir/lib/Dialect/StandardOps/IR/Ops.cpp
+++ b/mlir/lib/Dialect/StandardOps/IR/Ops.cpp
@@ -484,7 +484,7 @@ static LogicalResult verify(AtomicRMWOp op) {
 // GenericAtomicRMWOp
 //===----------------------------------------------------------------------===//
 
-void GenericAtomicRMWOp::build(Builder *builder, OperationState &result,
+void GenericAtomicRMWOp::build(OpBuilder &builder, OperationState &result,
                                Value memref, ValueRange ivs) {
   result.addOperands(memref);
   result.addOperands(ivs);
@@ -775,13 +775,12 @@ static Type getI1SameShape(Type type) {
 // CmpIOp
 //===----------------------------------------------------------------------===//
 
-static void buildCmpIOp(Builder *build, OperationState &result,
+static void buildCmpIOp(OpBuilder &build, OperationState &result,
                         CmpIPredicate predicate, Value lhs, Value rhs) {
   result.addOperands({lhs, rhs});
   result.types.push_back(getI1SameShape(lhs.getType()));
-  result.addAttribute(
-      CmpIOp::getPredicateAttrName(),
-      build->getI64IntegerAttr(static_cast<int64_t>(predicate)));
+  result.addAttribute(CmpIOp::getPredicateAttrName(),
+                      build.getI64IntegerAttr(static_cast<int64_t>(predicate)));
 }
 
 // Compute `lhs` `pred` `rhs`, where `pred` is one of the known integer
@@ -830,13 +829,12 @@ OpFoldResult CmpIOp::fold(ArrayRef<Attribute> operands) {
 // CmpFOp
 //===----------------------------------------------------------------------===//
 
-static void buildCmpFOp(Builder *build, OperationState &result,
+static void buildCmpFOp(OpBuilder &build, OperationState &result,
                         CmpFPredicate predicate, Value lhs, Value rhs) {
   result.addOperands({lhs, rhs});
   result.types.push_back(getI1SameShape(lhs.getType()));
-  result.addAttribute(
-      CmpFOp::getPredicateAttrName(),
-      build->getI64IntegerAttr(static_cast<int64_t>(predicate)));
+  result.addAttribute(CmpFOp::getPredicateAttrName(),
+                      build.getI64IntegerAttr(static_cast<int64_t>(predicate)));
 }
 
 /// Compute `lhs` `pred` `rhs`, where `pred` is one of the known floating point
@@ -1180,9 +1178,9 @@ bool ConstantOp::isBuildableWith(Attribute value, Type type) {
          value.isa<UnitAttr>();
 }
 
-void ConstantFloatOp::build(Builder *builder, OperationState &result,
+void ConstantFloatOp::build(OpBuilder &builder, OperationState &result,
                             const APFloat &value, FloatType type) {
-  ConstantOp::build(builder, result, type, builder->getFloatAttr(type, value));
+  ConstantOp::build(builder, result, type, builder.getFloatAttr(type, value));
 }
 
 bool ConstantFloatOp::classof(Operation *op) {
@@ -1195,21 +1193,19 @@ bool ConstantIntOp::classof(Operation *op) {
          op->getResult(0).getType().isSignlessInteger();
 }
 
-void ConstantIntOp::build(Builder *builder, OperationState &result,
+void ConstantIntOp::build(OpBuilder &builder, OperationState &result,
                           int64_t value, unsigned width) {
-  Type type = builder->getIntegerType(width);
-  ConstantOp::build(builder, result, type,
-                    builder->getIntegerAttr(type, value));
+  Type type = builder.getIntegerType(width);
+  ConstantOp::build(builder, result, type, builder.getIntegerAttr(type, value));
 }
 
 /// Build a constant int op producing an integer with the specified type,
 /// which must be an integer type.
-void ConstantIntOp::build(Builder *builder, OperationState &result,
+void ConstantIntOp::build(OpBuilder &builder, OperationState &result,
                           int64_t value, Type type) {
   assert(type.isSignlessInteger() &&
          "ConstantIntOp can only have signless integer type");
-  ConstantOp::build(builder, result, type,
-                    builder->getIntegerAttr(type, value));
+  ConstantOp::build(builder, result, type, builder.getIntegerAttr(type, value));
 }
 
 /// ConstantIndexOp only matches values whose result type is Index.
@@ -1217,11 +1213,10 @@ bool ConstantIndexOp::classof(Operation *op) {
   return ConstantOp::classof(op) && op->getResult(0).getType().isIndex();
 }
 
-void ConstantIndexOp::build(Builder *builder, OperationState &result,
+void ConstantIndexOp::build(OpBuilder &builder, OperationState &result,
                             int64_t value) {
-  Type type = builder->getIndexType();
-  ConstantOp::build(builder, result, type,
-                    builder->getIntegerAttr(type, value));
+  Type type = builder.getIndexType();
+  ConstantOp::build(builder, result, type, builder.getIntegerAttr(type, value));
 }
 
 //===----------------------------------------------------------------------===//
@@ -1363,7 +1358,7 @@ OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) {
 // DmaStartOp
 // ---------------------------------------------------------------------------
 
-void DmaStartOp::build(Builder *builder, OperationState &result,
+void DmaStartOp::build(OpBuilder &builder, OperationState &result,
                        Value srcMemRef, ValueRange srcIndices, Value destMemRef,
                        ValueRange destIndices, Value numElements,
                        Value tagMemRef, ValueRange tagIndices, Value stride,
@@ -1506,8 +1501,9 @@ LogicalResult DmaStartOp::fold(ArrayRef<Attribute> cstOperands,
 // DmaWaitOp
 // ---------------------------------------------------------------------------
 
-void DmaWaitOp::build(Builder *builder, OperationState &result, Value tagMemRef,
-                      ValueRange tagIndices, Value numElements) {
+void DmaWaitOp::build(OpBuilder &builder, OperationState &result,
+                      Value tagMemRef, ValueRange tagIndices,
+                      Value numElements) {
   result.addOperands(tagMemRef);
   result.addOperands(tagIndices);
   result.addOperands(numElements);
@@ -2157,7 +2153,7 @@ static Type inferSubViewResultType(MemRefType memRefType) {
       .setAffineMaps(stridedLayout);
 }
 
-void mlir::SubViewOp::build(Builder *b, OperationState &result, Value source,
+void mlir::SubViewOp::build(OpBuilder &b, OperationState &result, Value source,
                             ValueRange offsets, ValueRange sizes,
                             ValueRange strides, Type resultType,
                             ArrayRef<NamedAttribute> attrs) {
@@ -2167,8 +2163,8 @@ void mlir::SubViewOp::build(Builder *b, OperationState &result, Value source,
   result.addAttributes(attrs);
 }
 
-void mlir::SubViewOp::build(Builder *b, OperationState &result, Type resultType,
-                            Value source) {
+void mlir::SubViewOp::build(OpBuilder &b, OperationState &result,
+                            Type resultType, Value source) {
   build(b, result, source, /*offsets=*/{}, /*sizes=*/{}, /*strides=*/{},
         resultType);
 }

diff  --git a/mlir/lib/Dialect/Vector/VectorOps.cpp b/mlir/lib/Dialect/Vector/VectorOps.cpp
index 40b7f6a69188..5930ff10f921 100644
--- a/mlir/lib/Dialect/Vector/VectorOps.cpp
+++ b/mlir/lib/Dialect/Vector/VectorOps.cpp
@@ -126,20 +126,20 @@ static void print(OpAsmPrinter &p, ReductionOp op) {
 // ContractionOp
 //===----------------------------------------------------------------------===//
 
-void vector::ContractionOp::build(Builder *builder, OperationState &result,
+void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
                                   Value lhs, Value rhs, Value acc,
                                   ArrayRef<ArrayRef<AffineExpr>> indexingExprs,
                                   ArrayRef<StringRef> iteratorTypes) {
   result.addOperands({lhs, rhs, acc});
   result.addTypes(acc.getType());
   result.addAttribute(getIndexingMapsAttrName(),
-                      builder->getAffineMapArrayAttr(
+                      builder.getAffineMapArrayAttr(
                           AffineMap::inferFromExprList(indexingExprs)));
   result.addAttribute(getIteratorTypesAttrName(),
-                      builder->getStrArrayAttr(iteratorTypes));
+                      builder.getStrArrayAttr(iteratorTypes));
 }
 
-void vector::ContractionOp::build(Builder *builder, OperationState &result,
+void vector::ContractionOp::build(OpBuilder &builder, OperationState &result,
                                   Value lhs, Value rhs, Value acc,
                                   ArrayAttr indexingMaps,
                                   ArrayAttr iteratorTypes) {
@@ -461,10 +461,10 @@ static Type inferExtractOpResultType(VectorType vectorType,
                          vectorType.getElementType());
 }
 
-void vector::ExtractOp::build(Builder *builder, OperationState &result,
+void vector::ExtractOp::build(OpBuilder &builder, OperationState &result,
                               Value source, ArrayRef<int64_t> position) {
   result.addOperands(source);
-  auto positionAttr = getVectorSubscriptAttr(*builder, position);
+  auto positionAttr = getVectorSubscriptAttr(builder, position);
   result.addTypes(inferExtractOpResultType(source.getType().cast<VectorType>(),
                                            positionAttr));
   result.addAttribute(getPositionAttrName(), positionAttr);
@@ -528,13 +528,13 @@ static LogicalResult verify(vector::ExtractOp op) {
 // ExtractSlicesOp
 //===----------------------------------------------------------------------===//
 
-void ExtractSlicesOp::build(Builder *builder, OperationState &result,
+void ExtractSlicesOp::build(OpBuilder &builder, OperationState &result,
                             TupleType tupleType, Value vector,
                             ArrayRef<int64_t> sizes,
                             ArrayRef<int64_t> strides) {
   result.addOperands(vector);
-  auto sizesAttr = getVectorSubscriptAttr(*builder, sizes);
-  auto stridesAttr = getVectorSubscriptAttr(*builder, strides);
+  auto sizesAttr = getVectorSubscriptAttr(builder, sizes);
+  auto stridesAttr = getVectorSubscriptAttr(builder, strides);
   result.addTypes(tupleType);
   result.addAttribute(getSizesAttrName(), sizesAttr);
   result.addAttribute(getStridesAttrName(), stridesAttr);
@@ -634,10 +634,10 @@ static LogicalResult verify(BroadcastOp op) {
 // ShuffleOp
 //===----------------------------------------------------------------------===//
 
-void ShuffleOp::build(Builder *builder, OperationState &result, Value v1,
+void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value v1,
                       Value v2, ArrayRef<int64_t> mask) {
   result.addOperands({v1, v2});
-  auto maskAttr = getVectorSubscriptAttr(*builder, mask);
+  auto maskAttr = getVectorSubscriptAttr(builder, mask);
   result.addTypes(v1.getType());
   result.addAttribute(getMaskAttrName(), maskAttr);
 }
@@ -731,10 +731,10 @@ static LogicalResult verify(InsertElementOp op) {
 // InsertOp
 //===----------------------------------------------------------------------===//
 
-void InsertOp::build(Builder *builder, OperationState &result, Value source,
+void InsertOp::build(OpBuilder &builder, OperationState &result, Value source,
                      Value dest, ArrayRef<int64_t> position) {
   result.addOperands({source, dest});
-  auto positionAttr = getVectorSubscriptAttr(*builder, position);
+  auto positionAttr = getVectorSubscriptAttr(builder, position);
   result.addTypes(dest.getType());
   result.addAttribute(getPositionAttrName(), positionAttr);
 }
@@ -795,13 +795,13 @@ void InsertSlicesOp::getStrides(SmallVectorImpl<int64_t> &results) {
 // InsertStridedSliceOp
 //===----------------------------------------------------------------------===//
 
-void InsertStridedSliceOp::build(Builder *builder, OperationState &result,
+void InsertStridedSliceOp::build(OpBuilder &builder, OperationState &result,
                                  Value source, Value dest,
                                  ArrayRef<int64_t> offsets,
                                  ArrayRef<int64_t> strides) {
   result.addOperands({source, dest});
-  auto offsetsAttr = getVectorSubscriptAttr(*builder, offsets);
-  auto stridesAttr = getVectorSubscriptAttr(*builder, strides);
+  auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
+  auto stridesAttr = getVectorSubscriptAttr(builder, strides);
   result.addTypes(dest.getType());
   result.addAttribute(getOffsetsAttrName(), offsetsAttr);
   result.addAttribute(getStridesAttrName(), stridesAttr);
@@ -1074,13 +1074,13 @@ static Type inferStridedSliceOpResultType(VectorType vectorType,
   return VectorType::get(shape, vectorType.getElementType());
 }
 
-void StridedSliceOp::build(Builder *builder, OperationState &result,
+void StridedSliceOp::build(OpBuilder &builder, OperationState &result,
                            Value source, ArrayRef<int64_t> offsets,
                            ArrayRef<int64_t> sizes, ArrayRef<int64_t> strides) {
   result.addOperands(source);
-  auto offsetsAttr = getVectorSubscriptAttr(*builder, offsets);
-  auto sizesAttr = getVectorSubscriptAttr(*builder, sizes);
-  auto stridesAttr = getVectorSubscriptAttr(*builder, strides);
+  auto offsetsAttr = getVectorSubscriptAttr(builder, offsets);
+  auto sizesAttr = getVectorSubscriptAttr(builder, sizes);
+  auto stridesAttr = getVectorSubscriptAttr(builder, strides);
   result.addTypes(
       inferStridedSliceOpResultType(source.getType().cast<VectorType>(),
                                     offsetsAttr, sizesAttr, stridesAttr));
@@ -1466,7 +1466,8 @@ static MemRefType inferVectorTypeCastResultType(MemRefType t) {
   return MemRefType::get({}, VectorType::get(t.getShape(), t.getElementType()));
 }
 
-void TypeCastOp::build(Builder *builder, OperationState &result, Value source) {
+void TypeCastOp::build(OpBuilder &builder, OperationState &result,
+                       Value source) {
   result.addOperands(source);
   result.addTypes(
       inferVectorTypeCastResultType(source.getType().cast<MemRefType>()));

diff  --git a/mlir/lib/IR/Function.cpp b/mlir/lib/IR/Function.cpp
index 1933c4df18bd..29250130cd9d 100644
--- a/mlir/lib/IR/Function.cpp
+++ b/mlir/lib/IR/Function.cpp
@@ -24,8 +24,8 @@ using namespace mlir;
 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
                       ArrayRef<NamedAttribute> attrs) {
   OperationState state(location, "func");
-  Builder builder(location->getContext());
-  FuncOp::build(&builder, state, name, type, attrs);
+  OpBuilder builder(location->getContext());
+  FuncOp::build(builder, state, name, type, attrs);
   return cast<FuncOp>(Operation::create(state));
 }
 FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
@@ -41,16 +41,16 @@ FuncOp FuncOp::create(Location location, StringRef name, FunctionType type,
   return func;
 }
 
-void FuncOp::build(Builder *builder, OperationState &result, StringRef name,
+void FuncOp::build(OpBuilder &builder, OperationState &result, StringRef name,
                    FunctionType type, ArrayRef<NamedAttribute> attrs) {
   result.addAttribute(SymbolTable::getSymbolAttrName(),
-                      builder->getStringAttr(name));
+                      builder.getStringAttr(name));
   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
   result.attributes.append(attrs.begin(), attrs.end());
   result.addRegion();
 }
 
-void FuncOp::build(Builder *builder, OperationState &result, StringRef name,
+void FuncOp::build(OpBuilder &builder, OperationState &result, StringRef name,
                    FunctionType type, ArrayRef<NamedAttribute> attrs,
                    ArrayRef<NamedAttributeList> argAttrs) {
   build(builder, result, name, type, attrs);

diff  --git a/mlir/lib/IR/Module.cpp b/mlir/lib/IR/Module.cpp
index b441462821b6..a0ef3ffd7f55 100644
--- a/mlir/lib/IR/Module.cpp
+++ b/mlir/lib/IR/Module.cpp
@@ -16,19 +16,19 @@ using namespace mlir;
 // Module Operation.
 //===----------------------------------------------------------------------===//
 
-void ModuleOp::build(Builder *builder, OperationState &result,
+void ModuleOp::build(OpBuilder &builder, OperationState &result,
                      Optional<StringRef> name) {
-  ensureTerminator(*result.addRegion(), *builder, result.location);
+  ensureTerminator(*result.addRegion(), builder, result.location);
   if (name)
-    result.attributes.push_back(builder->getNamedAttr(
-        mlir::SymbolTable::getSymbolAttrName(), builder->getStringAttr(*name)));
+    result.attributes.push_back(builder.getNamedAttr(
+        mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(*name)));
 }
 
 /// Construct a module from the given context.
 ModuleOp ModuleOp::create(Location loc, Optional<StringRef> name) {
   OperationState state(loc, "module");
-  Builder builder(loc->getContext());
-  ModuleOp::build(&builder, state, name);
+  OpBuilder builder(loc->getContext());
+  ModuleOp::build(builder, state, name);
   return cast<ModuleOp>(Operation::create(state));
 }
 

diff  --git a/mlir/lib/IR/Operation.cpp b/mlir/lib/IR/Operation.cpp
index a60e6bf385f2..2e4a7ee02040 100644
--- a/mlir/lib/IR/Operation.cpp
+++ b/mlir/lib/IR/Operation.cpp
@@ -984,7 +984,7 @@ LogicalResult OpTrait::impl::verifyResultSizeAttr(Operation *op,
 // These functions are out-of-line implementations of the methods in BinaryOp,
 // which avoids them being template instantiated/duplicated.
 
-void impl::buildBinaryOp(Builder *builder, OperationState &result, Value lhs,
+void impl::buildBinaryOp(OpBuilder &builder, OperationState &result, Value lhs,
                          Value rhs) {
   assert(lhs.getType() == rhs.getType());
   result.addOperands({lhs, rhs});
@@ -1025,7 +1025,7 @@ void impl::printOneResultOp(Operation *op, OpAsmPrinter &p) {
 // CastOp implementation
 //===----------------------------------------------------------------------===//
 
-void impl::buildCastOp(Builder *builder, OperationState &result, Value source,
+void impl::buildCastOp(OpBuilder &builder, OperationState &result, Value source,
                        Type destType) {
   result.addOperands(source);
   result.addTypes(destType);
@@ -1066,7 +1066,7 @@ Value impl::foldCastOp(Operation *op) {
 /// terminator operation to insert.
 void impl::ensureRegionTerminator(
     Region &region, Location loc,
-    function_ref<Operation *()> buildTerminatorOp) {
+    function_ref<Operation *(OpBuilder &)> buildTerminatorOp) {
   if (region.empty())
     region.push_back(new Block);
 
@@ -1074,7 +1074,8 @@ void impl::ensureRegionTerminator(
   if (!block.empty() && block.back().isKnownTerminator())
     return;
 
-  block.push_back(buildTerminatorOp());
+  OpBuilder builder(loc.getContext());
+  block.push_back(buildTerminatorOp(builder));
 }
 
 //===----------------------------------------------------------------------===//

diff  --git a/mlir/test/lib/Dialect/Test/TestOps.td b/mlir/test/lib/Dialect/Test/TestOps.td
index 6bd5b1b16839..3a50b30080f8 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.td
+++ b/mlir/test/lib/Dialect/Test/TestOps.td
@@ -739,9 +739,9 @@ def OpSymbolBindingB : TEST_Op<"symbol_binding_b", []> {
 
   let builders = [
     OpBuilder<
-      "Builder *builder, OperationState &state, Value operand",
+      "OpBuilder &builder, OperationState &state, Value operand",
       [{
-        state.types.assign({builder->getIntegerType(32)});
+        state.types.assign({builder.getIntegerType(32)});
         state.addOperands({operand});
       }]>
   ];
@@ -851,10 +851,10 @@ def TwoResultOp : TEST_Op<"two_result"> {
 
   let builders = [
     OpBuilder<
-      "Builder *builder, OperationState &state, IntegerAttr kind",
+      "OpBuilder &builder, OperationState &state, IntegerAttr kind",
       [{
-        auto i32 = builder->getIntegerType(32);
-        auto f32 = builder->getF32Type();
+        auto i32 = builder.getIntegerType(32);
+        auto f32 = builder.getF32Type();
         state.types.assign({i32, f32});
         state.addAttribute("kind", kind);
       }]>
@@ -1007,9 +1007,9 @@ def MixedVResultOp3 : TEST_Op<"mixed_variadic_out3",
   // result type. So need to provide a builder not requiring result types.
   let builders = [
     OpBuilder<
-      "Builder *builder, OperationState &state, IntegerAttr count",
+      "OpBuilder &builder, OperationState &state, IntegerAttr count",
       [{
-        auto i32Type = builder->getIntegerType(32);
+        auto i32Type = builder.getIntegerType(32);
         state.addTypes(i32Type); // $output1
         SmallVector<Type, 4> types(count.getInt(), i32Type);
         state.addTypes(types); // $output2

diff  --git a/mlir/test/lib/Dialect/Test/TestPatterns.cpp b/mlir/test/lib/Dialect/Test/TestPatterns.cpp
index d21d59ca1e8b..655cd1dd1609 100644
--- a/mlir/test/lib/Dialect/Test/TestPatterns.cpp
+++ b/mlir/test/lib/Dialect/Test/TestPatterns.cpp
@@ -77,7 +77,7 @@ static void invokeCreateWithInferredReturnType(Operation *op) {
                                            inferredReturnTypes))) {
         OperationState state(location, OpTy::getOperationName());
         // TODO(jpienaar): Expand to regions.
-        OpTy::build(&b, state, values, op->getAttrs());
+        OpTy::build(b, state, values, op->getAttrs());
         (void)b.createOperation(state);
       }
     }

diff  --git a/mlir/test/mlir-tblgen/op-attribute.td b/mlir/test/mlir-tblgen/op-attribute.td
index 6e22912d1a2b..522dc2459fca 100644
--- a/mlir/test/mlir-tblgen/op-attribute.td
+++ b/mlir/test/mlir-tblgen/op-attribute.td
@@ -74,7 +74,7 @@ def AOp : NS_Op<"a_op", []> {
 
 // DEF:      void AOp::build(
 // DEF:        some-return-type aAttr, some-return-type bAttr, /*optional*/some-attr-kind cAttr
-// DEF:        odsState.addAttribute("aAttr", some-const-builder-call((*odsBuilder), aAttr));
+// DEF:        odsState.addAttribute("aAttr", some-const-builder-call(odsBuilder, aAttr));
 
 // DEF:      void AOp::build(
 // DEF:        ArrayRef<NamedAttribute> attributes
@@ -198,8 +198,8 @@ def DOp : NS_Op<"d_op", []> {
 // DECL: static void build({{.*}}, APInt i32_attr, APFloat f64_attr, StringRef str_attr, bool bool_attr, ::SomeI32Enum enum_attr, APInt dv_i32_attr, APFloat dv_f64_attr, StringRef dv_str_attr = "abc", bool dv_bool_attr = true, ::SomeI32Enum dv_enum_attr = ::SomeI32Enum::case5)
 
 // DEF-LABEL: DOp definitions
-// DEF: odsState.addAttribute("str_attr", (*odsBuilder).getStringAttr(str_attr));
-// DEF: odsState.addAttribute("dv_str_attr", (*odsBuilder).getStringAttr(dv_str_attr));
+// DEF: odsState.addAttribute("str_attr", odsBuilder.getStringAttr(str_attr));
+// DEF: odsState.addAttribute("dv_str_attr", odsBuilder.getStringAttr(dv_str_attr));
 
 // Test derived type attr.
 // ---
@@ -249,7 +249,7 @@ def MixOperandsAndAttrs : NS_Op<"mix_operands_and_attrs", []> {
 // DEF-LABEL: MixOperandsAndAttrs definitions
 // DEF-DAG: Value MixOperandsAndAttrs::operand()
 // DEF-DAG: Value MixOperandsAndAttrs::otherArg()
-// DEF-DAG: void MixOperandsAndAttrs::build(Builder *odsBuilder, OperationState &odsState, FloatAttr attr, Value operand, FloatAttr otherAttr, Value otherArg)
+// DEF-DAG: void MixOperandsAndAttrs::build(OpBuilder &odsBuilder, OperationState &odsState, FloatAttr attr, Value operand, FloatAttr otherAttr, Value otherArg)
 // DEF-DAG: APFloat MixOperandsAndAttrs::attr()
 // DEF-DAG: APFloat MixOperandsAndAttrs::otherAttr()
 
@@ -264,7 +264,7 @@ def UnitAttrOp : NS_Op<"unit_attr_op", []> {
 // DEF: bool UnitAttrOp::attr() {
 // DEF:   return {{.*}} != nullptr
 
-// DEF: build(Builder *odsBuilder, OperationState &odsState, /*optional*/UnitAttr attr)
+// DEF: build(OpBuilder &odsBuilder, OperationState &odsState, /*optional*/UnitAttr attr)
 
 
 // Test elementAttr field of TypedArrayAttr.

diff  --git a/mlir/test/mlir-tblgen/op-decl.td b/mlir/test/mlir-tblgen/op-decl.td
index eb736b7e6f0b..69f1cfe5d8aa 100644
--- a/mlir/test/mlir-tblgen/op-decl.td
+++ b/mlir/test/mlir-tblgen/op-decl.td
@@ -76,9 +76,9 @@ def NS_AOp : NS_Op<"a_op", [IsolatedFromAbove, IsolatedFromAbove]> {
 // CHECK:   FloatAttr attr2Attr()
 // CHECK:   Optional< APFloat > attr2();
 // CHECK:   static void build(Value val);
-// CHECK:   static void build(Builder *odsBuilder, OperationState &odsState, Type r, ArrayRef<Type> s, Value a, ValueRange b, IntegerAttr attr1, /*optional*/FloatAttr attr2, unsigned someRegionsCount)
-// CHECK:   static void build(Builder *odsBuilder, OperationState &odsState, Type r, ArrayRef<Type> s, Value a, ValueRange b, APInt attr1, /*optional*/FloatAttr attr2, unsigned someRegionsCount)
-// CHECK:   static void build(Builder *, OperationState &odsState, ArrayRef<Type> resultTypes, ValueRange operands, ArrayRef<NamedAttribute> attributes, unsigned numRegions)
+// CHECK:   static void build(OpBuilder &odsBuilder, OperationState &odsState, Type r, ArrayRef<Type> s, Value a, ValueRange b, IntegerAttr attr1, /*optional*/FloatAttr attr2, unsigned someRegionsCount)
+// CHECK:   static void build(OpBuilder &odsBuilder, OperationState &odsState, Type r, ArrayRef<Type> s, Value a, ValueRange b, APInt attr1, /*optional*/FloatAttr attr2, unsigned someRegionsCount)
+// CHECK:   static void build(OpBuilder &, OperationState &odsState, ArrayRef<Type> resultTypes, ValueRange operands, ArrayRef<NamedAttribute> attributes, unsigned numRegions)
 // CHECK:   static ParseResult parse(OpAsmParser &parser, OperationState &result);
 // CHECK:   void print(OpAsmPrinter &p);
 // CHECK:   LogicalResult verify();
@@ -120,7 +120,7 @@ def NS_EOp : NS_Op<"op_with_optionals", []> {
 // CHECK-LABEL: NS::EOp declarations
 // CHECK:   Value a();
 // CHECK:   Value b();
-// CHECK:   static void build(Builder *odsBuilder, OperationState &odsState, /*optional*/Type b, /*optional*/Value a)
+// CHECK:   static void build(OpBuilder &odsBuilder, OperationState &odsState, /*optional*/Type b, /*optional*/Value a)
 
 // Check that default builders can be suppressed.
 // ---

diff  --git a/mlir/test/mlir-tblgen/op-result.td b/mlir/test/mlir-tblgen/op-result.td
index c8bdd15cf2f1..7886c2772a21 100644
--- a/mlir/test/mlir-tblgen/op-result.td
+++ b/mlir/test/mlir-tblgen/op-result.td
@@ -23,9 +23,9 @@ def OpB : NS_Op<"same_input_output_type_op", [SameOperandsAndResultType]> {
 }
 
 // CHECK-LABEL: OpB definitions
-// CHECK: void OpB::build(Builder *odsBuilder, OperationState &odsState, Type y, Value x)
+// CHECK: void OpB::build(OpBuilder &odsBuilder, OperationState &odsState, Type y, Value x)
 // CHECK:   odsState.addTypes(y);
-// CHECK: void OpB::build(Builder *odsBuilder, OperationState &odsState, Value x)
+// CHECK: void OpB::build(OpBuilder &odsBuilder, OperationState &odsState, Value x)
 // CHECK:   odsState.addTypes({x.getType()});
 
 def OpC : NS_Op<"three_normal_result_op", []> {
@@ -33,12 +33,12 @@ def OpC : NS_Op<"three_normal_result_op", []> {
 }
 
 // CHECK-LABEL: OpC definitions
-// CHECK:       void OpC::build(Builder *odsBuilder, OperationState &odsState, Type x, Type resultType1, Type z)
+// CHECK:       void OpC::build(OpBuilder &odsBuilder, OperationState &odsState, Type x, Type resultType1, Type z)
 // CHECK-NEXT:   odsState.addTypes(x)
 // CHECK-NEXT:   odsState.addTypes(resultType1)
 // CHECK-NEXT:   odsState.addTypes(z)
 
-// CHECK:      void OpC::build(Builder *odsBuilder, OperationState &odsState, ArrayRef<Type> resultTypes) {
+// CHECK:      void OpC::build(OpBuilder &odsBuilder, OperationState &odsState, ArrayRef<Type> resultTypes) {
 // CHECK-NEXT:   assert(resultTypes.size() == 3u && "mismatched number of results");
 // CHECK-NEXT:   odsState.addTypes(resultTypes);
 
@@ -49,7 +49,7 @@ def OpD : NS_Op<"type_attr_as_result_type", [FirstAttrDerivedResultType]> {
 }
 
 // CHECK-LABEL: OpD definitions
-// CHECK: void OpD::build(Builder *odsBuilder, OperationState &odsState, ValueRange operands, ArrayRef<NamedAttribute> attributes)
+// CHECK: void OpD::build(OpBuilder &odsBuilder, OperationState &odsState, ValueRange operands, ArrayRef<NamedAttribute> attributes)
 // CHECK: odsState.addTypes({attr.second.cast<TypeAttr>().getValue()});
 
 def OpE : NS_Op<"value_attr_as_result_type", [FirstAttrDerivedResultType]> {
@@ -58,7 +58,7 @@ def OpE : NS_Op<"value_attr_as_result_type", [FirstAttrDerivedResultType]> {
 }
 
 // CHECK-LABEL: OpE definitions
-// CHECK: void OpE::build(Builder *odsBuilder, OperationState &odsState, ValueRange operands, ArrayRef<NamedAttribute> attributes)
+// CHECK: void OpE::build(OpBuilder &odsBuilder, OperationState &odsState, ValueRange operands, ArrayRef<NamedAttribute> attributes)
 // CHECK: odsState.addTypes({attr.second.getType()});
 
 def OpF : NS_Op<"one_variadic_result_op", []> {
@@ -77,7 +77,7 @@ def OpG : NS_Op<"one_normal_and_one_variadic_result_op", []> {
 
 // CHECK-LABEL: OpG definitions
 
-// CHECK:      void OpG::build(Builder *odsBuilder, OperationState &odsState, Type x, ArrayRef<Type> y)
+// CHECK:      void OpG::build(OpBuilder &odsBuilder, OperationState &odsState, Type x, ArrayRef<Type> y)
 // CHECK-NEXT:   odsState.addTypes(x);
 // CHECK-NEXT:   odsState.addTypes(y);
 
@@ -109,5 +109,5 @@ def OpK : NS_Op<"only_input_is_variadic_with_same_value_type_op", [SameOperandsA
   let results = (outs AnyTensor:$result);
 }
 
-// CHECK-LABEL: OpK::build(Builder *odsBuilder, OperationState &odsState, ValueRange input)
+// CHECK-LABEL: OpK::build(OpBuilder &odsBuilder, OperationState &odsState, ValueRange input)
 // CHECK: odsState.addTypes({input.front().getType()});

diff  --git a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
index c1395f7655ed..424a29716368 100644
--- a/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
+++ b/mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
@@ -1467,13 +1467,13 @@ void TCParser::printODS(llvm::raw_ostream &os, StringRef cppOpName,
       let results = (outs Variadic<AnyRankedTensor>:$output_tensors);
       let regions = (region SizedRegion<1>:$region);
       let builders = [OpBuilder<
-        "Builder *b, OperationState &result, TypeRange outputTypes, "
+        "OpBuilder &b, OperationState &result, TypeRange outputTypes, "
         # "ValueRange views",
         [{{
           result.addOperands(views);
           result.addTypes(outputTypes);
           buildNamedStructuredOpRegion<{0}>(
-            *b, result, TypeRange(views), outputTypes);
+            b, result, TypeRange(views), outputTypes);
         }]>
       ];
       let parser = [{

diff  --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
index ad9c070c4530..bbfc06f883f8 100644
--- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
@@ -743,7 +743,7 @@ void OpEmitter::genSeparateArgParamBuilder() {
       // TODO(jpienaar): Expand to handle regions.
       body << formatv(R"(
         SmallVector<Type, 2> inferredReturnTypes;
-        if (succeeded({0}::inferReturnTypes(odsBuilder->getContext(),
+        if (succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
                       {1}.location, {1}.operands, {1}.attributes,
                       /*regions=*/{{}, inferredReturnTypes)))
           {1}.addTypes(inferredReturnTypes);
@@ -800,7 +800,7 @@ void OpEmitter::genUseOperandAsResultTypeCollectiveParamBuilder() {
 
   // Signature
   std::string params =
-      std::string("Builder *odsBuilder, OperationState &") + builderOpState +
+      std::string("OpBuilder &odsBuilder, OperationState &") + builderOpState +
       ", ValueRange operands, ArrayRef<NamedAttribute> attributes";
   if (op.getNumVariadicRegions())
     params += ", unsigned numRegions";
@@ -830,7 +830,7 @@ void OpEmitter::genUseOperandAsResultTypeCollectiveParamBuilder() {
 void OpEmitter::genInferredTypeCollectiveParamBuilder() {
   // TODO(jpienaar): Expand to support regions.
   const char *params =
-      "Builder *odsBuilder, OperationState &{0}, "
+      "OpBuilder &odsBuilder, OperationState &{0}, "
       "ValueRange operands, ArrayRef<NamedAttribute> attributes";
   auto &m =
       opClass.newMethod("void", "build", formatv(params, builderOpState).str(),
@@ -838,7 +838,7 @@ void OpEmitter::genInferredTypeCollectiveParamBuilder() {
   auto &body = m.body();
   body << formatv(R"(
     SmallVector<Type, 2> inferredReturnTypes;
-    if (succeeded({0}::inferReturnTypes(odsBuilder->getContext(),
+    if (succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
                   {1}.location, operands, attributes,
                   /*regions=*/{{}, inferredReturnTypes)))
       build(odsBuilder, odsState, inferredReturnTypes, operands, attributes);
@@ -871,7 +871,7 @@ void OpEmitter::genUseOperandAsResultTypeSeparateParamBuilder() {
 
 void OpEmitter::genUseAttrAsResultTypeBuilder() {
   std::string params =
-      std::string("Builder *odsBuilder, OperationState &") + builderOpState +
+      std::string("OpBuilder &odsBuilder, OperationState &") + builderOpState +
       ", ValueRange operands, ArrayRef<NamedAttribute> attributes";
   auto &m = opClass.newMethod("void", "build", params, OpMethod::MP_Static);
   auto &body = m.body();
@@ -961,7 +961,7 @@ void OpEmitter::genCollectiveParamBuilder() {
   int numVariadicOperands = op.getNumVariableLengthOperands();
   int numNonVariadicOperands = numOperands - numVariadicOperands;
   // Signature
-  std::string params = std::string("Builder *, OperationState &") +
+  std::string params = std::string("OpBuilder &, OperationState &") +
                        builderOpState +
                        ", ArrayRef<Type> resultTypes, ValueRange operands, "
                        "ArrayRef<NamedAttribute> attributes";
@@ -1013,7 +1013,7 @@ void OpEmitter::buildParamList(std::string &paramList,
   auto numResults = op.getNumResults();
   resultTypeNames.reserve(numResults);
 
-  paramList = "Builder *odsBuilder, OperationState &";
+  paramList = "OpBuilder &odsBuilder, OperationState &";
   paramList.append(builderOpState);
 
   switch (typeParamKind) {
@@ -1151,7 +1151,7 @@ void OpEmitter::genCodeForAddingArgAndRegionForBuilder(OpMethodBody &body,
   if (op.getTrait("OpTrait::AttrSizedOperandSegments")) {
     body << "  " << builderOpState
          << ".addAttribute(\"operand_segment_sizes\", "
-            "odsBuilder->getI32VectorAttr({";
+            "odsBuilder.getI32VectorAttr({";
     interleaveComma(llvm::seq<int>(0, op.getNumOperands()), body, [&](int i) {
       if (op.getOperand(i).isOptional())
         body << "(" << getArgumentName(op, i) << " ? 1 : 0)";
@@ -1175,7 +1175,7 @@ void OpEmitter::genCodeForAddingArgAndRegionForBuilder(OpMethodBody &body,
         // If this is a raw value, then we need to wrap it in an Attribute
         // instance.
         FmtContext fctx;
-        fctx.withBuilder("(*odsBuilder)");
+        fctx.withBuilder("odsBuilder");
 
         std::string builderTemplate =
             std::string(attr.getConstBuilderTemplate());

diff  --git a/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp b/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
index c9f1e1570fa6..06c417ca23f7 100644
--- a/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
+++ b/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
@@ -38,7 +38,7 @@ class SerializationTest : public ::testing::Test {
   SerializationTest() { createModuleOp(); }
 
   void createModuleOp() {
-    Builder builder(&context);
+    OpBuilder builder(&context);
     OperationState state(UnknownLoc::get(&context),
                          spirv::ModuleOp::getOperationName());
     state.addAttribute("addressing_model",
@@ -51,7 +51,7 @@ class SerializationTest : public ::testing::Test {
                        spirv::VerCapExtAttr::get(
                            spirv::Version::V_1_0, ArrayRef<spirv::Capability>(),
                            ArrayRef<spirv::Extension>(), &context));
-    spirv::ModuleOp::build(&builder, state);
+    spirv::ModuleOp::build(builder, state);
     module = cast<spirv::ModuleOp>(Operation::create(state));
   }
 


        


More information about the flang-commits mailing list