blob: cb4f4f58b8623c7ead4801e6d8efe4176744f3be [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 Lattner7879f842018-09-02 22:01:45 -0700194 /// Create operation of specific op type at the current insertion point
195 /// without verifying to see if it is valid.
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700196 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700197 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700198 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700199 OpTy::build(this, &state, args...);
200 auto *inst = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700201 auto result = inst->template getAs<OpTy>();
202 assert(result && "Builder didn't return the right type");
203 return result;
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700204 }
205
Chris Lattner7879f842018-09-02 22:01:45 -0700206 /// Create operation of specific op type at the current insertion point. If
207 /// the result is an invalid op (the verifier hook fails), emit a the
208 /// specified error message and return null.
209 template <typename OpTy, typename... Args>
210 OpPointer<OpTy> createChecked(const Twine &message, Location *location,
211 Args... args) {
212 OperationState state(getContext(), location, OpTy::getOperationName());
213 OpTy::build(this, &state, args...);
214 auto *inst = createOperation(state);
215 auto result = inst->template getAs<OpTy>();
216 assert(result && "Builder didn't return the right type");
217
218 // If the operation we produce is valid, return it.
219 if (!result->verify())
220 return result;
221 // Otherwise, emit the provided message and return null.
222 inst->emitError(message);
223 inst->eraseFromBlock();
224 return OpPointer<OpTy>();
225 }
226
Uday Bondhugula15984952018-08-01 22:36:12 -0700227 OperationInst *cloneOperation(const OperationInst &srcOpInst) {
228 auto *op = srcOpInst.clone();
Chris Lattner992a1272018-08-07 12:02:37 -0700229 insert(op);
Uday Bondhugula15984952018-08-01 22:36:12 -0700230 return op;
231 }
232
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700233 // Terminators.
234
Chris Lattnerfc647d52018-08-27 21:05:16 -0700235 ReturnInst *createReturn(Location *location, ArrayRef<CFGValue *> operands) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700236 return insertTerminator(ReturnInst::create(location, operands));
Chris Lattner40746442018-07-21 14:32:09 -0700237 }
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700238
Chris Lattnerfc647d52018-08-27 21:05:16 -0700239 BranchInst *createBranch(Location *location, BasicBlock *dest,
Chris Lattner8a9310a2018-08-24 21:13:19 -0700240 ArrayRef<CFGValue *> operands = {}) {
241 return insertTerminator(BranchInst::create(location, dest, operands));
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700242 }
243
Chris Lattnerfc647d52018-08-27 21:05:16 -0700244 CondBranchInst *createCondBranch(Location *location, CFGValue *condition,
Chris Lattner091a6b52018-08-23 14:58:27 -0700245 BasicBlock *trueDest,
246 BasicBlock *falseDest) {
James Molloy4f788372018-07-24 15:01:27 -0700247 return insertTerminator(
Chris Lattner1628fa02018-08-23 14:32:25 -0700248 CondBranchInst::create(location, condition, trueDest, falseDest));
James Molloy4f788372018-07-24 15:01:27 -0700249 }
250
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700251private:
252 template <typename T>
253 T *insertTerminator(T *term) {
254 block->setTerminator(term);
255 return term;
256 }
257
258 CFGFunction *function;
259 BasicBlock *block = nullptr;
260 BasicBlock::iterator insertPoint;
261};
262
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700263/// This class helps build an MLFunction. Statements that are created are
264/// automatically inserted at an insertion point or added to the current
265/// statement block.
266class MLFuncBuilder : public Builder {
267public:
Chris Lattnere787b322018-08-08 11:14:57 -0700268 /// Create ML function builder and set insertion point to the given statement,
269 /// which will cause subsequent insertions to go right before it.
270 MLFuncBuilder(Statement *stmt)
271 // TODO: Eliminate findFunction from this.
272 : Builder(stmt->findFunction()->getContext()) {
273 setInsertionPoint(stmt);
274 }
275
276 MLFuncBuilder(StmtBlock *block, StmtBlock::iterator insertPoint)
277 // TODO: Eliminate findFunction from this.
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700278 : Builder(block->findFunction()->getContext()) {
Chris Lattnere787b322018-08-08 11:14:57 -0700279 setInsertionPoint(block, insertPoint);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700280 }
281
282 /// Reset the insertion point to no location. Creating an operation without a
283 /// set insertion point is an error, but this can still be useful when the
284 /// current insertion point a builder refers to is being removed.
285 void clearInsertionPoint() {
286 this->block = nullptr;
287 insertPoint = StmtBlock::iterator();
288 }
289
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700290 /// Set the insertion point to the specified location.
291 /// Unlike CFGFuncBuilder, MLFuncBuilder allows to set insertion
292 /// point to a different function.
293 void setInsertionPoint(StmtBlock *block, StmtBlock::iterator insertPoint) {
294 // TODO: check that insertPoint is in this rather than some other block.
295 this->block = block;
296 this->insertPoint = insertPoint;
297 }
298
Uday Bondhugula67701712018-08-21 16:01:23 -0700299 /// Set the insertion point to the specified operation, which will cause
300 /// subsequent insertions to go right before it.
Chris Lattnere787b322018-08-08 11:14:57 -0700301 void setInsertionPoint(Statement *stmt) {
Tatiana Shpeismand880b352018-07-31 23:14:16 -0700302 setInsertionPoint(stmt->getBlock(), StmtBlock::iterator(stmt));
303 }
304
Chris Lattnere787b322018-08-08 11:14:57 -0700305 /// Set the insertion point to the start of the specified block.
306 void setInsertionPointToStart(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700307 setInsertionPoint(block, block->begin());
Uday Bondhugula15984952018-08-01 22:36:12 -0700308 }
309
Chris Lattnere787b322018-08-08 11:14:57 -0700310 /// Set the insertion point to the end of the specified block.
311 void setInsertionPointToEnd(StmtBlock *block) {
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700312 setInsertionPoint(block, block->end());
Chris Lattnere787b322018-08-08 11:14:57 -0700313 }
314
Uday Bondhugula84b80952018-08-03 13:22:26 -0700315 /// Get the current insertion point of the builder.
316 StmtBlock::iterator getInsertionPoint() const { return insertPoint; }
317
Chris Lattnereed6c4d2018-08-07 09:12:35 -0700318 /// Create an operation given the fields represented as an OperationState.
319 OperationStmt *createOperation(const OperationState &state);
320
Chris Lattner992a1272018-08-07 12:02:37 -0700321 /// Create operation of specific op type at the current insertion point.
Jacques Pienaarac86d102018-08-03 08:16:37 -0700322 template <typename OpTy, typename... Args>
Chris Lattnerfc647d52018-08-27 21:05:16 -0700323 OpPointer<OpTy> create(Location *location, Args... args) {
Chris Lattner1628fa02018-08-23 14:32:25 -0700324 OperationState state(getContext(), location, OpTy::getOperationName());
Chris Lattner1eb77482018-08-22 19:25:49 -0700325 OpTy::build(this, &state, args...);
326 auto *stmt = createOperation(state);
Chris Lattner992a1272018-08-07 12:02:37 -0700327 auto result = stmt->template getAs<OpTy>();
328 assert(result && "Builder didn't return the right type");
329 return result;
Jacques Pienaarac86d102018-08-03 08:16:37 -0700330 }
331
Chris Lattner7879f842018-09-02 22:01:45 -0700332 /// Create operation of specific op type at the current insertion point. If
333 /// the result is an invalid op (the verifier hook fails), emit an error and
334 /// return null.
335 template <typename OpTy, typename... Args>
336 OpPointer<OpTy> createChecked(const Twine &message, Location *location,
337 Args... args) {
338 OperationState state(getContext(), location, OpTy::getOperationName());
339 OpTy::build(this, &state, args...);
340 auto *stmt = createOperation(state);
341 auto result = stmt->template getAs<OpTy>();
342 assert(result && "Builder didn't return the right type");
343
344 // If the operation we produce is valid, return it.
345 if (!result->verify())
346 return result;
347 // Otherwise, emit the provided message and return null.
348 stmt->emitError(message);
349 stmt->eraseFromBlock();
350 return OpPointer<OpTy>();
351 }
352
Chris Lattnere787b322018-08-08 11:14:57 -0700353 /// Create a deep copy of the specified statement, remapping any operands that
354 /// use values outside of the statement using the map that is provided (
355 /// leaving them alone if no entry is present). Replaces references to cloned
356 /// sub-statements to the corresponding statement that is copied, and adds
357 /// those mappings to the map.
358 Statement *clone(const Statement &stmt,
359 OperationStmt::OperandMapTy &operandMapping) {
360 Statement *cloneStmt = stmt.clone(operandMapping, getContext());
Uday Bondhugula134154e2018-08-06 18:40:34 -0700361 block->getStatements().insert(insertPoint, cloneStmt);
362 return cloneStmt;
Uday Bondhugula84b80952018-08-03 13:22:26 -0700363 }
364
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700365 // Create for statement. When step is not specified, it is set to 1.
Chris Lattnerfc647d52018-08-27 21:05:16 -0700366 ForStmt *createFor(Location *location, ArrayRef<MLValue *> lbOperands,
Tatiana Shpeismande8829f2018-08-24 23:38:14 -0700367 AffineMap *lbMap, ArrayRef<MLValue *> ubOperands,
368 AffineMap *ubMap, int64_t step = 1);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700369
Tatiana Shpeismanc6aa35b2018-08-28 15:26:20 -0700370 /// Create if statement.
371 IfStmt *createIf(Location *location, ArrayRef<MLValue *> operands,
372 IntegerSet *set);
Tatiana Shpeisman565b9642018-07-16 11:47:09 -0700373
374private:
375 StmtBlock *block = nullptr;
376 StmtBlock::iterator insertPoint;
377};
Chris Lattner158e0a3e2018-07-08 20:51:38 -0700378
379} // namespace mlir
380
381#endif