1 //===- Bufferize.cpp - Bufferization utilities ----------------------------===//
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 #include "PassDetail.h"
10 
11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
13 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h"
14 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
15 #include "mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h"
16 #include "mlir/Dialect/Bufferization/Transforms/Passes.h"
17 #include "mlir/Dialect/Func/IR/FuncOps.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/IR/Operation.h"
20 #include "mlir/Pass/PassManager.h"
21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
22 #include "mlir/Transforms/Passes.h"
23 
24 using namespace mlir;
25 using namespace mlir::bufferization;
26 
27 //===----------------------------------------------------------------------===//
28 // BufferizeTypeConverter
29 //===----------------------------------------------------------------------===//
30 
31 static Value materializeToTensor(OpBuilder &builder, TensorType type,
32                                  ValueRange inputs, Location loc) {
33   assert(inputs.size() == 1);
34   assert(inputs[0].getType().isa<BaseMemRefType>());
35   return builder.create<bufferization::ToTensorOp>(loc, type, inputs[0]);
36 }
37 
38 /// Registers conversions into BufferizeTypeConverter
39 BufferizeTypeConverter::BufferizeTypeConverter() {
40   // Keep all types unchanged.
41   addConversion([](Type type) { return type; });
42   // Convert RankedTensorType to MemRefType.
43   addConversion([](RankedTensorType type) -> Type {
44     return MemRefType::get(type.getShape(), type.getElementType());
45   });
46   // Convert UnrankedTensorType to UnrankedMemRefType.
47   addConversion([](UnrankedTensorType type) -> Type {
48     return UnrankedMemRefType::get(type.getElementType(), 0);
49   });
50   addArgumentMaterialization(materializeToTensor);
51   addSourceMaterialization(materializeToTensor);
52   addTargetMaterialization([](OpBuilder &builder, BaseMemRefType type,
53                               ValueRange inputs, Location loc) -> Value {
54     assert(inputs.size() == 1 && "expected exactly one input");
55 
56     if (auto inputType = inputs[0].getType().dyn_cast<MemRefType>()) {
57       // MemRef to MemRef cast.
58       assert(inputType != type && "expected different types");
59       // Unranked to ranked and ranked to unranked casts must be explicit.
60       auto rankedDestType = type.dyn_cast<MemRefType>();
61       if (!rankedDestType)
62         return nullptr;
63       FailureOr<Value> replacement =
64           castOrReallocMemRefValue(builder, inputs[0], rankedDestType);
65       if (failed(replacement))
66         return nullptr;
67       return *replacement;
68     }
69 
70     if (inputs[0].getType().isa<TensorType>()) {
71       // Tensor to MemRef cast.
72       return builder.create<bufferization::ToMemrefOp>(loc, type, inputs[0]);
73     }
74 
75     llvm_unreachable("only tensor/memref input types supported");
76   });
77 }
78 
79 void mlir::bufferization::populateBufferizeMaterializationLegality(
80     ConversionTarget &target) {
81   target.addLegalOp<bufferization::ToTensorOp, bufferization::ToMemrefOp>();
82 }
83 
84 namespace {
85 // In a finalizing bufferize conversion, we know that all tensors have been
86 // converted to memrefs, thus, this op becomes an identity.
87 class BufferizeToTensorOp
88     : public OpConversionPattern<bufferization::ToTensorOp> {
89 public:
90   using OpConversionPattern::OpConversionPattern;
91   LogicalResult
92   matchAndRewrite(bufferization::ToTensorOp op, OpAdaptor adaptor,
93                   ConversionPatternRewriter &rewriter) const override {
94     rewriter.replaceOp(op, adaptor.memref());
95     return success();
96   }
97 };
98 } // namespace
99 
100 namespace {
101 // In a finalizing bufferize conversion, we know that all tensors have been
102 // converted to memrefs, thus, this op becomes an identity.
103 class BufferizeToMemrefOp
104     : public OpConversionPattern<bufferization::ToMemrefOp> {
105 public:
106   using OpConversionPattern::OpConversionPattern;
107   LogicalResult
108   matchAndRewrite(bufferization::ToMemrefOp op, OpAdaptor adaptor,
109                   ConversionPatternRewriter &rewriter) const override {
110     rewriter.replaceOp(op, adaptor.tensor());
111     return success();
112   }
113 };
114 } // namespace
115 
116 void mlir::bufferization::populateEliminateBufferizeMaterializationsPatterns(
117     BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) {
118   patterns.add<BufferizeToTensorOp, BufferizeToMemrefOp>(typeConverter,
119                                                          patterns.getContext());
120 }
121 
122 namespace {
123 struct FinalizingBufferizePass
124     : public FinalizingBufferizeBase<FinalizingBufferizePass> {
125   using FinalizingBufferizeBase<
126       FinalizingBufferizePass>::FinalizingBufferizeBase;
127 
128   void runOnOperation() override {
129     auto func = getOperation();
130     auto *context = &getContext();
131 
132     BufferizeTypeConverter typeConverter;
133     RewritePatternSet patterns(context);
134     ConversionTarget target(*context);
135 
136     populateEliminateBufferizeMaterializationsPatterns(typeConverter, patterns);
137 
138     // If all result types are legal, and all block arguments are legal (ensured
139     // by func conversion above), then all types in the program are legal.
140     //
141     // We also check that the operand types are legal to avoid creating invalid
142     // IR. For example, this prevents
143     // populateEliminateBufferizeMaterializationsPatterns from updating the
144     // types of the operands to a return op without updating the enclosing
145     // function.
146     target.markUnknownOpDynamicallyLegal(
147         [&](Operation *op) { return typeConverter.isLegal(op); });
148 
149     if (failed(applyFullConversion(func, target, std::move(patterns))))
150       signalPassFailure();
151   }
152 };
153 
154 static BufferizationOptions::LayoutMapOption
155 parseLayoutMapOption(const std::string &s) {
156   if (s == "fully-dynamic-layout-map")
157     return BufferizationOptions::LayoutMapOption::FullyDynamicLayoutMap;
158   if (s == "identity-layout-map")
159     return BufferizationOptions::LayoutMapOption::IdentityLayoutMap;
160   if (s == "infer-layout-map")
161     return BufferizationOptions::LayoutMapOption::InferLayoutMap;
162   llvm_unreachable("invalid layout map option");
163 }
164 
165 struct OneShotBufferizePass
166     : public OneShotBufferizeBase<OneShotBufferizePass> {
167   OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {}
168 
169   explicit OneShotBufferizePass(const OneShotBufferizationOptions &options)
170       : options(options) {}
171 
172   void getDependentDialects(DialectRegistry &registry) const override {
173     registry
174         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
175     registerAllocationOpInterfaceExternalModels(registry);
176   }
177 
178   void runOnOperation() override {
179     OneShotBufferizationOptions opt;
180     if (!options) {
181       // Make new bufferization options if none were provided when creating the
182       // pass.
183       opt.allowReturnAllocs = allowReturnAllocs;
184       opt.allowUnknownOps = allowUnknownOps;
185       opt.alwaysAliasingWithDest = alwaysAliasingWithDest;
186       opt.analysisFuzzerSeed = analysisFuzzerSeed;
187       opt.createDeallocs = createDeallocs;
188       opt.functionBoundaryTypeConversion =
189           parseLayoutMapOption(functionBoundaryTypeConversion);
190       opt.printConflicts = printConflicts;
191       opt.testAnalysisOnly = testAnalysisOnly;
192       opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries;
193       opt.unknownTypeConversion = parseLayoutMapOption(unknownTypeConversion);
194 
195       OpFilter::Entry::FilterFn filterFn =
196           [&](Operation *op) {
197             // Filter may be specified via options.
198             if (this->dialectFilter.hasValue())
199               return llvm::is_contained(this->dialectFilter,
200                                         op->getDialect()->getNamespace());
201             // No filter specified: All other ops are allowed.
202             return true;
203           };
204       opt.opFilter.allowOperation(filterFn);
205     } else {
206       opt = *options;
207     }
208 
209     ModuleOp moduleOp = getOperation();
210     if (opt.bufferizeFunctionBoundaries) {
211       if (failed(runOneShotModuleBufferize(moduleOp, opt))) {
212         signalPassFailure();
213         return;
214       }
215     } else {
216       if (failed(runOneShotBufferize(moduleOp, opt))) {
217         signalPassFailure();
218         return;
219       }
220     }
221 
222     if (opt.testAnalysisOnly)
223       return;
224 
225     OpPassManager cleanupPipeline("builtin.module");
226     cleanupPipeline.addPass(createCanonicalizerPass());
227     cleanupPipeline.addPass(createCSEPass());
228     cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
229     (void)runPipeline(cleanupPipeline, moduleOp);
230   }
231 
232 private:
233   llvm::Optional<OneShotBufferizationOptions> options;
234 };
235 } // namespace
236 
237 namespace {
238 struct BufferizationBufferizePass
239     : public BufferizationBufferizeBase<BufferizationBufferizePass> {
240   void runOnOperation() override {
241     BufferizationOptions options = getPartialBufferizationOptions();
242     options.opFilter.allowDialect<BufferizationDialect>();
243 
244     if (failed(bufferizeOp(getOperation(), options)))
245       signalPassFailure();
246   }
247 
248   void getDependentDialects(DialectRegistry &registry) const override {
249     registry
250         .insert<bufferization::BufferizationDialect, memref::MemRefDialect>();
251   }
252 };
253 } // namespace
254 
255 std::unique_ptr<Pass> mlir::bufferization::createBufferizationBufferizePass() {
256   return std::make_unique<BufferizationBufferizePass>();
257 }
258 
259 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() {
260   return std::make_unique<OneShotBufferizePass>();
261 }
262 
263 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass(
264     const OneShotBufferizationOptions &options) {
265   return std::make_unique<OneShotBufferizePass>(options);
266 }
267 
268 std::unique_ptr<OperationPass<func::FuncOp>>
269 mlir::bufferization::createFinalizingBufferizePass() {
270   return std::make_unique<FinalizingBufferizePass>();
271 }
272 
273 //===----------------------------------------------------------------------===//
274 // BufferizableOpInterface-based Bufferization
275 //===----------------------------------------------------------------------===//
276 
277 static bool isaTensor(Type t) { return t.isa<TensorType>(); }
278 
279 /// Return true if the given op has a tensor result or a tensor operand.
280 static bool hasTensorSemantics(Operation *op) {
281   if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
282     bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor);
283     bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor);
284     return hasTensorArg || hasTensorResult;
285   }
286 
287   bool hasTensorResult = any_of(op->getResultTypes(), isaTensor);
288   bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor);
289   return hasTensorResult || hasTensorOperand;
290 }
291 
292 LogicalResult bufferization::bufferizeOp(Operation *op,
293                                          const AnalysisState &analysisState) {
294   // Catch incorrect API usage.
295   assert((analysisState.hasDialectState(
296               func::FuncDialect::getDialectNamespace()) ||
297           !analysisState.getOptions().bufferizeFunctionBoundaries) &&
298          "must use ModuleBufferize to bufferize function boundaries");
299 
300   BufferizationState bufferizationState(analysisState);
301   if (failed(bufferizeOp(op, bufferizationState)))
302     return failure();
303   return success();
304 }
305 
306 namespace {
307 /// A rewriter that keeps track of extra information during bufferization.
308 class BufferizationRewriter : public IRRewriter {
309 public:
310   BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps,
311                         DenseSet<Operation *> &toMemrefOps,
312                         const BufferizationOptions &options,
313                         const OpFilter *opFilter)
314       : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps),
315         options(options), opFilter(opFilter) {}
316 
317 protected:
318   void notifyOperationRemoved(Operation *op) override {
319     IRRewriter::notifyOperationRemoved(op);
320     erasedOps.insert(op);
321     // Erase if present.
322     toMemrefOps.erase(op);
323   }
324 
325   void notifyOperationInserted(Operation *op) override {
326     IRRewriter::notifyOperationInserted(op);
327 
328     // Keep track of to_memref ops.
329     if (isa<ToMemrefOp>(op)) {
330       toMemrefOps.insert(op);
331       return;
332     }
333 
334     // Skip to_tensor ops.
335     if (isa<ToTensorOp>(op))
336       return;
337 
338     // Skip non-tensor ops.
339     if (!hasTensorSemantics(op))
340       return;
341 
342     // Skip ops that are not allowed.
343     if (!options.isOpAllowed(op) || (opFilter && !opFilter->isOpAllowed(op)))
344       return;
345 
346     // Adding new bufferizable ops is not allowed during bufferization. Such ops
347     // would not be analyzed and can lead to surprising behavior.
348     llvm_unreachable(
349         "creating new tensor ops is not allowed during bufferization");
350   }
351 
352 private:
353   /// A set of all erased ops.
354   DenseSet<Operation *> &erasedOps;
355 
356   /// A set of all to_memref ops.
357   DenseSet<Operation *> &toMemrefOps;
358 
359   /// The bufferization options.
360   /// Used for debug modes.
361   LLVM_ATTRIBUTE_UNUSED
362   const BufferizationOptions &options;
363 
364   const OpFilter *opFilter;
365 };
366 } // namespace
367 
368 LogicalResult bufferization::bufferizeOp(Operation *op,
369                                          BufferizationState &bufferizationState,
370                                          const OpFilter *opFilter) {
371   const auto &options = bufferizationState.getOptions();
372   assert(options.unknownTypeConversion !=
373              BufferizationOptions::LayoutMapOption::InferLayoutMap &&
374          "invalid layout map option");
375 
376   // Keep track of to_memref ops.
377   DenseSet<Operation *> toMemrefOps;
378   op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); });
379 
380   // Gather all bufferizable ops in top-to-bottom order.
381   //
382   // We should ideally know the exact memref type of all operands when
383   // bufferizing an op. (This is the case when bufferizing top-to-bottom.)
384   // Otherwise, we have to use a memref type with a fully dynamic layout map to
385   // avoid copies. We are currently missing patterns for layout maps to
386   // canonicalize away (or canonicalize to more precise layouts).
387   SmallVector<Operation *> worklist;
388   op->walk<WalkOrder::PreOrder>([&](Operation *op) {
389     if (hasTensorSemantics(op))
390       worklist.push_back(op);
391   });
392 
393   // Keep track of all erased ops.
394   DenseSet<Operation *> erasedOps;
395 
396   // Bufferize all ops.
397   BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps,
398                                  bufferizationState.getOptions(), opFilter);
399   for (unsigned i = 0; i < worklist.size(); ++i) {
400     Operation *op = worklist[i];
401     // Skip ops that were erased.
402     if (erasedOps.contains(op))
403       continue;
404     // Skip ops that are not bufferizable or not allowed.
405     auto bufferizableOp = options.dynCastBufferizableOp(op);
406     if (!bufferizableOp)
407       continue;
408     if (opFilter && !opFilter->isOpAllowed(op))
409       continue;
410     // Skip ops that no longer have tensor semantics.
411     if (!hasTensorSemantics(op))
412       continue;
413     // Bufferize the op.
414     rewriter.setInsertionPoint(op);
415     if (failed(bufferizableOp.bufferize(rewriter, bufferizationState)))
416       return op->emitError("failed to bufferize op");
417   }
418 
419   // Fold all to_memref(to_tensor(x)) pairs.
420   for (Operation *op : toMemrefOps) {
421     rewriter.setInsertionPoint(op);
422     (void)bufferization::foldToMemrefToTensorPair(rewriter,
423                                                   cast<ToMemrefOp>(op));
424   }
425 
426   /// Check the result of bufferization. Return an error if an op was not
427   /// bufferized, unless partial bufferization is allowed.
428   if (bufferizationState.getOptions().allowUnknownOps)
429     return success();
430 
431   for (Operation *op : worklist) {
432     // Skip ops that are entirely gone.
433     if (erasedOps.contains(op))
434       continue;
435     // Ops that no longer have tensor semantics (because they were updated
436     // in-place) are allowed.
437     if (!hasTensorSemantics(op))
438       continue;
439     // Continue ops that are not allowed.
440     if (!options.isOpAllowed(op))
441       continue;
442     if (opFilter && !opFilter->isOpAllowed(op))
443       continue;
444     // Ops without any uses and no side effects will fold away.
445     if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op))
446       continue;
447     return op->emitError("op was not bufferized");
448   }
449 
450   return success();
451 }
452 
453 namespace {
454 /// This a "no analysis, always copy" AnalysisState. In the absence of an
455 /// analysis, a buffer must be copied each time it is written to. Therefore, all
456 /// OpOperands that bufferize to a memory write must bufferize out-of-place.
457 class AlwaysCopyAnalysisState : public AnalysisState {
458 public:
459   AlwaysCopyAnalysisState(const BufferizationOptions &options)
460       : AnalysisState(options) {
461     // Note: Allocations must be deallocated with a subsequent run of the buffer
462     // deallocation pass.
463     assert(!options.createDeallocs &&
464            "cannot create deallocs with AlwaysCopyBufferizationState");
465   }
466 
467   AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete;
468 
469   virtual ~AlwaysCopyAnalysisState() = default;
470 
471   /// Return `true` if the given OpResult has been decided to bufferize inplace.
472   bool isInPlace(OpOperand &opOperand) const override {
473     // OpOperands that bufferize to a memory write are out-of-place, i.e., an
474     // alloc and copy is inserted.
475     return !bufferizesToMemoryWrite(opOperand);
476   }
477 
478   /// Return true if `v1` and `v2` bufferize to equivalent buffers.
479   bool areEquivalentBufferizedValues(Value v1, Value v2) const override {
480     // There is no analysis, so we do not know if the values are equivalent. The
481     // conservative answer is "false".
482     return false;
483   }
484 
485   /// Return true if `v1` and `v2` may bufferize to aliasing buffers.
486   bool areAliasingBufferizedValues(Value v1, Value v2) const override {
487     // There is no analysis, so we do not know if the values are equivalent. The
488     // conservative answer is "true".
489     return true;
490   }
491 
492   /// Return `true` if the given tensor has undefined contents.
493   bool hasUndefinedContents(OpOperand *opOperand) const override {
494     // There is no analysis, so the conservative answer is "false".
495     return false;
496   }
497 
498   /// Return true if the given tensor (or an aliasing tensor) is yielded from
499   /// the containing block. Also include all aliasing tensors in the same block.
500   bool isTensorYielded(Value tensor) const override {
501     // There is no analysis, so conservatively answer "true".
502     return true;
503   }
504 };
505 } // namespace
506 
507 LogicalResult bufferization::bufferizeOp(Operation *op,
508                                          const BufferizationOptions &options) {
509   AlwaysCopyAnalysisState state(options);
510   return bufferizeOp(op, state);
511 }
512 
513 BufferizationOptions bufferization::getPartialBufferizationOptions() {
514   BufferizationOptions options;
515   options.allowUnknownOps = true;
516   options.createDeallocs = false;
517   options.unknownTypeConversion =
518       BufferizationOptions::LayoutMapOption::IdentityLayoutMap;
519   return options;
520 }
521