blob: c677f3815e9f545cf395461bf1a888dc6f21e9d0 [file] [log] [blame]
Chris Lattner158e0a3e2018-07-08 20:51:38 -07001//===- Builders.h - Helpers for constructing MLIR Classes -------*- C++ -*-===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17
18#ifndef MLIR_IR_BUILDERS_H
19#define MLIR_IR_BUILDERS_H
20
21#include "mlir/IR/CFGFunction.h"
Tatiana Shpeisman565b9642018-07-16 11:47:09 -070022#include "mlir/IR/MLFunction.h"
23#include "mlir/IR/Statements.h"
Chris Lattner158e0a3e2018-07-08 20:51:38 -070024
25namespace mlir {
26class MLIRContext;
27class Module;
Chris Lattnerfc647d52018-08-27 21:05:16 -070028class UnknownLoc;
29class UniquedFilename;
30class FileLineColLoc;
Chris Lattner158e0a3e2018-07-08 20:51:38 -070031class Type;
32class PrimitiveType;
33class IntegerType;
34class FunctionType;
35class VectorType;
36class RankedTensorType;
37class UnrankedTensorType;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070038class BoolAttr;
39class IntegerAttr;
40class FloatAttr;
41class StringAttr;
James Molloyf0d2f442018-08-03 01:54:46 -070042class TypeAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070043class ArrayAttr;
Chris Lattner4613d9e2018-08-19 21:17:22 -070044class FunctionAttr;
MLIR Teamb61885d2018-07-18 16:29:21 -070045class AffineMapAttr;
Chris Lattner1ac20cb2018-07-10 10:59:53 -070046class AffineMap;
47class AffineExpr;
48class AffineConstantExpr;
49class AffineDimExpr;
50class AffineSymbolExpr;
Chris Lattner158e0a3e2018-07-08 20:51:38 -070051
52/// This class is a general helper class for creating context-global objects
53/// like types, attributes, and affine expressions.
54class Builder {
55public:
56 explicit Builder(MLIRContext *context) : context(context) {}
57 explicit Builder(Module *module);
58
59 MLIRContext *getContext() const { return context; }
60
Chris Lattner1ac20cb2018-07-10 10:59:53 -070061 Identifier getIdentifier(StringRef str);
62 Module *createModule();
63
Chris Lattnerfc647d52018-08-27 21:05:16 -070064 // Locations.
65 UnknownLoc *getUnknownLoc();
66 UniquedFilename getUniquedFilename(StringRef filename);
67 FileLineColLoc *getFileLineColLoc(UniquedFilename filename, unsigned line,
68 unsigned column);
69
Chris Lattner158e0a3e2018-07-08 20:51:38 -070070 // Types.
Chris Lattnerc3251192018-07-27 13:09:58 -070071 FloatType *getBF16Type();
72 FloatType *getF16Type();
73 FloatType *getF32Type();
74 FloatType *getF64Type();
75
76 OtherType *getAffineIntType();
77 OtherType *getTFControlType();
James Molloy72b0cbe2018-08-01 12:55:27 -070078 OtherType *getTFStringType();
Chris Lattner158e0a3e2018-07-08 20:51:38 -070079 IntegerType *getIntegerType(unsigned width);
80 FunctionType *getFunctionType(ArrayRef<Type *> inputs,
81 ArrayRef<Type *> results);
Jacques Pienaarc03c6952018-08-10 11:56:47 -070082 MemRefType *getMemRefType(ArrayRef<int> shape, Type *elementType,
83 ArrayRef<AffineMap *> affineMapComposition = {},
84 unsigned memorySpace = 0);
Chris Lattner158e0a3e2018-07-08 20:51:38 -070085 VectorType *getVectorType(ArrayRef<unsigned> shape, Type *elementType);
86 RankedTensorType *getTensorType(ArrayRef<int> shape, Type *elementType);
87 UnrankedTensorType *getTensorType(Type *elementType);
88
Chris Lattner1ac20cb2018-07-10 10:59:53 -070089 // Attributes.
90 BoolAttr *getBoolAttr(bool value);
91 IntegerAttr *getIntegerAttr(int64_t value);
92 FloatAttr *getFloatAttr(double value);
93 StringAttr *getStringAttr(StringRef bytes);
94 ArrayAttr *getArrayAttr(ArrayRef<Attribute *> value);
MLIR Teamb61885d2018-07-18 16:29:21 -070095 AffineMapAttr *getAffineMapAttr(AffineMap *value);
James Molloyf0d2f442018-08-03 01:54:46 -070096 TypeAttr *getTypeAttr(Type *type);
Chris Lattner1aa46322018-08-21 17:55:22 -070097 FunctionAttr *getFunctionAttr(const Function *value);
Chris Lattner1ac20cb2018-07-10 10:59:53 -070098
99 // Affine Expressions and Affine Map.
100 AffineMap *getAffineMap(unsigned dimCount, unsigned symbolCount,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700101 ArrayRef<AffineExpr *> results,
102 ArrayRef<AffineExpr *> rangeSizes);
Chris Lattner1ac20cb2018-07-10 10:59:53 -0700103 AffineDimExpr *getDimExpr(unsigned position);
104 AffineSymbolExpr *getSymbolExpr(unsigned position);
105 AffineConstantExpr *getConstantExpr(int64_t constant);
106 AffineExpr *getAddExpr(AffineExpr *lhs, AffineExpr *rhs);
107 AffineExpr *getSubExpr(AffineExpr *lhs, AffineExpr *rhs);
108 AffineExpr *getMulExpr(AffineExpr *lhs, AffineExpr *rhs);
109 AffineExpr *getModExpr(AffineExpr *lhs, AffineExpr *rhs);
110 AffineExpr *getFloorDivExpr(AffineExpr *lhs, AffineExpr *rhs);
111 AffineExpr *getCeilDivExpr(AffineExpr *lhs, AffineExpr *rhs);
112
Uday Bondhugulabc535622018-08-07 14:24:38 -0700113 // Integer set.
114 IntegerSet *getIntegerSet(unsigned dimCount, unsigned symbolCount,
115 ArrayRef<AffineExpr *> constraints,
116 ArrayRef<bool> isEq);
117
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700118 // Special cases of affine maps and integer sets
119 // One constant result: () -> (val).
120 AffineMap *getConstantMap(int64_t val);
121 // One dimension id identity map: (i) -> (i).
122 AffineMap *getDimIdentityMap();
123 // One symbol identity map: ()[s] -> (s).
124 AffineMap *getSymbolIdentityMap();
125
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700126 // TODO: Helpers for affine map/exprs, etc.
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700127protected:
128 MLIRContext *context;
129};
130
131/// This class helps build a CFGFunction. Instructions that are created are
132/// automatically inserted at an insertion point or added to the current basic
133/// block.
134class CFGFuncBuilder : public Builder {
135public:
Chris Lattner8174f3a2018-07-29 16:45:23 -0700136 CFGFuncBuilder(BasicBlock *block, BasicBlock::iterator insertPoint)
137 : Builder(block->getFunction()->getContext()),
138 function(block->getFunction()) {
139 setInsertionPoint(block, insertPoint);
140 }
141
142 CFGFuncBuilder(OperationInst *insertBefore)
143 : CFGFuncBuilder(insertBefore->getBlock(),
144 BasicBlock::iterator(insertBefore)) {}
145
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700146 CFGFuncBuilder(BasicBlock *block)
147 : Builder(block->getFunction()->getContext()),
148 function(block->getFunction()) {
149 setInsertionPoint(block);
150 }
Chris Lattner8174f3a2018-07-29 16:45:23 -0700151
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700152 CFGFuncBuilder(CFGFunction *function)
153 : Builder(function->getContext()), function(function) {}
154
155 /// Reset the insertion point to no location. Creating an operation without a
156 /// set insertion point is an error, but this can still be useful when the
157 /// current insertion point a builder refers to is being removed.
158 void clearInsertionPoint() {
159 this->block = nullptr;
160 insertPoint = BasicBlock::iterator();
161 }
162
Chris Lattner8174f3a2018-07-29 16:45:23 -0700163 /// Set the insertion point to the specified location.
164 void setInsertionPoint(BasicBlock *block, BasicBlock::iterator insertPoint) {
165 assert(block->getFunction() == function &&
166 "can't move to a different function");
167 this->block = block;
168 this->insertPoint = insertPoint;
169 }
170
171 /// Set the insertion point to the specified operation.
172 void setInsertionPoint(OperationInst *inst) {
173 setInsertionPoint(inst->getBlock(), BasicBlock::iterator(inst));
174 }
175
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700176 /// Set the insertion point to the end of the specified block.
177 void setInsertionPoint(BasicBlock *block) {
Chris Lattner8174f3a2018-07-29 16:45:23 -0700178 setInsertionPoint(block, block->end());
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700179 }
180
Chris Lattner992a1272018-08-07 12:02:37 -0700181 void insert(OperationInst *opInst) {
182 block->getOperations().insert(insertPoint, opInst);
183 }
184
Chris Lattner8a9310a2018-08-24 21:13:19 -0700185 /// Add new basic block and set the insertion point to the end of it. If an
186 /// 'insertBefore' basic block is passed, the block will be placed before the
187 /// specified block. If not, the block will be appended to the end of the
188 /// current function.
189 BasicBlock *createBlock(BasicBlock *insertBefore = nullptr);
Tatiana Shpeisman6708b452018-07-24 10:15:13 -0700190
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700191 /// Create an operation given the fields represented as an OperationState.
192 OperationInst *createOperation(const OperationState &state);
193
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700194 /// Create operation of specific op type at the current insertion point.
195 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700196 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700197 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700198 OpTy::build(this, &state, args...);
199 auto *inst = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700200 auto result = inst->template getAs<OpTy>();
201 assert(result && "Builder didn't return the right type");
202 return result;
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700203 }
204
Uday Bondhugula15984952018-08-01 22:36:12 -0700205 OperationInst *cloneOperation(const OperationInst &srcOpInst) {
206 auto *op = srcOpInst.clone();
Chris Lattner992a1272018-08-07 12:02:37 -0700207 insert(op);
Uday Bondhugula15984952018-08-01 22:36:12 -0700208 return op;
209 }
210
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700211 // Terminators.
212
Chris Lattnerfc647d52018-08-27 21:05:16 -0700213 ReturnInst *createReturn(Location *location, ArrayRef<CFGValue *> operands) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700214 return insertTerminator(ReturnInst::create(location, operands));
Chris Lattner40746442018-07-21 14:32:09 -0700215 }
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700216
Chris Lattnerfc647d52018-08-27 21:05:16 -0700217 BranchInst *createBranch(Location *location, BasicBlock *dest,
Chris Lattner8a9310a2018-08-24 21:13:19 -0700218 ArrayRef<CFGValue *> operands = {}) {
219 return insertTerminator(BranchInst::create(location, dest, operands));
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700220 }
221
Chris Lattnerfc647d52018-08-27 21:05:16 -0700222 CondBranchInst *createCondBranch(Location *location, CFGValue *condition,
Chris Lattner091a6b52018-08-23 14:58:27 -0700223 BasicBlock *trueDest,
224 BasicBlock *falseDest) {
James Molloy4f788372018-07-24 15:01:27 -0700225 return insertTerminator(
Chris Lattner1628fa02018-08-23 14:32:25 -0700226 CondBranchInst::create(location, condition, trueDest, falseDest));
James Molloy4f788372018-07-24 15:01:27 -0700227 }
228
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700229private:
230 template <typename T>
231 T *insertTerminator(T *term) {
232 block->setTerminator(term);
233 return term;
234 }
235
236 CFGFunction *function;
237 BasicBlock *block = nullptr;
238 BasicBlock::iterator insertPoint;
239};
240
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700241/// This class helps build an MLFunction. Statements that are created are
242/// automatically inserted at an insertion point or added to the current
243/// statement block.
244class MLFuncBuilder : public Builder {
245public:
Chris Lattnere787b322018-08-08 11:14:57 -0700246 /// Create ML function builder and set insertion point to the given statement,
247 /// which will cause subsequent insertions to go right before it.
248 MLFuncBuilder(Statement *stmt)
249 // TODO: Eliminate findFunction from this.
250 : Builder(stmt->findFunction()->getContext()) {
251 setInsertionPoint(stmt);
252 }
253
254 MLFuncBuilder(StmtBlock *block, StmtBlock::iterator insertPoint)
255 // TODO: Eliminate findFunction from this.
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700256 : Builder(block->findFunction()->getContext()) {
Chris Lattnere787b322018-08-08 11:14:57 -0700257 setInsertionPoint(block, insertPoint);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700258 }
259
260 /// Reset the insertion point to no location. Creating an operation without a
261 /// set insertion point is an error, but this can still be useful when the
262 /// current insertion point a builder refers to is being removed.
263 void clearInsertionPoint() {
264 this->block = nullptr;
265 insertPoint = StmtBlock::iterator();
266 }
267
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700268 /// Set the insertion point to the specified location.
269 /// Unlike CFGFuncBuilder, MLFuncBuilder allows to set insertion
270 /// point to a different function.
271 void setInsertionPoint(StmtBlock *block, StmtBlock::iterator insertPoint) {
272 // TODO: check that insertPoint is in this rather than some other block.
273 this->block = block;
274 this->insertPoint = insertPoint;
275 }
276
Uday Bondhugula67701712018-08-21 16:01:23 -0700277 /// Set the insertion point to the specified operation, which will cause
278 /// subsequent insertions to go right before it.
Chris Lattnere787b322018-08-08 11:14:57 -0700279 void setInsertionPoint(Statement *stmt) {
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700280 setInsertionPoint(stmt->getBlock(), StmtBlock::iterator(stmt));
281 }
282
Chris Lattnere787b322018-08-08 11:14:57 -0700283 /// Set the insertion point to the start of the specified block.
284 void setInsertionPointToStart(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700285 setInsertionPoint(block, block->begin());
Uday Bondhugula15984952018-08-01 22:36:12 -0700286 }
287
Chris Lattnere787b322018-08-08 11:14:57 -0700288 /// Set the insertion point to the end of the specified block.
289 void setInsertionPointToEnd(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700290 setInsertionPoint(block, block->end());
Chris Lattnere787b322018-08-08 11:14:57 -0700291 }
292
Uday Bondhugula84b80952018-08-03 13:22:26 -0700293 /// Get the current insertion point of the builder.
294 StmtBlock::iterator getInsertionPoint() const { return insertPoint; }
295
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700296 /// Create an operation given the fields represented as an OperationState.
297 OperationStmt *createOperation(const OperationState &state);
298
Chris Lattner992a1272018-08-07 12:02:37 -0700299 /// Create operation of specific op type at the current insertion point.
Jacques Pienaarac86d102018-08-03 08:16:37 -0700300 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700301 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700302 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700303 OpTy::build(this, &state, args...);
304 auto *stmt = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700305 auto result = stmt->template getAs<OpTy>();
306 assert(result && "Builder didn't return the right type");
307 return result;
Jacques Pienaarac86d102018-08-03 08:16:37 -0700308 }
309
Chris Lattnere787b322018-08-08 11:14:57 -0700310 /// Create a deep copy of the specified statement, remapping any operands that
311 /// use values outside of the statement using the map that is provided (
312 /// leaving them alone if no entry is present). Replaces references to cloned
313 /// sub-statements to the corresponding statement that is copied, and adds
314 /// those mappings to the map.
315 Statement *clone(const Statement &stmt,
316 OperationStmt::OperandMapTy &operandMapping) {
317 Statement *cloneStmt = stmt.clone(operandMapping, getContext());
Uday Bondhugula134154e2018-08-06 18:40:34 -0700318 block->getStatements().insert(insertPoint, cloneStmt);
319 return cloneStmt;
Uday Bondhugula84b80952018-08-03 13:22:26 -0700320 }
321
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700322 // Create for statement. When step is not specified, it is set to 1.
Chris Lattnerfc647d52018-08-27 21:05:16 -0700323 ForStmt *createFor(Location *location, ArrayRef<MLValue *> lbOperands,
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700324 AffineMap *lbMap, ArrayRef<MLValue *> ubOperands,
325 AffineMap *ubMap, int64_t step = 1);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700326
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700327 /// Create if statement.
328 IfStmt *createIf(Location *location, ArrayRef<MLValue *> operands,
329 IntegerSet *set);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700330
331private:
332 StmtBlock *block = nullptr;
333 StmtBlock::iterator insertPoint;
334};
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700335
336} // namespace mlir
337
338#endif