9 #ifndef MLIR_IR_BUILDERS_H
10 #define MLIR_IR_BUILDERS_H
13 #include "llvm/Support/Compiler.h"
30 class RankedTensorType;
31 class UnrankedTensorType;
42 class DenseElementsAttr;
43 class DenseIntElementsAttr;
92 template <
typename Ty,
typename... Args>
99 template <
typename Attr,
typename... Args>
217 if (!region->
empty())
253 assert(terminator !=
nullptr &&
"the block has no terminator");
319 : block(insertBlock), point(insertPt) {}
322 bool isSet()
const {
return (block !=
nullptr); }
328 Block *block =
nullptr;
350 : builder(other.builder), ip(other.ip) {
351 other.builder =
nullptr;
365 this->block =
nullptr;
386 this->insertPoint = insertPoint;
410 auto blockArg = llvm::cast<BlockArgument>(val);
444 TypeRange argTypes = std::nullopt,
445 ArrayRef<Location> locs = std::nullopt);
451 Block *
createBlock(Block *insertBefore, TypeRange argTypes = std::nullopt,
452 ArrayRef<Location> locs = std::nullopt);
459 Operation *
insert(Operation *op);
462 Operation *
create(
const OperationState &state);
465 Operation *
create(Location loc, StringAttr opName, ValueRange operands,
466 TypeRange types = {},
467 ArrayRef<NamedAttribute> attributes = {},
468 BlockRange successors = {},
469 MutableArrayRef<std::unique_ptr<Region>> regions = {});
473 template <
typename OpT>
474 RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
475 std::optional<RegisteredOperationName> opName =
477 if (LLVM_UNLIKELY(!opName)) {
478 llvm::report_fatal_error(
479 "Building op `" + OpT::getOperationName() +
480 "` but it isn't registered in this MLIRContext: the dialect may not "
481 "be loaded or this operation isn't registered by the dialect. See "
482 "also https://mlir.llvm.org/getting_started/Faq/"
483 "#registered-loaded-dependent-whats-up-with-dialects-management");
490 template <
typename OpTy,
typename... Args>
493 getCheckRegisteredInfo<OpTy>(location.
getContext()));
494 OpTy::build(*
this, state, std::forward<Args>(args)...);
496 auto result = dyn_cast<OpTy>(op);
497 assert(result &&
"builder didn't return the right type");
504 template <
typename OpTy,
typename... Args>
510 getCheckRegisteredInfo<OpTy>(location.
getContext()));
511 OpTy::build(*
this, state, std::forward<Args>(args)...);
522 template <
typename OpTy,
typename... Args>
523 std::enable_if_t<OpTy::template hasTrait<OpTrait::OneResult>(),
Value>
526 createOrFold<OpTy>(results, location, std::forward<Args>(args)...);
527 return results.front();
531 template <
typename OpTy,
typename... Args>
532 std::enable_if_t<OpTy::template hasTrait<OpTrait::ZeroResults>(), OpTy>
534 auto op = create<OpTy>(location, std::forward<Args>(args)...);
536 (void)
tryFold(op.getOperation(), unused);
560 return insert(op.cloneWithoutRegions(mapper));
563 return insert(op.cloneWithoutRegions());
565 template <
typename OpT>
576 Block *block =
nullptr;
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
Operation * getTerminator()
Get the terminator operation of this block.
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
This class is a general helper class for creating context-global objects like types,...
FloatType getFloat8E5M2Type()
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'.
FloatType getFloat8E4M3B11FNUZType()
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.
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.
MLIRContext * getContext() const
ArrayAttr getTypeArrayAttr(TypeRange values)
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
FloatType getFloat8E4M3FNType()
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
AffineMap getSymbolIdentityMap()
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
FloatType getFloat8E4M3FNUZType()
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)
FloatType getFloat8E5M2FNUZType()
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.
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.
This is a utility class for mapping one set of IR entities to another.
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.
RAII guard to reset the insertion point of the builder when destroyed.
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
InsertionGuard & operator=(const InsertionGuard &)=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.
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...
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...
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.
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
OpBuilder(Region ®ion, Listener *listener=nullptr)
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...
Listener * listener
The optional listener for events of this builder.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes=std::nullopt, ArrayRef< Location > locs=std::nullopt)
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
std::enable_if_t< OpTy::template hasTrait< OpTrait::ZeroResults >), OpTy > createOrFold(Location location, Args &&...args)
Overload to create or fold a zero 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...
std::enable_if_t< OpTy::template hasTrait< OpTrait::OneResult >), Value > createOrFold(Location location, Args &&...args)
Overload to create or fold a single result operation.
Block * getBlock() const
Returns the current block of the builder.
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...
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results)
Attempts to fold the given operation and places new results within 'results'.
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Operation is the basic unit of execution within MLIR.
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.
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 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.
Base class for DenseArrayAttr that is instantiated and specialized for each supported element type be...
@ Type
An inlay hint that for a type annotation.
This header declares functions that assist transformations in the MemRef dialect.
bool succeeded(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a success value.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
This class represents an efficient way to signal success or failure.
Base class for listeners.
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 notifyBlockCreated(Block *block)
Notification handler for when a block is created using the builder.
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op)
Notification handler for when an operation is inserted into the builder.
This represents an operation in an abstracted form, suitable for use with the builder APIs.