9#ifndef MLIR_IR_BUILDERS_H
10#define MLIR_IR_BUILDERS_H
13#include "llvm/Support/Compiler.h"
22class FileLineColRange;
31class RankedTensorType;
32class UnrankedTensorType;
90 template <
typename Ty,
typename... Args>
92 return Ty::get(
context, std::forward<Args>(args)...);
97 template <
typename Attr,
typename... Args>
99 return Attr::get(
context, std::forward<Args>(args)...);
219 if (!region->
empty())
254 auto *terminator = block->getTerminator();
255 assert(terminator !=
nullptr &&
"the block has no terminator");
334 : block(insertBlock), point(insertPt) {}
337 bool isSet()
const {
return (block !=
nullptr); }
343 Block *block =
nullptr;
355 builder->restoreInsertionPoint(ip);
365 : builder(other.builder), ip(other.ip) {
366 other.builder =
nullptr;
380 this->block =
nullptr;
401 this->insertPoint = insertPoint;
425 auto blockArg = llvm::cast<BlockArgument>(val);
459 TypeRange argTypes = {}, ArrayRef<Location> locs = {});
466 ArrayRef<Location> locs = {});
473 Operation *
insert(Operation *op);
476 Operation *
create(
const OperationState &state);
481 ArrayRef<NamedAttribute> attributes = {},
482 BlockRange successors = {},
483 MutableArrayRef<std::unique_ptr<Region>> regions = {});
487 template <
typename OpT>
488 RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
489 std::optional<RegisteredOperationName> opName =
491 if (LLVM_UNLIKELY(!opName)) {
492 llvm::report_fatal_error(
493 "Building op `" + OpT::getOperationName() +
494 "` but it isn't known in this MLIRContext: the dialect may not "
495 "be loaded or this operation hasn't been added by the dialect. See "
496 "also https://mlir.llvm.org/getting_started/Faq/"
497 "#registered-loaded-dependent-whats-up-with-dialects-management");
504 template <
typename OpTy,
typename... Args>
505 [[deprecated(
"Use OpTy::create instead")]]
508 getCheckRegisteredInfo<OpTy>(location.
getContext()));
509 OpTy::build(*
this, state, std::forward<Args>(args)...);
511 auto result = dyn_cast<OpTy>(op);
512 assert(
result &&
"builder didn't return the right type");
525 template <
typename OpTy,
typename... Args>
531 getCheckRegisteredInfo<OpTy>(location.
getContext()));
532 OpTy::build(*
this, state, std::forward<Args>(args)...);
535 block->getOperations().insert(insertPoint, op);
538 if (succeeded(
tryFold(op, results)) && !results.empty()) {
546 results.assign(opResults.begin(), opResults.end());
548 listener->notifyOperationInserted(op, {});
552 template <
typename OpTy,
typename... Args>
553 std::enable_if_t<OpTy::template hasTrait<OpTrait::OneResult>(),
Value>
557 return results.front();
561 template <
typename OpTy,
typename... Args>
562 std::enable_if_t<OpTy::template hasTrait<OpTrait::ZeroResults>(), OpTy>
564 auto op = OpTy::create(*
this, location, std::forward<Args>(args)...);
600 template <
typename OpT>
621 Block *block =
nullptr;
634 template <
typename... T>
636 :
OpBuilder(std::forward<T>(operands)...), curLoc(loc) {}
656 auto *terminator = block->getTerminator();
657 assert(terminator !=
nullptr &&
"the block has no terminator");
672 template <
typename OpTy,
typename... Args>
674 return OpTy::create(*
this, curLoc, std::forward<Args>(args)...);
680 template <
typename OpTy,
typename... Args>
686 template <
typename OpTy,
typename... Args>
687 std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::OneResult>(),
Value>
693 template <
typename OpTy,
typename... Args>
694 std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::ZeroResults>(), OpTy>
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
OpListType::iterator iterator
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
IntegerAttr getIndexAttr(int64_t value)
AffineMap getSingleDimShiftAffineMap(int64_t shift)
Returns a map that shifts its (single) input dimension by 'shift'.
ArrayAttr getIndexArrayAttr(ArrayRef< int64_t > values)
DenseF64ArrayAttr getDenseF64ArrayAttr(ArrayRef< double > values)
DenseI8ArrayAttr getDenseI8ArrayAttr(ArrayRef< int8_t > values)
IntegerAttr getI32IntegerAttr(int32_t value)
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
DenseIntElementsAttr getBoolVectorAttr(ArrayRef< bool > values)
Vector-typed DenseIntElementsAttr getters. values must not be empty.
TupleType getTupleType(TypeRange elementTypes)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getF64FloatAttr(double value)
AffineMap getShiftedAffineMap(AffineMap map, int64_t shift)
Returns an affine map that is a translation (shift) of all result expressions in 'map' by 'shift'.
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
FloatAttr getF16FloatAttr(float value)
AffineMap getDimIdentityMap()
AffineMap getMultiDimIdentityMap(unsigned rank)
IntegerAttr getI16IntegerAttr(int16_t value)
DenseI16ArrayAttr getDenseI16ArrayAttr(ArrayRef< int16_t > values)
AffineExpr getAffineSymbolExpr(unsigned position)
DenseFPElementsAttr getF32VectorAttr(ArrayRef< float > values)
FloatAttr getFloatAttr(Type type, double value)
AffineExpr getAffineConstantExpr(int64_t constant)
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
BoolAttr getBoolAttr(bool value)
StringAttr getStringAttr(const Twine &bytes)
Builder(MLIRContext *context)
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
IntegerAttr getSI32IntegerAttr(int32_t value)
Signed and unsigned integer attribute getters.
GraphType getGraphType(TypeRange inputs, TypeRange results)
TypedAttr getZeroAttr(Type type)
Location getFusedLoc(ArrayRef< Location > locs, Attribute metadata=Attribute())
AffineExpr getAffineDimExpr(unsigned position)
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
ArrayAttr getTypeArrayAttr(TypeRange values)
FloatType getF8E8M0Type()
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
AffineMap getSymbolIdentityMap()
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
FloatAttr getF32FloatAttr(float value)
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
NamedAttribute getNamedAttr(StringRef name, Attribute val)
IntegerAttr getUI32IntegerAttr(uint32_t value)
IntegerAttr getI8IntegerAttr(int8_t value)
ArrayAttr getF32ArrayAttr(ArrayRef< float > values)
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
DenseIntElementsAttr getIndexVectorAttr(ArrayRef< int64_t > values)
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
TypedAttr getOneAttr(Type type)
An attribute that represents a reference to a dense vector or tensor object.
An attribute that represents a reference to a dense float vector or tensor object.
An attribute that represents a reference to a dense integer vector or tensor object.
An instance of this location represents a tuple of file, line number, and column number.
This is a utility class for mapping one set of IR entities to another.
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::OneResult >(), Value > createOrFold(Args &&...args)
Overload to create or fold a single result operation.
void setLoc(Location loc)
Location getLoc() const
Accessors for the implied location.
mlir::InFlightDiagnostic emitWarning(const llvm::Twine &message=llvm::Twine())
static ImplicitLocOpBuilder atBlockTerminator(Location loc, Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
ImplicitLocOpBuilder(Location loc, T &&...operands)
OpBuilder has a bunch of convenience constructors - we support them all with the additional Location.
static ImplicitLocOpBuilder atBlockBegin(Location loc, Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::ZeroResults >(), OpTy > createOrFold(Args &&...args)
Overload to create or fold a zero result operation.
mlir::InFlightDiagnostic emitError(const llvm::Twine &message=llvm::Twine())
This builder can also be used to emit diagnostics to the current location.
mlir::InFlightDiagnostic emitRemark(const llvm::Twine &message=llvm::Twine())
OpTy create(Args &&...args)
Create an operation of specific op type at the current insertion point and location.
void createOrFold(llvm::SmallVectorImpl< Value > &results, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
static ImplicitLocOpBuilder atBlockEnd(Location loc, Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to after the last operation in the block but still insid...
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext * getContext() const
Return the context this location is uniqued in.
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
This class represents a saved insertion point.
InsertPoint()=default
Creates a new insertion point which doesn't point to anything.
Block::iterator getPoint() const
bool isSet() const
Returns true if this insert point is set.
InsertPoint(Block *insertBlock, Block::iterator insertPt)
Creates a new insertion point at the given location.
InsertionGuard & operator=(const InsertionGuard &)=delete
InsertionGuard(OpBuilder &builder)
InsertionGuard(InsertionGuard &&other) noexcept
Implement the move constructor to clear the builder field of other.
InsertionGuard(const InsertionGuard &)=delete
InsertionGuard & operator=(InsertionGuard &&other)=delete
This class helps build Operations.
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
OpBuilder(Region *region, Listener *listener=nullptr)
Create a builder and set the insertion point to the start of the region.
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
std::enable_if_t< OpTy::template hasTrait< OpTrait::ZeroResults >(), OpTy > createOrFold(Location location, Args &&...args)
Overload to create or fold a zero result operation.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * cloneWithoutRegions(Operation &op)
OpT cloneWithoutRegions(OpT op)
OpBuilder(MLIRContext *ctx, Listener *listener=nullptr)
Create a builder with the given context.
void clearInsertionPoint()
Reset the insertion point to no location.
static OpBuilder atBlockEnd(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to after the last operation in the block but still insid...
Block * getBlock() const
Returns the current block of the builder.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPoint(Operation *op)
Sets the insertion point to the specified operation, which will cause subsequent insertions to go rig...
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
OpBuilder(Region ®ion, Listener *listener=nullptr)
void cloneRegionBefore(Region ®ion, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
OpBuilder(Block *block, Block::iterator insertPoint, Listener *listener=nullptr)
OpTy create(Location location, Args &&...args)
Create an operation of specific op type at the current insertion point.
OpBuilder(Operation *op, Listener *listener=nullptr)
Create a builder and set insertion point to the given operation, which will cause subsequent insertio...
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results, SmallVectorImpl< Operation * > *materializedConstants=nullptr)
Attempts to fold the given operation and places new results within results.
Listener * listener
The optional listener for events of this builder.
std::enable_if_t< OpTy::template hasTrait< OpTrait::OneResult >(), Value > createOrFold(Location location, Args &&...args)
Overload to create or fold a single result operation.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Operation is the basic unit of execution within MLIR.
Block * getBlock()
Returns the operation block that contains this operation.
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, OpaqueProperties properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
result_range getResults()
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockListType::iterator iterator
static std::optional< RegisteredOperationName > lookup(StringRef name, MLIRContext *ctx)
Lookup the registered operation information for the given operation.
This class implements the result iterators for the Operation class.
static TypeID get()
Construct a type info object for the given type T.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
detail::DenseArrayAttrImpl< int8_t > DenseI8ArrayAttr
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
InFlightDiagnostic emitRemark(Location loc)
Utility method to emit a remark message using this location.
detail::DenseArrayAttrImpl< double > DenseF64ArrayAttr
detail::DenseArrayAttrImpl< bool > DenseBoolArrayAttr
detail::DenseArrayAttrImpl< float > DenseF32ArrayAttr
detail::DenseArrayAttrImpl< int16_t > DenseI16ArrayAttr
Kind
The kind of listener.
@ RewriterBaseListener
RewriterBase::Listener or user-derived class.
@ OpBuilderListener
OpBuilder::Listener or user-derived class.
This class represents a listener that may be used to hook into various actions within an OpBuilder.
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
This represents an operation in an abstracted form, suitable for use with the builder APIs.