MLIR  22.0.0git
Builders.h
Go to the documentation of this file.
1 //===- Builders.h - Helpers for constructing MLIR Classes -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef MLIR_IR_BUILDERS_H
10 #define MLIR_IR_BUILDERS_H
11 
12 #include "mlir/IR/OpDefinition.h"
13 #include "llvm/Support/Compiler.h"
14 #include <optional>
15 
16 namespace mlir {
17 
18 class AffineExpr;
19 class IRMapping;
20 class UnknownLoc;
21 class FileLineColLoc;
22 class FileLineColRange;
23 class Type;
24 class IntegerType;
25 class FloatType;
26 class FunctionType;
27 class GraphType;
28 class IndexType;
29 class MemRefType;
30 class VectorType;
31 class RankedTensorType;
32 class UnrankedTensorType;
33 class TupleType;
34 class NoneType;
35 class BoolAttr;
36 class IntegerAttr;
37 class FloatAttr;
38 class StringAttr;
39 class TypeAttr;
40 class ArrayAttr;
41 class SymbolRefAttr;
42 class ElementsAttr;
43 class DenseElementsAttr;
44 class DenseIntElementsAttr;
45 class AffineMapAttr;
46 class AffineMap;
47 class UnitAttr;
48 
49 /// This class is a general helper class for creating context-global objects
50 /// like types, attributes, and affine expressions.
51 class Builder {
52 public:
54  explicit Builder(Operation *op) : Builder(op->getContext()) {}
55 
56  MLIRContext *getContext() const { return context; }
57 
58  // Locations.
61  Attribute metadata = Attribute());
62 
63  // Types.
64  FloatType getF8E8M0Type();
65  FloatType getBF16Type();
66  FloatType getF16Type();
67  FloatType getTF32Type();
68  FloatType getF32Type();
69  FloatType getF64Type();
70  FloatType getF80Type();
71  FloatType getF128Type();
72 
73  IndexType getIndexType();
74 
75  IntegerType getI1Type();
76  IntegerType getI2Type();
77  IntegerType getI4Type();
78  IntegerType getI8Type();
79  IntegerType getI16Type();
80  IntegerType getI32Type();
81  IntegerType getI64Type();
82  IntegerType getIntegerType(unsigned width);
83  IntegerType getIntegerType(unsigned width, bool isSigned);
84  FunctionType getFunctionType(TypeRange inputs, TypeRange results);
85  GraphType getGraphType(TypeRange inputs, TypeRange results);
86  TupleType getTupleType(TypeRange elementTypes);
87  NoneType getNoneType();
88 
89  /// Get or construct an instance of the type `Ty` with provided arguments.
90  template <typename Ty, typename... Args>
91  Ty getType(Args &&...args) {
92  return Ty::get(context, std::forward<Args>(args)...);
93  }
94 
95  /// Get or construct an instance of the attribute `Attr` with provided
96  /// arguments.
97  template <typename Attr, typename... Args>
98  Attr getAttr(Args &&...args) {
99  return Attr::get(context, std::forward<Args>(args)...);
100  }
101 
102  // Attributes.
103  NamedAttribute getNamedAttr(StringRef name, Attribute val);
104 
105  UnitAttr getUnitAttr();
106  BoolAttr getBoolAttr(bool value);
107  DictionaryAttr getDictionaryAttr(ArrayRef<NamedAttribute> value);
108  IntegerAttr getIntegerAttr(Type type, int64_t value);
109  IntegerAttr getIntegerAttr(Type type, const APInt &value);
110  FloatAttr getFloatAttr(Type type, double value);
111  FloatAttr getFloatAttr(Type type, const APFloat &value);
112  StringAttr getStringAttr(const Twine &bytes);
113  ArrayAttr getArrayAttr(ArrayRef<Attribute> value);
114 
115  // Returns a 0-valued attribute of the given `type`. This function only
116  // supports boolean, integer, and 16-/32-/64-bit float types, and vector or
117  // ranked tensor of them. Returns null attribute otherwise.
118  TypedAttr getZeroAttr(Type type);
119  // Returns a 1-valued attribute of the given `type`.
120  // Type constraints are the same as `getZeroAttr`.
121  TypedAttr getOneAttr(Type type);
122 
123  // Convenience methods for fixed types.
124  FloatAttr getF16FloatAttr(float value);
125  FloatAttr getF32FloatAttr(float value);
126  FloatAttr getF64FloatAttr(double value);
127 
128  IntegerAttr getI8IntegerAttr(int8_t value);
129  IntegerAttr getI16IntegerAttr(int16_t value);
130  IntegerAttr getI32IntegerAttr(int32_t value);
131  IntegerAttr getI64IntegerAttr(int64_t value);
132  IntegerAttr getIndexAttr(int64_t value);
133 
134  /// Signed and unsigned integer attribute getters.
135  IntegerAttr getSI32IntegerAttr(int32_t value);
136  IntegerAttr getUI32IntegerAttr(uint32_t value);
137 
138  /// Vector-typed DenseIntElementsAttr getters. `values` must not be empty.
143 
146 
147  /// Tensor-typed DenseIntElementsAttr getters. `values` can be empty.
148  /// These are generally preferable for representing general lists of integers
149  /// as attributes.
153 
154  /// Tensor-typed DenseArrayAttr getters.
162 
163  ArrayAttr getAffineMapArrayAttr(ArrayRef<AffineMap> values);
164  ArrayAttr getBoolArrayAttr(ArrayRef<bool> values);
165  ArrayAttr getI32ArrayAttr(ArrayRef<int32_t> values);
166  ArrayAttr getI64ArrayAttr(ArrayRef<int64_t> values);
167  ArrayAttr getIndexArrayAttr(ArrayRef<int64_t> values);
168  ArrayAttr getF32ArrayAttr(ArrayRef<float> values);
169  ArrayAttr getF64ArrayAttr(ArrayRef<double> values);
170  ArrayAttr getStrArrayAttr(ArrayRef<StringRef> values);
171  ArrayAttr getTypeArrayAttr(TypeRange values);
172 
173  // Affine expressions and affine maps.
174  AffineExpr getAffineDimExpr(unsigned position);
175  AffineExpr getAffineSymbolExpr(unsigned position);
176  AffineExpr getAffineConstantExpr(int64_t constant);
177 
178  // Special cases of affine maps and integer sets
179  /// Returns a zero result affine map with no dimensions or symbols: () -> ().
181  /// Returns a single constant result affine map with 0 dimensions and 0
182  /// symbols. One constant result: () -> (val).
183  AffineMap getConstantAffineMap(int64_t val);
184  // One dimension id identity map: (i) -> (i).
186  // Multi-dimensional identity map: (d0, d1, d2) -> (d0, d1, d2).
187  AffineMap getMultiDimIdentityMap(unsigned rank);
188  // One symbol identity map: ()[s] -> (s).
190 
191  /// Returns a map that shifts its (single) input dimension by 'shift'.
192  /// (d0) -> (d0 + shift)
193  AffineMap getSingleDimShiftAffineMap(int64_t shift);
194 
195  /// Returns an affine map that is a translation (shift) of all result
196  /// expressions in 'map' by 'shift'.
197  /// Eg: input: (d0, d1)[s0] -> (d0, d1 + s0), shift = 2
198  /// returns: (d0, d1)[s0] -> (d0 + 2, d1 + s0 + 2)
199  AffineMap getShiftedAffineMap(AffineMap map, int64_t shift);
200 
201 protected:
203 };
204 
205 /// This class helps build Operations. Operations that are created are
206 /// automatically inserted at an insertion point. The builder is copyable.
207 class OpBuilder : public Builder {
208 public:
209  class InsertPoint;
210  struct Listener;
211 
212  /// Create a builder with the given context.
213  explicit OpBuilder(MLIRContext *ctx, Listener *listener = nullptr)
214  : Builder(ctx), listener(listener) {}
215 
216  /// Create a builder and set the insertion point to the start of the region.
217  explicit OpBuilder(Region *region, Listener *listener = nullptr)
218  : OpBuilder(region->getContext(), listener) {
219  if (!region->empty())
220  setInsertionPointToStart(&region->front());
221  }
222  explicit OpBuilder(Region &region, Listener *listener = nullptr)
223  : OpBuilder(&region, listener) {}
224 
225  /// Create a builder and set insertion point to the given operation, which
226  /// will cause subsequent insertions to go right before it.
227  explicit OpBuilder(Operation *op, Listener *listener = nullptr)
228  : OpBuilder(op->getContext(), listener) {
229  setInsertionPoint(op);
230  }
231 
232  OpBuilder(Block *block, Block::iterator insertPoint,
233  Listener *listener = nullptr)
234  : OpBuilder(block->getParent()->getContext(), listener) {
235  setInsertionPoint(block, insertPoint);
236  }
237 
238  /// Create a builder and set the insertion point to before the first operation
239  /// in the block but still inside the block.
240  static OpBuilder atBlockBegin(Block *block, Listener *listener = nullptr) {
241  return OpBuilder(block, block->begin(), listener);
242  }
243 
244  /// Create a builder and set the insertion point to after the last operation
245  /// in the block but still inside the block.
246  static OpBuilder atBlockEnd(Block *block, Listener *listener = nullptr) {
247  return OpBuilder(block, block->end(), listener);
248  }
249 
250  /// Create a builder and set the insertion point to before the block
251  /// terminator.
253  Listener *listener = nullptr) {
254  auto *terminator = block->getTerminator();
255  assert(terminator != nullptr && "the block has no terminator");
256  return OpBuilder(block, Block::iterator(terminator), listener);
257  }
258 
259  //===--------------------------------------------------------------------===//
260  // Listeners
261  //===--------------------------------------------------------------------===//
262 
263  /// Base class for listeners.
264  struct ListenerBase {
265  /// The kind of listener.
266  enum class Kind {
267  /// OpBuilder::Listener or user-derived class.
268  OpBuilderListener = 0,
269 
270  /// RewriterBase::Listener or user-derived class.
272  };
273 
274  Kind getKind() const { return kind; }
275 
276  protected:
278 
279  private:
280  const Kind kind;
281  };
282 
283  /// This class represents a listener that may be used to hook into various
284  /// actions within an OpBuilder.
285  struct Listener : public ListenerBase {
286  Listener() : ListenerBase(ListenerBase::Kind::OpBuilderListener) {}
287 
288  virtual ~Listener() = default;
289 
290  /// Notify the listener that the specified operation was inserted.
291  ///
292  /// * If the operation was moved, then `previous` is the previous location
293  /// of the op.
294  /// * If the operation was unlinked before it was inserted, then `previous`
295  /// is empty.
296  ///
297  /// Note: Creating an (unlinked) op does not trigger this notification.
298  virtual void notifyOperationInserted(Operation *op, InsertPoint previous) {}
299 
300  /// Notify the listener that the specified block was inserted.
301  ///
302  /// * If the block was moved, then `previous` and `previousIt` are the
303  /// previous location of the block.
304  /// * If the block was unlinked before it was inserted, then `previous`
305  /// is "nullptr".
306  ///
307  /// Note: Creating an (unlinked) block does not trigger this notification.
308  virtual void notifyBlockInserted(Block *block, Region *previous,
309  Region::iterator previousIt) {}
310 
311  protected:
313  };
314 
315  /// Sets the listener of this builder to the one provided.
316  void setListener(Listener *newListener) { listener = newListener; }
317 
318  /// Returns the current listener of this builder, or nullptr if this builder
319  /// doesn't have a listener.
320  Listener *getListener() const { return listener; }
321 
322  //===--------------------------------------------------------------------===//
323  // Insertion Point Management
324  //===--------------------------------------------------------------------===//
325 
326  /// This class represents a saved insertion point.
327  class InsertPoint {
328  public:
329  /// Creates a new insertion point which doesn't point to anything.
330  InsertPoint() = default;
331 
332  /// Creates a new insertion point at the given location.
333  InsertPoint(Block *insertBlock, Block::iterator insertPt)
334  : block(insertBlock), point(insertPt) {}
335 
336  /// Returns true if this insert point is set.
337  bool isSet() const { return (block != nullptr); }
338 
339  Block *getBlock() const { return block; }
340  Block::iterator getPoint() const { return point; }
341 
342  private:
343  Block *block = nullptr;
344  Block::iterator point;
345  };
346 
347  /// RAII guard to reset the insertion point of the builder when destroyed.
349  public:
351  : builder(&builder), ip(builder.saveInsertionPoint()) {}
352 
354  if (builder)
355  builder->restoreInsertionPoint(ip);
356  }
357 
358  InsertionGuard(const InsertionGuard &) = delete;
360 
361  /// Implement the move constructor to clear the builder field of `other`.
362  /// That way it does not restore the insertion point upon destruction as
363  /// that should be done exclusively by the just constructed InsertionGuard.
364  InsertionGuard(InsertionGuard &&other) noexcept
365  : builder(other.builder), ip(other.ip) {
366  other.builder = nullptr;
367  }
368 
370 
371  private:
372  OpBuilder *builder;
374  };
375 
376  /// Reset the insertion point to no location. Creating an operation without a
377  /// set insertion point is an error, but this can still be useful when the
378  /// current insertion point a builder refers to is being removed.
380  this->block = nullptr;
381  insertPoint = Block::iterator();
382  }
383 
384  /// Return a saved insertion point.
387  }
388 
389  /// Restore the insert point to a previously saved point.
391  if (ip.isSet())
392  setInsertionPoint(ip.getBlock(), ip.getPoint());
393  else
395  }
396 
397  /// Set the insertion point to the specified location.
398  void setInsertionPoint(Block *block, Block::iterator insertPoint) {
399  // TODO: check that insertPoint is in this rather than some other block.
400  this->block = block;
401  this->insertPoint = insertPoint;
402  }
403 
404  /// Sets the insertion point to the specified operation, which will cause
405  /// subsequent insertions to go right before it.
408  }
409 
410  /// Sets the insertion point to the node after the specified operation, which
411  /// will cause subsequent insertions to go right after it.
414  }
415 
416  /// Sets the insertion point to the node after the specified value. If value
417  /// has a defining operation, sets the insertion point to the node after such
418  /// defining operation. This will cause subsequent insertions to go right
419  /// after it. Otherwise, value is a BlockArgument. Sets the insertion point to
420  /// the start of its block.
422  if (Operation *op = val.getDefiningOp()) {
424  } else {
425  auto blockArg = llvm::cast<BlockArgument>(val);
426  setInsertionPointToStart(blockArg.getOwner());
427  }
428  }
429 
430  /// Sets the insertion point to the start of the specified block.
432  setInsertionPoint(block, block->begin());
433  }
434 
435  /// Sets the insertion point to the end of the specified block.
437  setInsertionPoint(block, block->end());
438  }
439 
440  /// Return the block the current insertion point belongs to. Note that the
441  /// insertion point is not necessarily the end of the block.
442  Block *getInsertionBlock() const { return block; }
443 
444  /// Returns the current insertion point of the builder.
445  Block::iterator getInsertionPoint() const { return insertPoint; }
446 
447  /// Returns the current block of the builder.
448  Block *getBlock() const { return block; }
449 
450  //===--------------------------------------------------------------------===//
451  // Block Creation
452  //===--------------------------------------------------------------------===//
453 
454  /// Add new block with 'argTypes' arguments and set the insertion point to the
455  /// end of it. The block is inserted at the provided insertion point of
456  /// 'parent'. `locs` contains the locations of the inserted arguments, and
457  /// should match the size of `argTypes`.
458  Block *createBlock(Region *parent, Region::iterator insertPt = {},
459  TypeRange argTypes = {}, ArrayRef<Location> locs = {});
460 
461  /// Add new block with 'argTypes' arguments and set the insertion point to the
462  /// end of it. The block is placed before 'insertBefore'. `locs` contains the
463  /// locations of the inserted arguments, and should match the size of
464  /// `argTypes`.
465  Block *createBlock(Block *insertBefore, TypeRange argTypes = {},
466  ArrayRef<Location> locs = {});
467 
468  //===--------------------------------------------------------------------===//
469  // Operation Creation
470  //===--------------------------------------------------------------------===//
471 
472  /// Insert the given operation at the current insertion point and return it.
473  Operation *insert(Operation *op);
474 
475  /// Creates an operation given the fields represented as an OperationState.
476  Operation *create(const OperationState &state);
477 
478  /// Creates an operation with the given fields.
479  Operation *create(Location loc, StringAttr opName, ValueRange operands,
480  TypeRange types = {},
481  ArrayRef<NamedAttribute> attributes = {},
482  BlockRange successors = {},
483  MutableArrayRef<std::unique_ptr<Region>> regions = {});
484 
485 private:
486  /// Helper for sanity checking preconditions for create* methods below.
487  template <typename OpT>
488  RegisteredOperationName getCheckRegisteredInfo(MLIRContext *ctx) {
489  std::optional<RegisteredOperationName> opName =
490  RegisteredOperationName::lookup(TypeID::get<OpT>(), ctx);
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");
498  }
499  return *opName;
500  }
501 
502 public:
503  /// Create an operation of specific op type at the current insertion point.
504  template <typename OpTy, typename... Args>
505  OpTy create(Location location, Args &&...args) {
506  OperationState state(location,
507  getCheckRegisteredInfo<OpTy>(location.getContext()));
508  OpTy::build(*this, state, std::forward<Args>(args)...);
509  auto *op = create(state);
510  auto result = dyn_cast<OpTy>(op);
511  assert(result && "builder didn't return the right type");
512  return result;
513  }
514 
515  /// Create an operation of specific op type at the current insertion point,
516  /// and immediately try to fold it. This functions populates 'results' with
517  /// the results of the operation.
518  template <typename OpTy, typename... Args>
520  Args &&...args) {
521  // Create the operation without using 'create' as we want to control when
522  // the listener is notified.
523  OperationState state(location,
524  getCheckRegisteredInfo<OpTy>(location.getContext()));
525  OpTy::build(*this, state, std::forward<Args>(args)...);
526  Operation *op = Operation::create(state);
527  if (block)
528  block->getOperations().insert(insertPoint, op);
529 
530  // Attempt to fold the operation.
531  if (succeeded(tryFold(op, results)) && !results.empty()) {
532  // Erase the operation, if the fold removed the need for this operation.
533  // Note: The fold already populated the results in this case.
534  op->erase();
535  return;
536  }
537 
538  ResultRange opResults = op->getResults();
539  results.assign(opResults.begin(), opResults.end());
540  if (block && listener)
541  listener->notifyOperationInserted(op, /*previous=*/{});
542  }
543 
544  /// Overload to create or fold a single result operation.
545  template <typename OpTy, typename... Args>
546  std::enable_if_t<OpTy::template hasTrait<OpTrait::OneResult>(), Value>
547  createOrFold(Location location, Args &&...args) {
548  SmallVector<Value, 1> results;
549  createOrFold<OpTy>(results, location, std::forward<Args>(args)...);
550  return results.front();
551  }
552 
553  /// Overload to create or fold a zero result operation.
554  template <typename OpTy, typename... Args>
555  std::enable_if_t<OpTy::template hasTrait<OpTrait::ZeroResults>(), OpTy>
556  createOrFold(Location location, Args &&...args) {
557  auto op = OpTy::create(*this, location, std::forward<Args>(args)...);
558  SmallVector<Value, 0> unused;
559  (void)tryFold(op.getOperation(), unused);
560 
561  // Folding cannot remove a zero-result operation, so for convenience we
562  // continue to return it.
563  return op;
564  }
565 
566  /// Attempts to fold the given operation and places new results within
567  /// `results`. Returns success if the operation was folded, failure otherwise.
568  /// If the fold was in-place, `results` will not be filled. Optionally, newly
569  /// materialized constant operations can be returned to the caller.
570  ///
571  /// Note: This function does not erase the operation on a successful fold.
572  LogicalResult
574  SmallVectorImpl<Operation *> *materializedConstants = nullptr);
575 
576  /// Creates a deep copy of the specified operation, remapping any operands
577  /// that use values outside of the operation using the map that is provided
578  /// ( leaving them alone if no entry is present). Replaces references to
579  /// cloned sub-operations to the corresponding operation that is copied,
580  /// and adds those mappings to the map.
581  Operation *clone(Operation &op, IRMapping &mapper);
582  Operation *clone(Operation &op);
583 
584  /// Creates a deep copy of this operation but keep the operation regions
585  /// empty. Operands are remapped using `mapper` (if present), and `mapper` is
586  /// updated to contain the results.
588  return insert(op.cloneWithoutRegions(mapper));
589  }
591  return insert(op.cloneWithoutRegions());
592  }
593  template <typename OpT>
594  OpT cloneWithoutRegions(OpT op) {
595  return cast<OpT>(cloneWithoutRegions(*op.getOperation()));
596  }
597 
598  /// Clone the blocks that belong to "region" before the given position in
599  /// another region "parent". The two regions must be different. The caller is
600  /// responsible for creating or updating the operation transferring flow of
601  /// control to the region and passing it the correct block arguments.
602  void cloneRegionBefore(Region &region, Region &parent,
603  Region::iterator before, IRMapping &mapping);
604  void cloneRegionBefore(Region &region, Region &parent,
605  Region::iterator before);
606  void cloneRegionBefore(Region &region, Block *before);
607 
608 protected:
609  /// The optional listener for events of this builder.
611 
612 private:
613  /// The current block this builder is inserting into.
614  Block *block = nullptr;
615  /// The insertion point within the block that this builder is inserting
616  /// before.
617  Block::iterator insertPoint;
618 };
619 
620 /// ImplicitLocOpBuilder maintains a 'current location', allowing use of the
621 /// create<> method without specifying the location. It is otherwise the same
622 /// as OpBuilder.
624 public:
625  /// OpBuilder has a bunch of convenience constructors - we support them all
626  /// with the additional Location.
627  template <typename... T>
628  ImplicitLocOpBuilder(Location loc, T &&...operands)
629  : OpBuilder(std::forward<T>(operands)...), curLoc(loc) {}
630 
631  /// Create a builder and set the insertion point to before the first operation
632  /// in the block but still inside the block.
634  Listener *listener = nullptr) {
635  return ImplicitLocOpBuilder(loc, block, block->begin(), listener);
636  }
637 
638  /// Create a builder and set the insertion point to after the last operation
639  /// in the block but still inside the block.
641  Listener *listener = nullptr) {
642  return ImplicitLocOpBuilder(loc, block, block->end(), listener);
643  }
644 
645  /// Create a builder and set the insertion point to before the block
646  /// terminator.
648  Listener *listener = nullptr) {
649  auto *terminator = block->getTerminator();
650  assert(terminator != nullptr && "the block has no terminator");
651  return ImplicitLocOpBuilder(loc, block, Block::iterator(terminator),
652  listener);
653  }
654 
655  /// Accessors for the implied location.
656  Location getLoc() const { return curLoc; }
657  void setLoc(Location loc) { curLoc = loc; }
658 
659  // We allow clients to use the explicit-loc version of create as well.
660  using OpBuilder::create;
662 
663  /// Create an operation of specific op type at the current insertion point and
664  /// location.
665  template <typename OpTy, typename... Args>
666  OpTy create(Args &&...args) {
667  return OpTy::create(*this, curLoc, std::forward<Args>(args)...);
668  }
669 
670  /// Create an operation of specific op type at the current insertion point,
671  /// and immediately try to fold it. This functions populates 'results' with
672  /// the results after folding the operation.
673  template <typename OpTy, typename... Args>
674  void createOrFold(llvm::SmallVectorImpl<Value> &results, Args &&...args) {
675  OpBuilder::createOrFold<OpTy>(results, curLoc, std::forward<Args>(args)...);
676  }
677 
678  /// Overload to create or fold a single result operation.
679  template <typename OpTy, typename... Args>
680  std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::OneResult>(), Value>
681  createOrFold(Args &&...args) {
682  return OpBuilder::createOrFold<OpTy>(curLoc, std::forward<Args>(args)...);
683  }
684 
685  /// Overload to create or fold a zero result operation.
686  template <typename OpTy, typename... Args>
687  std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::ZeroResults>(), OpTy>
688  createOrFold(Args &&...args) {
689  return OpBuilder::createOrFold<OpTy>(curLoc, std::forward<Args>(args)...);
690  }
691 
692  /// This builder can also be used to emit diagnostics to the current location.
694  emitError(const llvm::Twine &message = llvm::Twine()) {
695  return mlir::emitError(curLoc, message);
696  }
698  emitWarning(const llvm::Twine &message = llvm::Twine()) {
699  return mlir::emitWarning(curLoc, message);
700  }
702  emitRemark(const llvm::Twine &message = llvm::Twine()) {
703  return mlir::emitRemark(curLoc, message);
704  }
705 
706 private:
707  Location curLoc;
708 };
709 
710 } // namespace mlir
711 
712 #endif
union mlir::linalg::@1241::ArityGroupAndKind::Kind kind
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:33
OpListType::iterator iterator
Definition: Block.h:140
Operation * getTerminator()
Get the terminator operation of this block.
Definition: Block.cpp:244
OpListType & getOperations()
Definition: Block.h:137
iterator end()
Definition: Block.h:144
iterator begin()
Definition: Block.h:143
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,...
Definition: Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:107
AffineMap getSingleDimShiftAffineMap(int64_t shift)
Returns a map that shifts its (single) input dimension by 'shift'.
Definition: Builders.cpp:400
IntegerType getI16Type()
Definition: Builders.cpp:60
UnitAttr getUnitAttr()
Definition: Builders.cpp:97
ArrayAttr getIndexArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:286
DenseF64ArrayAttr getDenseF64ArrayAttr(ArrayRef< double > values)
Definition: Builders.cpp:174
IntegerType getI2Type()
Definition: Builders.cpp:54
FloatType getF80Type()
Definition: Builders.cpp:46
FloatType getF128Type()
Definition: Builders.cpp:48
DenseI8ArrayAttr getDenseI8ArrayAttr(ArrayRef< int8_t > values)
Definition: Builders.cpp:154
IntegerAttr getI32IntegerAttr(int32_t value)
Definition: Builders.cpp:199
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:162
DenseIntElementsAttr getBoolVectorAttr(ArrayRef< bool > values)
Vector-typed DenseIntElementsAttr getters. values must not be empty.
Definition: Builders.cpp:115
FloatType getF32Type()
Definition: Builders.cpp:42
FloatType getTF32Type()
Definition: Builders.cpp:40
TupleType getTupleType(TypeRange elementTypes)
Definition: Builders.cpp:83
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition: Builders.cpp:227
FloatAttr getF64FloatAttr(double value)
Definition: Builders.cpp:241
AffineMap getShiftedAffineMap(AffineMap map, int64_t shift)
Returns an affine map that is a translation (shift) of all result expressions in 'map' by 'shift'.
Definition: Builders.cpp:406
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:275
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:166
FloatAttr getF16FloatAttr(float value)
Definition: Builders.cpp:249
AffineMap getDimIdentityMap()
Definition: Builders.cpp:382
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition: Builders.cpp:386
IntegerAttr getI16IntegerAttr(int16_t value)
Definition: Builders.cpp:216
DenseI16ArrayAttr getDenseI16ArrayAttr(ArrayRef< int16_t > values)
Definition: Builders.cpp:158
AffineExpr getAffineSymbolExpr(unsigned position)
Definition: Builders.cpp:367
DenseFPElementsAttr getF32VectorAttr(ArrayRef< float > values)
Definition: Builders.cpp:139
FloatAttr getFloatAttr(Type type, double value)
Definition: Builders.cpp:253
AffineExpr getAffineConstantExpr(int64_t constant)
Definition: Builders.cpp:371
DenseIntElementsAttr getI32TensorAttr(ArrayRef< int32_t > values)
Tensor-typed DenseIntElementsAttr getters.
Definition: Builders.cpp:178
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition: Builders.cpp:75
IntegerType getI64Type()
Definition: Builders.cpp:64
IntegerType getI32Type()
Definition: Builders.cpp:62
IntegerAttr getI64IntegerAttr(int64_t value)
Definition: Builders.cpp:111
IntegerType getIntegerType(unsigned width)
Definition: Builders.cpp:66
NoneType getNoneType()
Definition: Builders.cpp:87
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:185
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition: Builders.h:91
BoolAttr getBoolAttr(bool value)
Definition: Builders.cpp:99
IntegerType getI4Type()
Definition: Builders.cpp:56
StringAttr getStringAttr(const Twine &bytes)
Definition: Builders.cpp:261
MLIRContext * context
Definition: Builders.h:202
Builder(MLIRContext *context)
Definition: Builders.h:53
AffineMap getEmptyAffineMap()
Returns a zero result affine map with no dimensions or symbols: () -> ().
Definition: Builders.cpp:375
Builder(Operation *op)
Definition: Builders.h:54
IntegerAttr getSI32IntegerAttr(int32_t value)
Signed and unsigned integer attribute getters.
Definition: Builders.cpp:206
GraphType getGraphType(TypeRange inputs, TypeRange results)
Definition: Builders.cpp:79
TypedAttr getZeroAttr(Type type)
Definition: Builders.cpp:323
FloatType getF16Type()
Definition: Builders.cpp:38
Location getFusedLoc(ArrayRef< Location > locs, Attribute metadata=Attribute())
Definition: Builders.cpp:26
FloatType getBF16Type()
Definition: Builders.cpp:36
AffineExpr getAffineDimExpr(unsigned position)
Definition: Builders.cpp:363
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:192
AffineMap getConstantAffineMap(int64_t val)
Returns a single constant result affine map with 0 dimensions and 0 symbols.
Definition: Builders.cpp:377
MLIRContext * getContext() const
Definition: Builders.h:56
ArrayAttr getTypeArrayAttr(TypeRange values)
Definition: Builders.cpp:311
FloatType getF8E8M0Type()
Definition: Builders.cpp:34
DenseIntElementsAttr getI32VectorAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:121
DenseF32ArrayAttr getDenseF32ArrayAttr(ArrayRef< float > values)
Definition: Builders.cpp:170
DenseIntElementsAttr getI64VectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:127
AffineMap getSymbolIdentityMap()
Definition: Builders.cpp:395
ArrayAttr getF64ArrayAttr(ArrayRef< double > values)
Definition: Builders.cpp:299
IntegerType getI1Type()
Definition: Builders.cpp:52
DenseFPElementsAttr getF64VectorAttr(ArrayRef< double > values)
Definition: Builders.cpp:144
Location getUnknownLoc()
Definition: Builders.cpp:24
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition: Builders.cpp:265
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
Definition: Builders.cpp:150
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:280
IndexType getIndexType()
Definition: Builders.cpp:50
IntegerType getI8Type()
Definition: Builders.cpp:58
FloatAttr getF32FloatAttr(float value)
Definition: Builders.cpp:245
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Definition: Builders.cpp:103
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition: Builders.cpp:93
IntegerAttr getUI32IntegerAttr(uint32_t value)
Definition: Builders.cpp:211
IntegerAttr getI8IntegerAttr(int8_t value)
Definition: Builders.cpp:220
ArrayAttr getF32ArrayAttr(ArrayRef< float > values)
Definition: Builders.cpp:293
FloatType getF64Type()
Definition: Builders.cpp:44
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
Definition: Builders.cpp:269
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
Definition: Builders.cpp:305
DenseIntElementsAttr getIndexVectorAttr(ArrayRef< int64_t > values)
Definition: Builders.cpp:133
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition: Builders.cpp:317
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition: Builders.h:98
TypedAttr getOneAttr(Type type)
Definition: Builders.cpp:341
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.
Definition: IRMapping.h:26
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition: Builders.h:623
void setLoc(Location loc)
Definition: Builders.h:657
Location getLoc() const
Accessors for the implied location.
Definition: Builders.h:656
mlir::InFlightDiagnostic emitWarning(const llvm::Twine &message=llvm::Twine())
Definition: Builders.h:698
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::ZeroResults >), OpTy > createOrFold(Args &&...args)
Overload to create or fold a zero result operation.
Definition: Builders.h:688
static ImplicitLocOpBuilder atBlockTerminator(Location loc, Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition: Builders.h:647
ImplicitLocOpBuilder(Location loc, T &&...operands)
OpBuilder has a bunch of convenience constructors - we support them all with the additional Location.
Definition: Builders.h:628
std::enable_if_t< OpTy::template hasTrait< mlir::OpTrait::OneResult >), Value > createOrFold(Args &&...args)
Overload to create or fold a single result operation.
Definition: Builders.h:681
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...
Definition: Builders.h:633
mlir::InFlightDiagnostic emitError(const llvm::Twine &message=llvm::Twine())
This builder can also be used to emit diagnostics to the current location.
Definition: Builders.h:694
mlir::InFlightDiagnostic emitRemark(const llvm::Twine &message=llvm::Twine())
Definition: Builders.h:702
OpTy create(Args &&...args)
Create an operation of specific op type at the current insertion point and location.
Definition: Builders.h:666
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...
Definition: Builders.h:674
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...
Definition: Builders.h:640
This class represents a diagnostic that is inflight and set to be reported.
Definition: Diagnostics.h:314
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext * getContext() const
Return the context this location is uniqued in.
Definition: Location.h:86
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:164
This class represents a saved insertion point.
Definition: Builders.h:327
InsertPoint()=default
Creates a new insertion point which doesn't point to anything.
Block::iterator getPoint() const
Definition: Builders.h:340
bool isSet() const
Returns true if this insert point is set.
Definition: Builders.h:337
InsertPoint(Block *insertBlock, Block::iterator insertPt)
Creates a new insertion point at the given location.
Definition: Builders.h:333
Block * getBlock() const
Definition: Builders.h:339
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:348
InsertionGuard(OpBuilder &builder)
Definition: Builders.h:350
InsertionGuard(InsertionGuard &&other) noexcept
Implement the move constructor to clear the builder field of other.
Definition: Builders.h:364
InsertionGuard(const InsertionGuard &)=delete
InsertionGuard & operator=(InsertionGuard &&other)=delete
InsertionGuard & operator=(const InsertionGuard &)=delete
This class helps build Operations.
Definition: Builders.h:207
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition: Builders.h:385
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...
Definition: Builders.h:240
OpBuilder(Region *region, Listener *listener=nullptr)
Create a builder and set the insertion point to the start of the region.
Definition: Builders.h:217
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition: Builders.h:445
Operation * cloneWithoutRegions(Operation &op)
Definition: Builders.h:590
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.
Definition: Builders.cpp:429
OpT cloneWithoutRegions(OpT op)
Definition: Builders.h:594
OpBuilder(MLIRContext *ctx, Listener *listener=nullptr)
Create a builder with the given context.
Definition: Builders.h:213
void clearInsertionPoint()
Reset the insertion point to no location.
Definition: Builders.h:379
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...
Definition: Builders.h:246
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition: Builders.cpp:552
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
Definition: Builders.h:316
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:431
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:398
void setInsertionPoint(Operation *op)
Sets the insertion point to the specified operation, which will cause subsequent insertions to go rig...
Definition: Builders.h:406
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition: Builders.h:252
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition: Builders.h:436
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition: Builders.h:390
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition: Builders.h:320
OpBuilder(Region &region, Listener *listener=nullptr)
Definition: Builders.h:222
void cloneRegionBefore(Region &region, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
Definition: Builders.cpp:579
OpBuilder(Block *block, Block::iterator insertPoint, Listener *listener=nullptr)
Definition: Builders.h:232
OpTy create(Location location, Args &&...args)
Create an operation of specific op type at the current insertion point.
Definition: Builders.h:505
OpBuilder(Operation *op, Listener *listener=nullptr)
Create a builder and set insertion point to the given operation, which will cause subsequent insertio...
Definition: Builders.h:227
LogicalResult tryFold(Operation *op, SmallVectorImpl< Value > &results, SmallVectorImpl< Operation * > *materializedConstants=nullptr)
Attempts to fold the given operation and places new results within results.
Definition: Builders.cpp:472
Listener * listener
The optional listener for events of this builder.
Definition: Builders.h:610
std::enable_if_t< OpTy::template hasTrait< OpTrait::ZeroResults >), OpTy > createOrFold(Location location, Args &&...args)
Overload to create or fold a zero result operation.
Definition: Builders.h:556
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...
Definition: Builders.h:519
std::enable_if_t< OpTy::template hasTrait< OpTrait::OneResult >), Value > createOrFold(Location location, Args &&...args)
Overload to create or fold a single result operation.
Definition: Builders.h:547
Block * getBlock() const
Returns the current block of the builder.
Definition: Builders.h:448
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition: Builders.h:421
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:456
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:412
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Definition: Builders.cpp:420
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Definition: Builders.h:587
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition: Builders.h:442
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
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.
Definition: Operation.cpp:66
Block * getBlock()
Returns the operation block that contains this operation.
Definition: Operation.h:213
Operation * cloneWithoutRegions(IRMapping &mapper)
Create a partial copy of this operation without traversing into attached regions.
Definition: Operation.cpp:704
result_range getResults()
Definition: Operation.h:415
void erase()
Remove this operation from its parent block and delete it.
Definition: Operation.cpp:538
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
bool empty()
Definition: Region.h:60
Block & front()
Definition: Region.h:65
BlockListType::iterator iterator
Definition: Region.h:52
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.
Definition: ValueRange.h:247
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:37
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:18
Base class for DenseArrayAttr that is instantiated and specialized for each supported element type be...
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
InFlightDiagnostic emitRemark(Location loc)
Utility method to emit a remark message using this location.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Base class for listeners.
Definition: Builders.h:264
Kind
The kind of listener.
Definition: Builders.h:266
@ 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.
Definition: Builders.h:285
virtual void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt)
Notify the listener that the specified block was inserted.
Definition: Builders.h:308
virtual ~Listener()=default
virtual void notifyOperationInserted(Operation *op, InsertPoint previous)
Notify the listener that the specified operation was inserted.
Definition: Builders.h:298
This represents an operation in an abstracted form, suitable for use with the builder APIs.